<?php

namespace App\Services;

use App\Owner;
use App\Services\common\QueryService;
use App\User;
use App\Waybill;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Uuid;

Class WaybillService
{
    private function conditionQuery(Request $request){
        $waybills = Waybill::filterAuthorities()->with(['owner','wmsCommodities','waybillAuditLogs' => function ($query) {
            return $query->with('user');
        }])->selectRaw('waybills.* ,waybill_on_tops.id top_id ,waybill_on_tops.remark,waybill_on_tops.updated_at top_update')
            ->leftJoin('waybill_on_tops','waybill_on_tops.waybill_id','=','waybills.id')
            ->whereNull('waybill_on_tops.deleted_at')
            ->orderBy('waybill_on_tops.updated_at','desc')
            ->orderBy('waybills.id','desc');
        $columnQueryRules=[
            'waybill_number' => ['like' => ''],
            'carrier_bill' => ['like' => ''],
            'owner_id' => ['multi' => ','],
            'wms_bill_number' => ['like' => ''],
            'origination' => ['like' => ''],
            'destination' => ['like' => ''],
            'created_at_start' => ['alias' => 'created_at' , 'startDate' => ' 00:00:00'],
            'created_at_end' => ['alias' => 'created_at' , 'endDate' => ' 23:59:59'],
            'uriType' => ['alias' => 'type']
        ];
        $waybills = app(QueryService::class)->query($request,$waybills,$columnQueryRules,"waybills");
        return $waybills;
    }

    public function paginate(Request $request){
        $waybills = $this->conditionQuery($request);
        return $waybills->paginate($request->paginate ?? 50);
    }

    public function get(Request $request){
        $waybills = $this->conditionQuery($request);
        return $waybills->get();
    }

    public function some(Request $request){
        return $waybills = Waybill::filterAuthorities()->with(['owner'])->selectRaw('waybills.* ,waybill_on_tops.id top_id ,waybill_on_tops.remark,waybill_on_tops.updated_at top_update')
            ->leftJoin('waybill_on_tops','waybill_on_tops.waybill_id','=','waybills.id')
            ->whereNull('waybill_on_tops.deleted_at')
            ->orderBy('waybill_on_tops.updated_at','desc')
            ->orderBy('waybills.id','desc')
            ->whereIn('waybills.id',explode(',',$request->data))
            ->get();
    }

    public function store(Request $request){
        return DB::transaction(function ()use($request){
            $waybill=new Waybill();
            $inputs = $request->all();
            $inputs['status']='未审核';
            $inputs['waybill_number']=Uuid::uuid1();
            $waybill->fill($inputs);
            if ($request->collect_fee)$waybill->collect_fee=$request->collect_fee;
            $waybill->save();
            $number_id=$waybill->id;
            if ($request->type=='直发车') $waybill_number='BSZF';
            else $waybill_number='BSZX';
            $waybill_number .= date ("ymd").str_pad($number_id>99999?$number_id%99999:$number_id,4,"0",STR_PAD_LEFT);
            $waybill->update(['waybill_number' => $waybill_number ]);
            return $waybill;
        });
    }

    public function find($id){
        return Waybill::query()->find($id);
    }

    public function update(Request $request,$id)
    {
        $waybill = $this->find($id);
        //替换换行符
        if ($request->dispatch_remark) {
            $request->offsetSet('dispatch_remark', str_replace(PHP_EOL, ' ', $request->dispatch_remark));
        }
        if (!$request->destination) $request->offsetSet('destination', $waybill->destination);
        if ($request->destination_city_id && $waybill->destination_city_id != $request->destination_city_id) {
            $city = app(CityService::class)->find($request->destination_city_id);
            if ($city && $city->province_name && (mb_strpos($request->destination, $city->name) === false || mb_strpos($request->destination, $city->province_name) === false)) {
                if (mb_strpos($request->destination, $city->name) === false && mb_strpos($request->destination, $city->province_name) === false) {
                    $request->offsetSet('destination', $city->province_name . $city->name . $request->destination);
                    goto sign;
                }
                if (mb_strpos($request->destination, $city->province_name) === false) {
                    $request->offsetSet('destination', $city->province_name . $request->destination);
                }
                if (mb_strpos($request->destination, $city->name) === false) {
                    $province_name = $city->province_name;
                    $start_index = mb_strpos($request->destination, $city->province_name . '省');
                    if ($start_index === false) $start_index = mb_strpos($request->destination, $city->province_name);
                    else $province_name = $province_name . '省';
                    $strBefore = mb_substr($request->destination, $start_index, mb_strlen($province_name));
                    $strAfter = mb_substr($request->destination, $start_index + mb_strlen($province_name));
                    $request->offsetSet('destination', $strBefore . $city->name . $strAfter);
                }
            }
        }
        sign:
        $waybill->fill($request->input());
        $waybill->update();
        return $waybill;
    }
}
