<?php

namespace App\Http\Controllers;

use App\Components\AsyncResponse;
use App\Imports\ExpressImport;
use App\Imports\OwnerPriceDirectLogisticDetailImport;
use App\Imports\OwnerPriceLogisticDetailImport;
use App\Owner;
use App\OwnerPriceDirectLogistic;
use App\OwnerPriceDirectLogisticCar;
use App\OwnerPriceExpress;
use App\OwnerPriceExpressProvince;
use App\OwnerPriceLogistic;
use App\OwnerPriceLogisticDetail;
use App\OwnerPriceOperation;
use App\OwnerPriceOperationItem;
use App\OwnerPriceSystem;
use App\OwnerStoragePriceModel;
use App\Services\common\BatchUpdateService;
use App\Services\common\ExportService;
use App\Services\common\QueryService;
use App\Services\LogService;
use App\Services\OwnerPriceOperationItemService;
use App\Services\OwnerPriceOperationService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class PriceModelController extends Controller
{
    use AsyncResponse;
    public function storageIndex(Request $request)
    {
        if(!Gate::allows('计费模型-仓储')){ return redirect('denied');  }
        $models = app('OwnerStoragePriceModelService')->paginate($request->input("id"),["unit","owners","timeUnit"]);
        return response()->view('maintenance.priceModel.storage.index',compact("models"));
    }

    public function storageCreate()
    {
        if(!Gate::allows('计费模型-仓储-录入')){ return redirect('denied');  }
        $units = app('UnitService')->getSelection();
        $owners = app("OwnerService")->getIntersectPermitting();
        return response()->view('maintenance.priceModel.storage.create',compact("units","owners"));
    }

    public function storageStore(Request $request)
    {
        if(!Gate::allows('计费模型-仓储-录入')){ return redirect('denied');  }
        $this->storageValidator($request->input())->validate();
        /** @var OwnerStoragePriceModel $model */
        $model = app('OwnerStoragePriceModelService')->create($request->input());
        $result = $model->owners()->sync(explode(",",$request->input("owner_id")));
        app("OwnerService")->refreshRelevance($result["attached"],0);
        LogService::log(__METHOD__,"计费模型-创建仓储计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return response()->redirectTo('maintenance/priceModel/storage')->with('successTip',"创建成功！");
    }

    public function storageEdit($id)
    {
        if(!Gate::allows('计费模型-仓储-编辑')){ return redirect('denied');  }
        $model = app('OwnerStoragePriceModelService')->find($id,["owners"]);
        $units = app('UnitService')->getSelection();
        $owners = app("OwnerService")->getIntersectPermitting();
        return response()->view('maintenance.priceModel.storage.create',compact("units","model","owners"));
    }

    public function storageUpdate(Request $request)
    {
        if(!Gate::allows('计费模型-仓储-编辑')){ return redirect('denied');  }
        $service = app('OwnerStoragePriceModelService');
        $id = request("id");
        $model = $service->find($id);
        $values = [
            "counting_type" => $request->input("counting_type"),
            "name"          => $request->input("name"),
            "using_type"    => $request->input("using_type"),
            "minimum_area"  => $request->input("minimum_area"),
            "price"         => $request->input("price"),
            "discount_type" => $request->input("discount_type"),
            "discount_value"=> $request->input("discount_value"),
            "unit_id"       => $request->input("unit_id"),
            "time_unit_id"  => $request->input("time_unit_id"),
        ];
        if ($model->operation){
            if ($model->operation=='C')$values["operation"]="U";
            $service->update(["id"=>$id],$values);
            $model = new OwnerStoragePriceModel();
            $model->id = $id;
            $result = $model->owners()->sync(explode(",",request("owner_id")));
            app("OwnerService")->refreshRelevance($result["attached"],0);
            app("OwnerService")->refreshRelevance($result["detached"],0,true);
        }else $service->copy($model,$values,explode(",",request("owner_id")));
        return response()->redirectTo('maintenance/priceModel/storage')->with('successTip',"更新成功！");
    }

    public function storageDestroy($id)
    {
        $model = app("OwnerStoragePriceModelService")->find($id);
        if ($model->operation && $model->target_id){
            app("OwnerStoragePriceModelService")->destroy($id);
            $id = $model->target_id;
        }
        app('OwnerStoragePriceModelService')->update(["id"=>$id],["operation"=>"D"]);
        $this->success();
    }

    private function storageValidator(array $params)
    {
        return Validator::make($params,[
            'name'=>['required'],
            'counting_type'=>['required'],
            'using_type'=>['required'],
            'minimum_area'=>['nullable','numeric','min:0'],
            'discount_value'=>['nullable','numeric','min:0'],
            'price.*'=>['required','numeric','min:0'],
            'amount_interval.*'=>['required','integer','min:0'],
            'discount_type'=>['required'],
            'unit_id'=>['required','integer'],
            'time_unit_id'=>['required','integer'],
        ],[
            'required'=>':attribute 为必填项',
            'min'=>':attribute 不得小于0',
            'integer'=>':attribute 未选择',
        ],[
            'name'          =>"名称",
            'counting_type' =>"计费类型",
            'using_type'    =>"用仓类型",
            'minimum_area'  =>"最低起租面积",
            'price.*'       =>"单价",
            'amount_interval.*'=>"数量区间",
            'discount_type' =>"减免类型",
            'discount_value'=>"减免值",
            'unit_id'       =>"单位",
            'time_unit_id'  =>"计时单位",
        ]);
    }

    public function operationIndex(Request $request){
        if(!Gate::allows('计费模型-作业-查询')){ return redirect('denied');  }
        $features = app("FeatureService")->getMapArray();
        OwnerPriceOperation::$features = $features;
        $models = app('OwnerPriceOperationService')->paginate($request->input(),["owners","items.unit"])->append("featureFormat");
        $owners = app("OwnerService")->getIntersectPermitting();
        return response()->view('maintenance.priceModel.operation.index',compact("models","owners"));
    }

    /* 获取出库模型规则 */
    public function getItems(Request $request)
    {
        $this->gate("计费模型-作业-查询");
        /** @var OwnerPriceOperationItemService $service */
        $service = app('OwnerPriceOperationItemService');
        $items = $service->get(["owner_price_operation_id"=>$request->input("id")],["unit"],true)->append("featureFormat");
        $this->success($items);
    }
    /* 修改子规则 */
    public function updateItem(Request $request)
    {
        $this->gate("计费模型-作业-编辑");
        /** @var OwnerPriceOperationItemService $service */
        $service = app('OwnerPriceOperationItemService');
        /** @var \stdClass $item */
        $item = $service->find(request("id"));
        $model = app('OwnerPriceOperationService')->find($item->owner_price_operation_id);
        $obj = ["amount"=>$request->input("amount"),
            "unit_id"=>$request->input("unit_id"),
            "priority"=>$request->input("priority"),
            "unit_price"=>$request->input("unit_price")];
        if ($model->operation){
            if ($model->operation == 'C')$obj["operation"] = "U";
            $service->update(["id"=>request("id")],$obj);
        }else app('OwnerPriceOperationService')->copy($model,[],null,[request("id")=>$obj]);
        $this->success();
    }

    public function createItem(Request $request)
    {
        $this->gate("计费模型-作业-编辑");
        /** @var OwnerPriceOperationItemService $service */
        $service = app('OwnerPriceOperationItemService');
        $id = request("owner_price_operation_id");
        switch ($request->input("strategy")){
            case "起步":
                $c = $service->isExist(["owner_price_operation_id"=>$id,"strategy"=>"起步"]);
                if ($c > 0) $this->error("已存在起步策略");
                break;
            case "默认":
                $c = $service->isExist(["owner_price_operation_id"=>$id,"strategy"=>"默认"]);
                if ($c > 0)$this->error("已存在默认策略");
                break;
        }
        $model = app('OwnerPriceOperationService')->find($id);
        if ($model->operation){
            if ($model->operation == 'C')app('OwnerPriceOperationService')->update(["id"=>$id],["operation"=>"U"]);
        }else {
            $copy = app('OwnerPriceOperationService')->copy($model);
            $request->offsetSet("owner_price_operation_id",$copy->id);
        }
        $data = $service->create($request->input());
        $data->load("unit");
        $this->success($data);
    }
    public function getFeatures()
    {
        $this->success(app("FeatureService")->translationFeature(request("feature")));
    }

    public function addFeature(Request $request)
    {
        if(!Gate::allows('计费模型-作业-编辑')){ return ["success"=>false,"data"=>"无权操作"];  }
        $id = $request->input("id");
        $features = $request->input("features");
        if (!$id || !$features)return ["success"=>false,"data"=>"非法参数"];
        $result = app("FeatureService")->analysisFeature($features);
        $feature = $result["feature"];
        $stack = [];
        if ($feature && ($feature[0]=='|' || $feature[0]=='&'))$feature=substr($feature,1);
        for ($i=0;$i<strlen($feature);$i++){
            if ($feature[$i] == '(')array_unshift($stack,'(');
            if ($feature[$i] == ')'){
                if (count($stack) == 0)return ["success"=>false,"data"=>"组标记错误，起始与结束标记必须对应"];
                array_shift($stack);
            }
        }
        if (count($stack) > 0)return ["success"=>false,"data"=>"组标记错误，起始与结束标记必须对应"];
        $row = app('OwnerPriceOperationItemService')->update(["id"=>$id],["feature"=>$feature]);
        if ($row != 1)return ["success"=>false,"data"=>"影响了“".$row."”行"];
        LogService::log(__METHOD__,"计费模型-修改出库特征",json_encode($request->input()));
        OwnerPriceOperationItem::$features = $result["map"];
        $rule = app('OwnerPriceOperationItemService')->find($id)->append("featureFormat");
        return ["success"=>true,"data"=>["featureFormat"=>$rule->featureFormat,"feature"=>$feature]];
    }

    public function getFeature(Request $request)
    {
        $features = $request->input("features");
        if (!$features)return ["success"=>false,"data"=>"非法参数"];
        $result = app("FeatureService")->analysisFeature($features);
        $feature = $result["feature"];
        $stack = [];
        if ($feature && ($feature[0]=='|' || $feature[0]=='&'))$feature=substr($feature,1);
        for ($i=0;$i<strlen($feature);$i++){
            if ($feature[$i] == '(')array_unshift($stack,'(');
            if ($feature[$i] == ')'){
                if (count($stack) == 0)return ["success"=>false,"data"=>"组标记错误，起始与结束标记必须对应"];
                array_shift($stack);
            }
        }
        if (count($stack) > 0)return ["success"=>false,"data"=>"组标记错误，起始与结束标记必须对应"];
        if ($request->has("isFormat"))$this->success(["feature"=>$feature,"featureFormat"=>app("FeatureService")->formatFeature($result["map"], $feature)]);
        $this->success($feature);
    }

    public function operationDestroy($id)
    {
        $this->gate("计费模型-作业-删除");
        $model = app('OwnerPriceOperationService')->find($id);
        if ($model->operation && $model->target_id){
            app("OwnerPriceOperationService")->destroy($id);
            $id = $model->target_id;
        }
        app('OwnerPriceOperationService')->update(["id"=>$id],["operation"=>"D"]);
        $this->success();
    }

    public function operationCreate(){
        if(!Gate::allows('计费模型-作业-录入')){ return redirect('denied');  }
        $owners = app("OwnerService")->getIntersectPermitting();
        $units = app('UnitService')->getSelection();
        return response()->view('maintenance.priceModel.operation.create',compact("owners","units"));
    }

    public function operationStore(Request $request)
    {
        if(!Gate::allows('计费模型-作业-录入')){ return redirect('denied');  }
        $request->offsetSet("items",json_decode($request->input("items"),true));
        $request->offsetSet("owner_id",explode(',',$request->input("owner_id")));
        $this->operationValidator($request->input())->validate();

        //录入主表
        /** @var OwnerPriceOperationService $service */
        $service = app("OwnerPriceOperationService");
        $ownerPriceOperation = $service->create([
            "operation_type" => $request->input("operation_type"),
            "strategy" => $request->input("strategy"),
            "name" => $request->input("name"),
            "priority" => $request->input("priority"),
            "remark" => $request->input("remark"),
            "feature" => $request->input("feature"),
            "discount_count"    => request("discount_count") ? implode(",",request("discount_count")) : null,
            "total_price"       => request("total_price"),
            "total_discount_price"=> request("total_discount_price") ? implode(",",request("total_discount_price")) : null,
        ]);
        if ($request->input("items")){
            //录入子表
            $insert = [];
            foreach ($request->input("items") as $rule){
                if ($rule["discount_price"] ?? false){
                    foreach ($rule["discount_price"] as $index=>$item){
                        if ($index!=0 && !$item)$rule["discount_price"][$index] = $rule["discount_price"][$index-1];
                    }
                }
                $insert[] = [
                    "owner_price_operation_id" => $ownerPriceOperation->id,
                    "amount" => $rule["amount"],
                    "unit_id" => $rule["unit_id"],
                    "unit_price" => $rule["unit_price"],
                    "strategy" => $rule["strategy"],
                    "feature" => $rule["feature"],
                    "priority" => $rule["priority"],
                    "discount_price" =>  implode(",",$rule["discount_price"]),
                ];
            }
            $service->insertItem($insert);
        }
        //录入中间表
        /** @var OwnerPriceOperation $ownerPriceOperation */
        if ($request->input("owner_id")){
            $result = $ownerPriceOperation->owners()->sync($request->input("owner_id"));
            app("OwnerService")->refreshRelevance($result["attached"],1);
            app("OwnerService")->refreshRelevance($result["detached"],1,true);
        }
        LogService::log(__METHOD__,"计费模型-录入作业计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return response()->redirectTo("maintenance/priceModel/operation")->with("successTip","创建“".$request->input("name")."”成功");
    }

    public function operationEdit($id)
    {
        if(!Gate::allows('计费模型-作业-编辑')){ return redirect('denied');  }
        $model = app('OwnerPriceOperationService')->find($id,["items"]);
        $owners = app("OwnerService")->getIntersectPermitting();
        $units = app('UnitService')->getSelection();
        return response()->view('maintenance.priceModel.operation.create',compact("owners","units","model"));
    }

    public function operationUpdate($id,Request $request)
    {
        if(!Gate::allows('计费模型-作业-编辑')){ return redirect('denied');  }
        $request->offsetSet("items",json_decode($request->input("items"),true));
        $request->offsetSet("owner_id",explode(',',$request->input("owner_id")));
        $this->operationValidator($request->input(),$id)->validate();

        /** @var OwnerPriceOperationService $service */
        $service = app("OwnerPriceOperationService");

        /** @var \stdClass $model */
        $model = $service->find($id);
        $obj = ["name" => $request->input("name"),
            "priority" => $request->input("priority"),
            "remark" => $request->input("remark"),
            "feature" => $request->input("feature"),
            "discount_count"    => implode(",",request("discount_count")),
            "total_price"       => request("total_price"),
            "total_discount_price"=> implode(",",request("total_discount_price")) ?? null,
        ];
        if ($model->operation){
            $service->findUpdate($model,$obj);
            $service->destroyItem($id);
            if ($request->input("items")){
                //录入子表
                $insert = [];
                foreach ($request->input("items") as $rule){
                    $insert[] = [
                        "owner_price_operation_id" => $model->id,
                        "amount" => $rule["amount"],
                        "unit_id" => $rule["unit_id"],
                        "unit_price" => $rule["unit_price"],
                        "strategy" => $rule["strategy"],
                        "feature" => $rule["feature"],
                        "priority" => $rule["priority"],
                        "discount_price" => implode(",",$rule["discount_price"]) ?? null,
                    ];
                }
                $service->insertItem($insert);
            }
            //录入中间表
            /** @var OwnerPriceOperation $model */
            if ($request->input("owner_id")){
                $result = $model->owners()->sync(request("owner_id"));
                app("OwnerService")->refreshRelevance($result["attached"],1);
                app("OwnerService")->refreshRelevance($result["detached"],1,true);
            }
        }else $service->copy($model,$obj,request("owner_id"),request("items"),false);
        LogService::log(__METHOD__,"计费模型-修改作业计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return response()->redirectTo("maintenance/priceModel/operation")->with("successTip","修改“".$request->input("name")."”成功");
    }

    private function operationValidator(array $params, $id= null)
    {
        return Validator::make($params,[
            'operation_type'=>['required'],
            'owner_id'=>[function ($attribute, $value, $fail)use($params,$id) {
                if ($params["strategy"] == '默认'){
                    $owners = Owner::query()->whereIn("id",$value)->withCount(["ownerPriceOperations"=>function($query)use($params,$id){
                        if ($id)$query->where('id',"!=",$id);
                        $query->where("strategy","默认")->where("operation_type",$params["operation_type"]);
                    }])->get();
                    $err = [];
                    foreach ($owners as $owner){
                        if ($owner->owner_price_operations_count > 0)$err[] = $owner->name;
                    }
                    if (count($err)>0)$fail("(".implode(',',$err).') 已经绑定'.$params["operation_type"].'的默认策略');
                }
            }],
            'strategy'=>['required'],
            'name'=>['required'],
            'priority'=>['sometimes','required','integer','min:0','max:100'],
            'items.*.strategy'=>['required'],
            'items.*.amount'=>["required","integer"],
            'items.*.unit_id'=>['required','integer'],
            'items.*.unit_price'=>['required','numeric',"min:0"],
        ],[
            'required'=>':attribute 为必填项',
            'min'=>':attribute 不得小于0',
            'integer'=>':attribute 必须为整数',
            'numeric'=>':attribute 必须为数字',
            'max'=>':attribute 超出最大值',
            'required_if'=>':attribute 操作类型为出库时不得为空',
        ],[
            'operation_type' =>"操作类型",
            'strategy'    =>"计费策略",
            'name'  =>"名称",
        ]);
    }

    public function expressIndex(Request $request){
        if(!Gate::allows('计费模型-快递-查询')){ return redirect('denied');  }
        $models = app('OwnerPriceExpressService')->paginate($request->input("id"));
        return response()->view('maintenance.priceModel.express.index',compact("models"));
    }

    public function expressGetDetail(Request $request)
    {
        $this->gate("计费模型-快递-查询");
        $model = new OwnerPriceExpress();
        $model->id = $request->input("id");
        $model->load("details.province");
        $this->success($model->details);
    }

    public function expressUpdateDetail(Request $request)
    {
        $this->gate("计费模型-快递-编辑");
        $detail = $request->input("detail");
        $values = ["additional_weight_price" => $detail["additional_weight_price"],
                    "initial_weight_price" => $detail["initial_weight_price"],
                  ];
        if ($detail["id"]){
            /** @var \stdClass $item */
            $item = OwnerPriceExpressProvince::query()->with("ownerPriceExpress")->find($detail["id"]);
            if ($item->ownerPriceExpress->operation){
                app('OwnerPriceExpressService')->updateDetail(["id"=>$detail["id"]],$values);
            }else app("OwnerPriceExpressService")->copy($item->ownerPriceExpress,[],null,null,[$detail["id"]=>$values]);
        }else{
            $row = app('OwnerPriceExpressService')->isExistDetail(["owner_price_express_id"=>request("id"),"province_id"=>$detail["province_id"]]);
            if ($row>0)$this->error("已存在该省份计费模型");
            $values["province_id"]=$detail["province_id"];
            $model = app('OwnerPriceExpressService')->find(request("id"));
            if ($model->operation){
                $values["owner_price_express_id"]=request("id");
            }else{
                $model = app("OwnerPriceExpressService")->copy($model);
                $values["owner_price_express_id"]=$model->id;
            }
            /** @var OwnerPriceExpressProvince $detail */
            $detail = app('OwnerPriceExpressService')->createDetail($values);
            $detail->load("province");
        }
        LogService::log(__METHOD__,"计费模型-修改快递计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        $this->success($detail);
    }

    public function expressDestroyDetail()
    {
        $this->gate("计费模型-快递-删除");
        if (!request("id"))$this->error("非法参数");
        /** @var \stdClass $item */
        $item = OwnerPriceExpressProvince::query()->with("ownerPriceExpress")->find(request("id"));
        if ($item->ownerPriceExpress->operation){
            app("OwnerPriceExpressService")->destroyDetail(request("id"));
        }else{
            $model = app("OwnerPriceExpressService")->copy($item->ownerPriceExpress);
            OwnerPriceExpressProvince::query()->where("owner_price_express_id",$model->id)
                ->where("province_id",$item->province_id)->delete();
        }
        $this->success();
    }

    public function expressImport(){
        $this->gate("计费模型-快递-录入");
        $this->importExcel(new ExpressImport(request("id") ? app('OwnerPriceExpressService')->find(request("id"),["details"]) : null));
    }

    public function expressCreate(){
        if(!Gate::allows('计费模型-快递-录入')){ return redirect('denied');  }
        $logistics = app("LogisticService")->getSelection();
        $owners = app("OwnerService")->getIntersectPermitting();
        return response()->view('maintenance.priceModel.express.create',compact("logistics","owners"));
    }

    public function expressStore(Request $request)
    {
        if(!Gate::allows('计费模型-快递-录入')){ return redirect('denied');  }
        $request->offsetSet("owner_id",explode(",",$request->input("owner_id")));
        $request->offsetSet("logistic_id",explode(",",$request->input("logistic_id")));
        $this->expressValidator($request->input())->validate();
        /** @var OwnerPriceExpress $model */
        $model = app("OwnerPriceExpressService")->create([
            "name" => $request->input("name"),
            "initial_weight" => $request->input("initial_weight"),
            "additional_weight" => $request->input("additional_weight"),
        ]);
        $result = $model->owners()->sync($request->input("owner_id"));
        app("OwnerService")->refreshRelevance($result["attached"],2);
        app("OwnerService")->refreshRelevance($result["detached"],2,true);
        $model->logistics()->sync($request->input("logistic_id"));
        LogService::log(__METHOD__,"计费模型-录入快递计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return response()->redirectTo("maintenance/priceModel/express")->with("successTip","录入“".$request->input("name")."”成功");
    }

    public function expressEdit($id)
    {
        if(!Gate::allows('计费模型-快递-编辑')){ return redirect('denied');  }
        /** @var OwnerPriceExpress $model */
        $model = app('OwnerPriceExpressService')->find($id)->append(["owner_id","logistic_id"]);
        $owners = app("OwnerService")->getIntersectPermitting();
        $logistics = app('LogisticService')->getSelection();
        return response()->view('maintenance.priceModel.express.create',compact("owners","logistics","model"));
    }

    public function expressUpdate($id,Request $request)
    {
        if(!Gate::allows('计费模型-快递-编辑')){ return redirect('denied');  }
        $request->offsetSet("owner_id",explode(",",$request->input("owner_id")));
        $request->offsetSet("logistic_id",explode(",",$request->input("logistic_id")));
        $model = app("OwnerPriceExpressService")->find($id);
        $values = ["name" => $request->input("name"),
            "initial_weight" => $request->input("initial_weight"),
            "additional_weight" => $request->input("additional_weight"),
        ];
        if ($model->operation){
            $this->expressValidator($request->input(),$id)->validate();
            /** @var OwnerPriceExpress $model */
            app("OwnerPriceExpressService")->update(["id"=>$id],$values);
            $model = new OwnerPriceExpress();
            $model->id = $id;
            $result = $model->owners()->sync($request->input("owner_id"));
            app("OwnerService")->refreshRelevance($result["attached"],2);
            app("OwnerService")->refreshRelevance($result["detached"],2,true);
            $model->logistics()->sync($request->input("logistic_id"));
        }else app("OwnerPriceExpressService")->copy($model,$values,$request->input("owner_id"),$request->input("logistic_id"));
        LogService::log(__METHOD__,"计费模型-修改快递计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return response()->redirectTo("maintenance/priceModel/express")->with("successTip","修改“".$request->input("name")."”成功");
    }

    private function expressValidator(array $params, $id=null)
    {
        return Validator::make($params,[
            'name'=>['required'],
            'initial_weight'=>['required','numeric','min:0'],
            'additional_weight'=>['required','numeric','min:0'],
            'owner_id'=>[function ($attribute, $value, $fail)use($id,$params) {
                $owners = app("OwnerPriceExpressService")->getExistOwnerName($value,$params["logistic_id"] ?? [],$id);
                if ($owners)$fail("(".implode(',',$owners).') 已经绑定计费模型');
            }],
            'amount_interval.*'=>['required','integer','min:0'],
            'weight_interval.*'=>['array'],
            'weight_interval.*.*'=>['required','numeric','min:0'],
            'items.*.province_id'=>['required'],
            'items.*.additional_weight_price.*.*'=>['required','numeric',"min:0"],
            'items.*.initial_weight_price.*.*'=>['required','numeric',"min:0"],
        ],[
            'required'=>':attribute 为必填项',
            'unique' => ':attribute 已存在',
            'min' => ':attribute 不得小于0',
        ],[
            'name' =>"名称",
            'initial_weight'  =>"首重",
            'additional_weight'  =>"续重",
            'amount_interval.*'  =>"数量区间",
            'weight_interval.*'  =>"重量区间",
            'weight_interval.*.*'  =>"重量区间",
            "items.*.province_id"=>"省份",
            "items.*.additional_weight_price.*.*"=>"续重价格",
            "items.*.initial_weight_price.*.*"=>"首重价格",
        ]);
    }

    public function expressDestroy($id)
    {
        $this->gate("计费模型-快递-删除");
        $model = app("OwnerPriceExpressService")->find($id);
        if ($model->operation && $model->target_id){
            app("OwnerPriceExpressService")->destroy($id);
            $id = $model->target_id;
        }
        app("OwnerPriceExpressService")->update(["id"=>$id],["operation"=>"D"]);
        $this->success();
    }

    public function logisticIndex(Request $request)
    {
        if(!Gate::allows('计费模型-物流-查询')){ return redirect('denied');  }
        $models = app("OwnerPriceLogisticService")->paginate($request->input("id"))->append(["unit_range_json","other_unit_range_json"]);
        return response()->view('maintenance.priceModel.logistic.index',compact("models"));
    }

    public function logisticCreate()
    {
        if(!Gate::allows('计费模型-物流-录入')){ return redirect('denied');  }
        $owners = app("OwnerService")->getIntersectPermitting();
        $logistics = app('LogisticService')->getSelection();
        $units = app('UnitService')->getSelection();
        return response()->view('maintenance.priceModel.logistic.create',compact("owners","logistics","units"));
    }

    public function logisticStore(Request $request)
    {
        if(!Gate::allows('计费模型-物流-录入')){ return redirect('denied');  }
        $request->offsetSet("owner_id",explode(",",$request->input("owner_id")));
        $request->offsetSet("logistic_id",explode(",",$request->input("logistic_id")));
        $this->logisticValidator($request->input())->validate();
        /** @var OwnerPriceLogistic $model */
        $model = app("OwnerPriceLogisticService")->create([
            "name" => $request->input("name"),
            "pick_up_price" => $request->input("pick_up_price"),
            "fuel_price" => $request->input("fuel_price"),
            "service_price" => $request->input("service_price"),
            "unit_id" => $request->input("unit_id"),
            "unit_range" => $request->input("unit_range"),
            "other_unit_id" => $request->input("other_unit_id"),
            "other_unit_range" => $request->input("other_unit_range"),
        ]);
        $result = $model->owners()->sync($request->input("owner_id"));
        app("OwnerService")->refreshRelevance($result["attached"],3);
        app("OwnerService")->refreshRelevance($result["detached"],3,true);
        $model->logistics()->sync($request->input("logistic_id"));
        LogService::log(__METHOD__,"计费模型-录入物流计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return response()->redirectTo("maintenance/priceModel/logistic")->with("successTip","创建“".$request->input("name")."”成功");
    }

    public function logisticEdit($id)
    {
        if(!Gate::allows('计费模型-物流-编辑')){ return redirect('denied');  }
        $owners = app("OwnerService")->getIntersectPermitting();
        $logistics = app('LogisticService')->getSelection(['id','name'],'物流');
        $units = app('UnitService')->getSelection();
        $model = app("OwnerPriceLogisticService")->find($id)->append(["owner_id","logistic_id"]);
        return response()->view('maintenance.priceModel.logistic.create',compact("owners","logistics","units","model"));
    }

    public function logisticUpdate($id, Request $request)
    {
        if(!Gate::allows('计费模型-物流-编辑')){ return redirect('denied');  }
        $request->offsetSet("owner_id",explode(",",$request->input("owner_id")));
        $request->offsetSet("logistic_id",explode(",",$request->input("logistic_id")));
        $this->logisticValidator($request->input(),$id)->validate();
        $values = ["name" => $request->input("name"),
            "pick_up_price" => $request->input("pick_up_price"),
            "fuel_price" => $request->input("fuel_price"),
            "service_price" => $request->input("service_price"),
            "unit_id" => $request->input("unit_id"),
            "unit_range" => $request->input("unit_range"),
            "other_unit_id" => $request->input("other_unit_id"),
            "other_unit_range" => $request->input("other_unit_range"),
        ];
        $model = app("OwnerPriceLogisticService")->find($id);
        if ($model->operation){
            app("OwnerPriceLogisticService")->update(["id"=>$id],$values);
            $model = new OwnerPriceLogistic();
            $model->id = $id;
            $result = $model->owners()->sync($request->input("owner_id"));
            app("OwnerService")->refreshRelevance($result["attached"],3);
            app("OwnerService")->refreshRelevance($result["detached"],3,true);
            $model->logistics()->sync($request->input("logistic_id"));
        }else app("OwnerPriceLogisticService")->copy($model,$values,$request->input("owner_id"),$request->input("logistic_id"));

        LogService::log(__METHOD__,"计费模型-修改物流计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return response()->redirectTo("maintenance/priceModel/logistic")->with("successTip","修改“".$request->input("name")."”成功");
    }

    public function logisticGetDetail(Request $request)
    {
        $this->gate("计费模型-物流-查询");
        $model = new OwnerPriceLogistic();
        $model->id = $request->input("id");
        $model->load(["details"=>function($query){
            /** @var Builder $query */
            $query->with(["unit","province","city"]);
        }]);
        $this->success($model->details);
    }

    public function expressExport($id)
    {
        if(!Gate::allows('计费模型-快递-查询')){ return ["success"=>false,"data"=>"无权操作"];  }
        $model = app("OwnerPriceExpressService")->find($id,[
            "owners","logistics","details"=>function($query){
                /** @var Builder $query */
                $query->with("province");
            }]);
        $row = ["客户","首重","续重","承运商"];
        $list = [[
            implode(",",array_column($model->owners->toArray(),"name")),
            $model->initial_weight,
            $model->additional_weight,
            implode(",",array_column($model->logistics->toArray(),"name")),
        ],[
            "价格名称","省","首重价格","续重价格",
        ]];
        foreach ($model->details as $detail){
            $list[] = [
                $model->name,
                $detail->province ? $detail->province->name : '',
                $detail->initial_weight_price,
                $detail->additional_weight_price,
            ];
        }
        return app(ExportService::class)->json($row,$list,"快递计费模型");
    }

    public function logisticImport(Request $request)
    {
        if(!Gate::allows('计费模型-物流-录入')){ return ["success"=>false,"data"=>"无权操作"];  }
        $fileSuffix=$request->file('file')->getClientOriginalExtension();
        if ($fileSuffix != 'xlsx' && $fileSuffix != 'xls' && $fileSuffix != 'csv')
            return ['success'=>false,'data'=>'不支持该文件类型'];
        ini_set('max_execution_time',2500);
        ini_set('memory_limit','1526M');
        $fileSuffix = ucwords($fileSuffix);

        if (!$request->has("id")){
            Excel::import(new OwnerPriceLogisticDetailImport(null),$request->file('file')->path(),null,$fileSuffix);
        }else{
            /** @var OwnerPriceLogistic $model */
            $model = app('OwnerPriceLogisticService')->find($request->input("id"),["unit","otherUnit","details"]);
            Excel::import(new OwnerPriceLogisticDetailImport($model),$request->file('file')->path(),null,$fileSuffix);
        }

        if (Cache::has('logistic'))return Cache::pull('logistic');

        return ["success"=>false,"data"=>"导入发生错误，数据无响应"];
    }

    public function logisticExport($id)
    {
        $this->gate("计费模型-物流-查询");
        $model = app("OwnerPriceLogisticService")->find($id,[
            "owners","logistics","unit","otherUnit","details"=>function($query){
                /** @var Builder $query */
                $query->with(["province","unit","city"]);
            }]);
        $row = ["客户","价格名称",
            "单位一区间/".($model->unit ? $model->unit->name : ''),
            "单位二区间/".($model->otherUnit ? $model->otherUnit->name : ''),
            "提货费","燃油附加费","信息服务费","创建时间","承运商"];
        $range = "";
        foreach (explode(",",$model->unit_range) as $str){
            $range .= $str."\r\n";
        }
        $otherRange = "";
        foreach (explode(",",$model->other_unit_range) as $str){
            $otherRange .= $str."\r\n";
        }
        $list = [[
            implode(",",array_column($model->owners->toArray(),"name")),
            $model->name,
            $range,
            $otherRange,
            $model->pick_up_price,
            $model->fuel_price,
            $model->service_price,
            $model->created_at,
            implode(",",array_column($model->logistics->toArray(),"name")),
        ],[
            "单位","区间","省份","市","单价","送货费","起始计费","起始计数","费率"
        ]];
        foreach ($model->details as $detail){
            $list[] = [
                $detail->unit ? $detail->unit->name : '',
                $detail->range,
                $detail->province ? $detail->province->name : '',
                $detail->city ? $detail->city->name : '',
                $detail->unit_price,
                $detail->delivery_fee,
                $detail->initial_fee,
                $detail->initial_amount,
                $detail->rate ? $detail->rate."%" : '',
            ];
        }
        return app(ExportService::class)->json($row,$list,"物流计费模型");
    }

    public function logisticUpdateDetail(Request $request)
    {
        $this->gate("计费模型-物流-编辑");
        $detail = $request->input("detail");
        if ($detail["id"]){
            $item = OwnerPriceLogisticDetail::query()->with("ownerPriceLogistic")->first();
            $obj = [
                "unit_price" => $detail["unit_price"],
                "delivery_fee" => $detail["delivery_fee"],
                "initial_fee" => $detail["initial_fee"],
                "initial_amount" => $detail["initial_amount"],
                "rate" => $detail["rate"],
            ];
            if ($item->ownerPriceLogistic->operation){
                app('OwnerPriceLogisticService')->updateDetail(["id"=>$detail["id"]],$obj);
            }else app('OwnerPriceLogisticService')->copy($item->ownerPriceLogistic,[],null,null,[$detail["id"]=>$obj]);
        }else{
            $row = app('OwnerPriceLogisticService')->isExistDetail([
                "owner_price_logistic_id"=>$request->input("id"),
                "unit_id"=>$detail["unit_id"],
                "range"=>$detail["range"],
                "province_id"=>$detail["province_id"],
                "city_id"=>$detail["city_id"],
            ]);
            if ($row>0)$this->error("已存在该计费模型");
            $model = app('OwnerPriceLogisticService')->find(request("id"));
            $id = request("id");
            if(!$model->operation)$id = app('OwnerPriceLogisticService')->copy($model)->id;
            /** @var OwnerPriceExpressProvince $detail */
            $detail = app('OwnerPriceLogisticService')->createDetail([
                "owner_price_logistic_id"=>$id,
                "unit_id"=>$detail["unit_id"],
                "range"=>$detail["range"],
                "province_id"=>$detail["province_id"],
                "city_id"=>$detail["city_id"],
                "unit_price" => $detail["unit_price"],
                "delivery_fee" => $detail["delivery_fee"],
                "initial_fee" => $detail["initial_fee"],
                "initial_amount" => $detail["initial_amount"],
                "rate" => $detail["rate"],
            ]);
            $detail->load("province","unit","city");
        }
        LogService::log(__METHOD__,"计费模型-修改物流计费详情",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        $this->success($detail);
    }

    public function logisticDestroyDetail(Request $request)
    {
        $this->gate("计费模型-物流-删除");
        $id = $request->input("id");
        if (!$id) $this->error("非法参数");
        /** @var \stdClass $item */
        $item = OwnerPriceLogisticDetail::query()->with("ownerPriceLogistic")->find($id);
        if ($item->ownerPriceLogistic->operation){
            app("OwnerPriceLogisticService")->destroyDetail($id);
        }else{
            $model = app("OwnerPriceLogisticService")->copy($item->ownerPriceLogistic);
            OwnerPriceLogisticDetail::query()->where("owner_price_logistic_id",$model->id)
                ->where("unit_id",$item->unit_id)->where("range",$item->range)
                ->where("province_id",$item->province_id)->where("city_id",$item->city_id)
                ->delete();
        }
        LogService::log(__METHOD__,"计费模型-删除物流计费详情",$id);
        $this->success();
    }
    public function logisticDestroy($id)
    {
        $this->gate("计费模型-物流-删除");
        if (!$id)$this->error("非法参数");
        $model = app("OwnerPriceLogisticService")->find($id);
        if ($model->operation && $model->target_id){
            app("OwnerPriceLogisticService")->destroy($id);
            $id = $model->target_id;
        }
        app("OwnerPriceLogisticService")->update(["id"=>$id],["operation"=>"D"]);
        $this->success();
    }

    private function logisticValidator(array $params,$id = null)
    {
        return Validator::make($params,[
            'name'=>['required',$id?"unique:owner_price_logistics,name,$id":'unique:owner_price_logistics,name'],
            'pick_up_price'=>['nullable','numeric','min:0'],
            'fuel_price'=>['nullable','numeric','min:0'],
            'service_price'=>['nullable','numeric','min:0'],
            'unit_id'=>['required'],
            'unit_range'=>['required',function ($attribute, $value, $fail) {
                $bool = app("OwnerPriceLogisticService")->checkRange($value);
                if (!$bool)$fail("格式错误,值必须为连续的且最后一个值不允许封闭");
            }],
            'other_unit_id'=>['required'],
            'other_unit_range'=>['required',function ($attribute, $value, $fail) {
                $bool = app("OwnerPriceLogisticService")->checkRange($value);
                if (!$bool)$fail("格式错误,值必须为连续的且最后一个值不允许封闭");
            }],
            'owner_id'=>[function ($attribute, $value, $fail)use($id,$params) {
                $owners = app("OwnerPriceExpressService")->getExistOwnerName($value,$params["logistic_id"] ?? [],$id,"ownerPriceLogistics");
                if ($owners)$fail("(".implode(',',$owners).') 已经绑定计费模型');
            }],
            'items.*.unit_id'=>['sometimes','required'],
            'items.*.range'=>['sometimes','required'],
            'items.*.province_id'=>['sometimes','required'],
            'items.*.city_id'=>['sometimes','required'],
            'items.*.unit_price'=>['sometimes','nullable','numeric',"min:0"],
            'items.*.delivery_fee'=>['sometimes','nullable','numeric',"min:0"],
            'items.*.initial_fee'=>['sometimes','nullable','numeric',"min:0"],
            'items.*.initial_amount'=>['sometimes','nullable','numeric',"min:0"],
            'items.*.rate'=>['sometimes','nullable','numeric',"min:0"],
        ],[
            'required'=>':attribute 为必填项',
            'unique' => ':attribute 已存在',
            'numeric' => ':attribute 必须为数字',
            'min' => ':attribute 不得为负',
        ],[
            'name' =>"名称",
            'pick_up_price'  =>"提货费",
            'fuel_price'  =>"燃油附加费",
            'service_price'  =>"信息服务费",
            'unit_id'  =>"单位一",
            'unit_range'  =>"区间值",
            'other_unit_id'  =>"单位二",
            'other_unit_range'  =>"区间值",
            'items.*.unit_id'=>"单位",
            'items.*.range'=>"区间",
            'items.*.province_id'=>"省份",
            'items.*.city_id'=>"城市",
            'items.*.unit_price'=>"单价",
            'items.*.delivery_fee'=>"送货费",
            'items.*.initial_fee'=>"起始计费",
            'items.*.initial_amount'=>"起始计数",
            'items.*.rate'=>"费率",
        ]);
    }

    public function directLogisticIndex(Request $request){
        if(!Gate::allows('计费模型-直发-查询')){ return redirect('denied');  }
        $models = app("OwnerPriceDirectLogisticService")->paginate($request->input("id"));
        return response()->view('maintenance.priceModel.directLogistic.index',compact("models"));
    }

    public function directLogisticCreate(){
        if(!Gate::allows('计费模型-直发-录入')){ return redirect('denied');  }
        $owners = app("OwnerService")->getIntersectPermitting();
        return response()->view('maintenance.priceModel.directLogistic.create',compact("owners"));
    }

    public function directLogisticStore(Request $request)
    {
        if(!Gate::allows('计费模型-直发-录入')){ return redirect('denied');  }
        $request->offsetSet("owner_id",explode(",",$request->input("owner_id")));
        $this->directLogisticValidator($request->input())->validate();
        /** @var OwnerPriceDirectLogistic $model */
        $model = app("OwnerPriceDirectLogisticService")->create([
            "name" => $request->input("name"),
            "base_km" => $request->input("base_km"),
        ]);
        $result = $model->owners()->sync($request->input("owner_id"));
        app("OwnerService")->refreshRelevance($result["attached"],4);
        app("OwnerService")->refreshRelevance($result["detached"],4,true);
        LogService::log(__METHOD__,"计费模型-录入直发车计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return response()->redirectTo("maintenance/priceModel/directLogistic")->with("successTip","创建“".$request->input("name")."”成功");
    }

    public function directLogisticDestroy($id)
    {
        $this->gate("计费模型-直发-删除");
        $model = app("OwnerPriceDirectLogisticService")->find($id);
        if($model->operation && $model->target_id){
            app("OwnerPriceDirectLogisticService")->destroy($id);
            $id = $model->target_id;
        }
        app("OwnerPriceDirectLogisticService")->update(["id"=>$id],["operation"=>"D"]);
        $this->success();
    }

    public function directLogisticEdit($id)
    {
        if(!Gate::allows('计费模型-直发-编辑')){ return redirect('denied');  }
        $owners = app("OwnerService")->getIntersectPermitting();
        $model = app("OwnerPriceDirectLogisticService")->find($id)->append("owner_id");
        return response()->view('maintenance.priceModel.directLogistic.create',compact("model","owners"));
    }

    public function directLogisticUpdate($id, Request $request)
    {
        if(!Gate::allows('计费模型-直发-编辑')){ return redirect('denied');  }
        $request->offsetSet("owner_id",explode(",",$request->input("owner_id")));
        $this->directLogisticValidator($request->input(),$id)->validate();
        $model = app("OwnerPriceDirectLogisticService")->find($id);
        $values = [
            "name" => $request->input("name"),
            "base_km" => $request->input("base_km"),
        ];
        if ($model->operation){
            app("OwnerPriceDirectLogisticService")->update(["id"=>$id],$values);
            $model = new OwnerPriceDirectLogistic();
            $model->id = $id;
            $result = $model->owners()->sync($request->input("owner_id"));
            app("OwnerService")->refreshRelevance($result["attached"],4);
            app("OwnerService")->refreshRelevance($result["detached"],4,true);
        }else app("OwnerPriceDirectLogisticService")->copy($model,$values,request("owner_id"));
        LogService::log(__METHOD__,"计费模型-修改直发车计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return response()->redirectTo("maintenance/priceModel/directLogistic")->with("successTip","修改“".$request->input("name")."”成功");
    }

    public function directLogisticGetDetail(Request $request)
    {
        $this->gate("计费模型-直发-查询");
        $model = new OwnerPriceDirectLogistic();
        $model->id = $request->input("id");
        $model->load(["details"=>function($query){
            /** @var Builder $query */
            $query->with("carType");
        }]);
        $this->success($model->details);
    }

    public function directLogisticImport(Request $request)
    {
        if(!Gate::allows('计费模型-直发-录入')){ return ["success"=>false,"data"=>"无权操作"];  }
        $fileSuffix=$request->file('file')->getClientOriginalExtension();
        if ($fileSuffix != 'xlsx' && $fileSuffix != 'xls' && $fileSuffix != 'csv')
            return ['success'=>false,'data'=>'不支持该文件类型'];
        ini_set('max_execution_time',2500);
        ini_set('memory_limit','1526M');
        $fileSuffix = ucwords($fileSuffix);

        if (!$request->has("id")){
            Excel::import(new OwnerPriceDirectLogisticDetailImport(null),$request->file('file')->path(),null,$fileSuffix);
        }else{
            $model = new OwnerPriceDirectLogistic();
            $model->id = $request->input("id");
            $model->load("details");
            Excel::import(new OwnerPriceDirectLogisticDetailImport($model),$request->file('file')->path(),null,$fileSuffix);
        }

        if (Cache::has('directLogistic'))return Cache::pull('directLogistic');
        return ["success"=>false,"data"=>"导入发生错误，数据无响应"];
    }

    public function directLogisticUpdateDetail(Request $request)
    {
        $this->gate("计费模型-直发-编辑");
        $detail = $request->input("detail");
        if ($detail["id"]){
            /** @var \stdClass $item */
            $item = OwnerPriceDirectLogisticCar::query()->with("ownerPriceDirectLogistic")->find($detail["id"]);
            $obj = [
                "base_fee" => $detail["base_fee"],
                "additional_fee" => $detail["additional_fee"],
            ];
            if ($item->ownerPriceDirectLogistic->operation){
                app('OwnerPriceDirectLogisticService')->updateDetail(["id"=>$detail["id"]],$obj);
            }else{
                app('OwnerPriceDirectLogisticService')->copy($item->ownerPriceDirectLogistic,[],null,[$detail["id"]=>$obj]);
            }
        }else{
            $row = app('OwnerPriceDirectLogisticService')->isExistDetail([
                "owner_price_direct_logistic_id"=>$request->input("id"),
                "car_type_id"=>$detail["car_type_id"],
            ]);
            if ($row>0)$this->error("已存在该计费模型");
            $model = app('OwnerPriceDirectLogisticService')->find(request("id"));
            $values = [
                "owner_price_direct_logistic_id"=>$request->input("id"),
                "car_type_id"=>$detail["car_type_id"],
                "base_fee" => $detail["base_fee"],
                "additional_fee" => $detail["additional_fee"],
            ];
            if (!$model->operation){
                $model = app('OwnerPriceDirectLogisticService')->copy($model);
                $values["owner_price_direct_logistic_id"] = $model->id;
            }
            /** @var OwnerPriceExpressProvince $detail */
            $detail = app('OwnerPriceDirectLogisticService')->createDetail($values);
            $detail->load("carType");
        }
        LogService::log(__METHOD__,"计费模型-修改直发车计费详情",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        $this->success($detail);
    }

    public function directLogisticDestroyDetail(Request $request)
    {
        $this->gate("计费模型-直发-删除");
        $id = $request->input("id");
        if (!$id)$this->error("非法参数");
        /** @var \stdClass $item */
        $item = OwnerPriceDirectLogisticCar::query()->with("ownerPriceDirectLogistic")->find($id);
        if ($item->ownerPriceDirectLogistic->operation){
            app("OwnerPriceDirectLogisticService")->destroyDetail($id);
        }else{
            $model = app("OwnerPriceDirectLogisticService")->copy($item->ownerPriceDirectLogistic);
            OwnerPriceDirectLogisticCar::query()->where("owner_price_direct_logistic_id",$model->id)
                ->where("car_type_id",$item->car_type_id)->delete();
        }
        LogService::log(__METHOD__,"计费模型-删除直发车计费详情",$id);
        $this->success();
    }

    private function directLogisticValidator(array $params, $id= null)
    {
        return Validator::make($params,[
            'name'=>['required',$id?"unique:owner_price_direct_logistics,name,$id":'unique:owner_price_direct_logistics,name'],
            'base_km'=>['required','numeric','min:0'],
            'owner_id'=>[function ($attribute, $value, $fail)use($id) {
                $owners = app("OwnerPriceDirectLogisticService")->getExistOwnerName($value,$id);
                if ($owners)$fail("(".implode(',',$owners).') 已经绑定直发计费模型');
            }],
        ],[
            'required'=>':attribute 为必填项',
            'unique' => ':attribute 已存在',
            'numeric' => ':attribute 必须为数字',
            'min' => ':attribute 不得为负',
        ],[
            'name' =>"名称",
            'base_km'  =>"起步公里数",
        ]);
    }

    public function apiStoreStorage()
    {
        $this->gate("项目管理-仓储-录入");
        $errors = $this->storageValidator(request()->input())->errors();
        if (count($errors)>0)$this->success(["errors"=>$errors]);

        if (!request("owner_id"))$this->error("参数传递错误");
        $values = [
            "name"              => request("name"),
            "counting_type"     => request("counting_type"),
            "using_type"        => request("using_type"),
            "minimum_area"      => request("minimum_area") ?? 0,
            "price"             => request("price"),
            "discount_type"     => request("discount_type"),
            "discount_value"    => request("discount_value") ?? 0,
            "unit_id"           => request("unit_id"),
            "time_unit_id"      => request("time_unit_id"),
            "amount_interval"   => request("amount_interval") ?? null,
            "tax_rate_id"       => request("tax_rate_id") ?? null,
        ];
        if (request("id")){
            $model = app('OwnerStoragePriceModelService')->find(request("id"));
            if ($model->operation){
                app('OwnerStoragePriceModelService')->update(["id"=>request("id")],$values);
                $this->success();
            }else $this->success(app('OwnerStoragePriceModelService')->copy($model,$values));
        }else{
            $model = app('OwnerStoragePriceModelService')->create($values);
            DB::insert(DB::raw("INSERT INTO owner_storage_price_model_owner VALUES(?,?)"),[$model->id,request("owner_id")]);
            app("OwnerService")->refreshRelevance(request("owner_id"),0);
            $this->success($model->id);
        }
    }

    public function apiStoreOperation()
    {
        $this->gate("计费模型-作业-录入");
        $params = request()->input();
        $params["owner_id"] = [$params["owner_id"]];
        $errors = $this->operationValidator($params,request("id"))->errors();
        if (count($errors)>0)$this->success(["errors"=>$errors]);

        if (!request("owner_id"))$this->error("参数传递错误");
        $operation = [
            "name"              => request("name"),
            "max_fee"           => request("max_fee") ?? null,
            "operation_type"    => request("operation_type"),
            "strategy"          => request("strategy"),
            "feature"           => request("feature"),
            "type_mark"         => request()->has("type_mark") ? \request("type_mark") : null,
            "surcharge"         => request("surcharge") ? request("surcharge") : null,
            "surcharge_unit_id" => request("surcharge_unit_id") ? request("surcharge_unit_id") : null,
            "remark"            => request("remark"),
            "discount_count"    => implode(",",request("discount_count")),
            "total_price"       => request("total_price"),
            "total_discount_price"=> implode(",",request("total_discount_price")),
            "tax_rate_id"       => request("tax_rate_id") ?? null,
        ];
        if (request("id")){
            $model = app('OwnerPriceOperationService')->find(request("id"),["items"]);
            if ($model->operation){
                app('OwnerPriceOperationService')->findUpdate($model,$operation);
                $delete = [];//需要删除子项
                $update = [["id","strategy","amount","unit_id","unit_price","feature","discount_price","odd_price"]];//需要更新子项
                $insert = [];//需要新增子项
                foreach ($params["items"] as $item){
                    $obj = [
                        "strategy"  => $item["strategy"],
                        "amount"    => $item["amount"],
                        "unit_id"   => $item["unit_id"],
                        "unit_price"=> $item["unit_price"],
                        "feature"   => $item["feature"] ?? null,
                        "odd_price" => $item["odd_price"] ?? null,
                        "discount_price"   => implode(",",$item["discount_price"] ?? []),
                    ];
                    if (isset($item["id"])){
                        $obj["id"] = $item["id"];
                        $update[] = $obj;
                        $delete[] = $item["id"];
                    } else{
                        $obj["owner_price_operation_id"] = $model->id;
                        $obj["feature"] = $item["feature"] ?? null;
                        $insert[] = $obj;
                    }
                }
                $ids = array_column($model->items->toArray(),"id");
                $delete = array_diff($ids,$delete);
                if ($delete)app("OwnerPriceOperationItemService")->destroy($delete);
                if (count($update) > 1)app(BatchUpdateService::class)->batchUpdate("owner_price_operation_items",$update);
                if ($insert)app("OwnerPriceOperationItemService")->insert($insert);
            }else $model = app("OwnerPriceOperationService")->copy($model,$operation,null,$params["items"],false);
        }else{
            DB::transaction(function ()use(&$model,$params,$operation){
                $model = app('OwnerPriceOperationService')->create($operation);
                foreach ($params["items"] as &$item){
                    $temp = [];
                    $temp["discount_price"]  = implode(",",$item["discount_price"] ?? []);
                    $temp["owner_price_operation_id"] = $model->id;
                    $temp["feature"] = $item["feature"] ?? null;
                    $temp["odd_price"] = $item["odd_price"] ?? null;
                    $temp["strategy"] = $item["strategy"];
                    $temp["amount"] = $item["amount"];
                    $temp["unit_id"] = $item["unit_id"];
                    $temp["unit_price"] = $item["unit_price"];
                    $item = $temp;
                }
                app("OwnerPriceOperationItemService")->insert($params["items"]);
                DB::insert(DB::raw("INSERT INTO owner_price_operation_owner(owner_price_operation_id,owner_id) VALUES(?,?)"),[$model->id,request("owner_id")]);
                app("OwnerService")->refreshRelevance(request("owner_id"),1);
                DB::commit();
            });
        }
        /** @var OwnerPriceOperation $model */
        $model->load("items");
        $this->success($model);
    }

    public function apiStoreExpress()
    {
        $this->gate("计费模型-快递-录入");
        $params = request()->input();
        $params["logistic_id"] = $params["logistics"];
        $errors = $this->expressValidator($params,request("id"))->errors()->toArray();
        $exist = [];
        foreach ($params["items"] as $index => $item){
            if (isset($exist[$item["province_id"]]))$errors["items.".$index.".province_id"] = ["已存在"];
            else $exist[$item["province_id"]] = true;
        }
        if (count($errors)>0)$this->success(["errors"=>$errors]);

        $obj = [
            "name"              => request("name"),
            "initial_weight"    => request("initial_weight"),
            "additional_weight" => request("additional_weight"),
            "amount_interval"   => request("amount_interval"),
            "weight_interval"   => request("weight_interval"),
            "tax_rate_id"       => request("tax_rate_id") ?? null,
        ];
        if (request("id")){
            /** @var \stdClass $model */
            $model = app('OwnerPriceExpressService')->find(request("id"),["details"]);
            if ($model->operation){
                app('OwnerPriceExpressService')->update(["id"=>request("id")],$obj);

                $delete = [];//需要删除子项
                $update = [["id","province_id","initial_weight_price","additional_weight_price"]];//需要更新子项
                $insert = [];//需要新增子项
                foreach ($params["items"] as $item){
                    $obj = [
                        "province_id"               => $item["province_id"],
                        "initial_weight_price"      => $item["initial_weight_price"],
                        "additional_weight_price"   => $item["additional_weight_price"],
                    ];
                    if (isset($item["id"])){
                        $obj["id"] = $item["id"];
                        $update[] = $obj;
                        $delete[] = $item["id"];
                    } else{
                        $obj["owner_price_express_id"] = $model->id;
                        $insert[] = $obj;
                    }
                }
                $ids = array_column($model->details->toArray(),"id");
                $delete = array_diff($ids,$delete);
                if ($delete)OwnerPriceExpressProvince::destroy($delete);
                if (count($update) > 1)app(BatchUpdateService::class)->batchUpdate("owner_price_express_provinces",$update);
                if ($insert)OwnerPriceExpressProvince::query()->insert($insert);
                /** @var OwnerPriceExpress $model */
                $model->logistics()->sync(request("logistics"));
            }else{
                foreach ($params["items"] as &$item)unset($item["id"]);
                $model = app('OwnerPriceExpressService')->copy($model,$obj,null,request("logistics"),$params["items"],false);
            }
        }else{
            DB::transaction(function ()use(&$model,$params,$obj){
                $model = app('OwnerPriceExpressService')->create($obj);
                foreach ($params["items"] as &$item){
                    $item["owner_price_express_id"] = $model->id;
                    $item["initial_weight_price"] = json_encode($item["initial_weight_price"]);
                    $item["additional_weight_price"] = json_encode($item["additional_weight_price"]);
                }
                OwnerPriceExpressProvince::query()->insert($params["items"]);
                DB::insert(DB::raw("INSERT INTO owner_price_express_owner VALUES(?,?)"),[$model->id,request("owner_id")]);
                app("OwnerService")->refreshRelevance(request("owner_id"),2);
                /** @var OwnerPriceExpress $model */
                $model->logistics()->syncWithoutDetaching(request("logistics"));
                DB::commit();
            });
        }
        $model->load("details");
        $this->success($model);
    }

    public function apiStoreLogistic()
    {
        $this->gate("计费模型-物流-录入");
        $params = request()->input();
        $params["owner_id"] = [$params["owner_id"]];
        $params["logistic_id"] = $params["logistics"];
        $errors = $this->logisticValidator($params,request("id"))->errors()->toArray();
        $exist = [];
        foreach ($params["items"] as $index => $item){
            $key = $item["unit_id"]."-".$item["range"]."-".$item["province_id"]."-".$item["city_id"];
            if (isset($exist[$key]))$errors["items.".$index.".unit_id"] = ["该条已存在"];
            else $exist[$key] = true;
        }
        if (count($errors)>0)$this->success(["errors"=>$errors]);

        $obj = [
            "name"              => request('name'),
            "unit_range"        => request('unit_range'),
            "unit_id"           => request('unit_id'),
            "other_unit_range"  => request('other_unit_range'),
            "other_unit_id"     => request('other_unit_id'),
            "pick_up_price"     => request('pick_up_price'),
            "fuel_price"        => request('fuel_price'),
            "service_price"     => request('service_price'),
            "tax_rate_id"       => request("tax_rate_id") ?? null,
        ];
        if (request("id")){
            $model = app("OwnerPriceLogisticService")->find(request("id"),["details"]);
            if ($model->operation){
                app("OwnerPriceLogisticService")->update(["id"=>request("id")],$obj);

                $delete = [];//需要删除子项
                $update = [["id","unit_id","range","province_id","city_id","unit_price","delivery_fee","initial_fee","initial_amount","rate"]];//需要更新子项
                $insert = [];//需要新增子项
                foreach ($params["items"] as $item){
                    $obj = [
                        "unit_id"        => $item["unit_id"],
                        "range"          => $item["range"],
                        "province_id"    => $item["province_id"],
                        "city_id"        => $item["city_id"],
                        "unit_price"     => $item["unit_price"],
                        "delivery_fee"   => $item["delivery_fee"],
                        "initial_fee"    => $item["initial_fee"],
                        "initial_amount" => $item["initial_amount"],
                        "rate"           => $item["rate"],
                    ];
                    if (isset($item["id"])){
                        $obj["id"] = $item["id"];
                        $update[] = $obj;
                        $delete[] = $item["id"];
                    } else{
                        $obj["owner_price_logistic_id"] = $model->id;
                        $insert[] = $obj;
                    }
                }
                $ids = array_column($model->details->toArray(),"id");
                $delete = array_diff($ids,$delete);
                if ($delete)OwnerPriceLogisticDetail::destroy($delete);
                if (count($update) > 1)app(BatchUpdateService::class)->batchUpdate("owner_price_logistic_details",$update);
                if ($insert)OwnerPriceLogisticDetail::query()->insert($insert);
                /** @var OwnerPriceLogistic $model */
                $model->logistics()->sync(request("logistics"));
            }else{
                foreach ($params["items"] as &$item)unset($item["id"]);
                $model = app("OwnerPriceLogisticService")->copy($model,$obj,null,request("logistics"),$params["items"],false);
            }
        }else{
            DB::transaction(function ()use(&$model,$params,$obj){
                $model = app("OwnerPriceLogisticService")->create($obj);
                foreach ($params["items"] as &$param)$param["owner_price_logistic_id"] = $model->id;
                OwnerPriceLogisticDetail::query()->insert($params["items"]);
                DB::insert(DB::raw("INSERT INTO owner_price_logistic_owner VALUES(?,?)"),[$model->id,request("owner_id")]);
                app("OwnerService")->refreshRelevance(request("owner_id"),3);
                /** @var OwnerPriceLogistic $model */
                $model->logistics()->syncWithoutDetaching(request("logistics"));
                DB::commit();
            });
        }
        $model->load("details");
        $this->success($model);
    }

    public function apiStoreDirectLogistic()
    {
        $this->gate("计费模型-直发-录入");
        $errors = $this->directLogisticValidator(request()->input(),request("id"))->errors()->toArray();
        $exist = [];
        foreach (request("items") as $index=>$item){
            if (isset($exist[$item['car_type_id']]))$errors["items.".$index.".car_type_id"] = ["已存在"];
            else $exist[$item['car_type_id']] = true;
        }
        if (count($errors)>0)$this->success(["errors"=>$errors]);

        $items = request()->input("items");
        $obj = [
            "name"      => request("name"),
            "base_km"   => request("base_km"),
            "tax_rate_id"=> request("tax_rate_id") ?? null,
        ];
        if (request("id")){
            $model = app("OwnerPriceDirectLogisticService")->find(request("id"),["details"]);
            if ($model->operation){
                app("OwnerPriceDirectLogisticService")->update(["id"=>request("id")],$obj);

                $delete = [];//需要删除子项
                $update = [["id","car_type_id","base_fee","additional_fee"]];//需要更新子项
                $insert = [];//需要新增子项
                foreach ($items as $item){
                    $obj = [
                        "car_type_id"       => $item["car_type_id"],
                        "base_fee"          => $item["base_fee"],
                        "additional_fee"    => $item["additional_fee"],
                    ];
                    if (isset($item["id"])){
                        $obj["id"] = $item["id"];
                        $update[] = $obj;
                        $delete[] = $item["id"];
                    } else{
                        $obj["owner_price_direct_logistic_id"] = $model->id;
                        $insert[] = $obj;
                    }
                }
                $ids = array_column($model->details->toArray(),"id");
                $delete = array_diff($ids,$delete);
                if ($delete)OwnerPriceDirectLogisticCar::destroy($delete);
                if (count($update) > 1)app(BatchUpdateService::class)->batchUpdate("owner_price_direct_logistic_cars",$update);
                if ($insert)OwnerPriceDirectLogisticCar::query()->insert($insert);
            }else{
                foreach ($items as &$item)unset($item["id"]);
                $model = app("OwnerPriceDirectLogisticService")->copy($model,$obj,null,$items,false);
            }
        }else{
            DB::transaction(function ()use(&$model,$items,$obj){
                $model = app("OwnerPriceDirectLogisticService")->create($obj);
                foreach ($items as &$item)$item["owner_price_direct_logistic_id"] = $model->id;
                OwnerPriceDirectLogisticCar::query()->insert($items);
                DB::insert(DB::raw("INSERT INTO owner_price_direct_logistic_owner VALUES(?,?)"),[$model->id,request("owner_id")]);
                app("OwnerService")->refreshRelevance(request("owner_id"),4);
                DB::commit();
            });
        }
        /** @var OwnerPriceDirectLogistic $model */
        $model->load("details");
        $this->success($model);
    }

    public function apiStoreSystem()
    {
        $this->gate("计费模型-系统-录入");
        if (!request("owner_id") || !request("usage_fee") || \request("usage_fee")<0)$this->success(["errors"=>["usage_fee"=>["不得小于0"]]]);
        $obj = [
            "usage_fee"=>\request("usage_fee"),
            "tax_rate_id"=>\request("tax_rate_id"),
            "time_unit_id"=>\request("time_unit_id"),
        ];
        if (request("id")){
            /** @var OwnerPriceSystem|\stdClass $model */
            $model = OwnerPriceSystem::query()->find(request("id"));
            $obj["operation"] = "U";
            if ($model->operation)$model->update($obj);
            else{
                $obj["target_id"] = $model->id;
                $obj["owner_id"] = $model->owner_id;
                $model = OwnerPriceSystem::query()->create($obj);
            }
        }else{
            $obj["operation"] = "C";
            $obj["owner_id"] = \request("owner_id");
            $model = OwnerPriceSystem::query()->create($obj);
        }
        $this->success($model);
    }

    public function getPriceModel()
    {
        /** @var Owner|\stdClass $owner */
        $owner = new Owner();
        $owner->id = request("id");
        $owner->load(["ownerStoragePriceModels","ownerPriceOperations"=>function($query){
            /** @var Builder $query */
            $query->with(["items"=>function($query){
                /** @var Builder $query */
                $query->orderByRaw("CASE strategy  WHEN '起步' THEN 1 WHEN '默认' THEN 2 WHEN '特征' THEN 3 END");
            }]);
        },"ownerPriceExpresses"=>function($query){
            /** @var Builder $query */
            $query->with(["details","logistics"]);
        },"ownerPriceLogistics"=>function($query){
            /** @var Builder $query */
            $query->with(["details","logistics"]);
        },"ownerPriceDirectLogistics.details","ownerPriceSystem"]);
        $owner->loadCount(["storageAudit","operationAudit","expressAudit","logisticAudit","directLogisticAudit","systemAudit"]);
        $features = app("FeatureService")->getMapArray();
        OwnerPriceOperation::$features = $features;
        OwnerPriceOperationItem::$features = $features;
        foreach ($owner->ownerPriceOperations as &$operation){
            $operation["featureFormat"] = $operation->featureFormat;
            $operation["isRejected"] = $operation->type_mark === 0 ? true : false;
            foreach ($operation->items as &$item){
                $item["featureFormat"] = $item->featureFormat;
                if ($item["strategy"] == "起步")$item["type"] = $item["amount"] ? 0 : 1;
            }
        }
        $this->success($owner);
    }

    public function apiGetStorage()
    {
        $this->gate("项目管理-项目-录入");
        $models = OwnerStoragePriceModel::query()->where(function (Builder $query){
            $query->whereNull("operation")->orWhere("operation","");
        });
        if (request("customer_id")){
            $customerId = request("customer_id");
            $models->whereHas("owners",function ($query)use($customerId){
                /** @var Builder $query */
                $query->where("customer_id",$customerId);
            });
        }
        if (request("owner_id")){
            $ownerId = request("owner_id");
            $models->whereHas("owners",function ($query)use($ownerId){
                /** @var Builder $query */
                $query->where("id",$ownerId);
            });
        }
        if (request("name")){
            $models->where("name","like","%".request("name")."%");
        }
        $this->success($models->get());
    }
    public function apiGetOperation()
    {
        $this->gate("项目管理-项目-录入");
        $models = OwnerPriceOperation::query()->with("items")->where(function (Builder $query){
            $query->whereNull("operation")->orWhere("operation","");
        });
        if (request("customer_id")){
            $customerId = request("customer_id");
            $models->whereHas("owners",function ($query)use($customerId){
                /** @var Builder $query */
                $query->where("customer_id",$customerId);
            });
        }
        if (request("owner_id")){
            $ownerId = request("owner_id");
            $models->whereHas("owners",function ($query)use($ownerId){
                /** @var Builder $query */
                $query->where("id",$ownerId);
            });
        }
        if (request("name")){
            $models->where("name","like","%".request("name")."%");
        }
        $features = app("FeatureService")->getMapArray();
        OwnerPriceOperation::$features = $features;
        OwnerPriceOperationItem::$features = $features;
        $models = $models->get();
        foreach ($models as &$operation){
            $operation["featureFormat"] = $operation->featureFormat;
            $operation["isRejected"] = $operation->type_mark === 0 ? true : false;
            $items = [];
            foreach ($operation->items as $item){
                $items[] = [
                    "strategy" => $item["strategy"],
                    "amount" => $item["amount"],
                    "unit_id" => $item["unit_id"],
                    "unit_price" => $item["unit_price"],
                    "discount_price" => $item["discount_price"] ?? null,
                    "feature" => $item["feature"],
                    "featureFormat" => $item->featureFormat,
                ];
            }
            $operation["items"] = $items;
        }
        $this->success($models);
    }
    public function apiGetExpress()
    {
        $this->gate("项目管理-项目-录入");
        $models = OwnerPriceExpress::query()->with(["details","logistics:id"])->where(function (Builder $query){
            $query->whereNull("operation")->orWhere("operation","");
        });
        if (request("customer_id")){
            $customerId = request("customer_id");
            $models->whereHas("owners",function ($query)use($customerId){
                /** @var Builder $query */
                $query->where("customer_id",$customerId);
            });
        }
        if (request("owner_id")){
            $ownerId = request("owner_id");
            $models->whereHas("owners",function ($query)use($ownerId){
                /** @var Builder $query */
                $query->where("id",$ownerId);
            });
        }
        if (request("logistic_id")){
            $logisticId = request("logistic_id");
            $models->whereHas("logistics",function ($query)use($logisticId){
                /** @var Builder $query */
                $query->where("id",$logisticId);
            });
        }
        if (request("name")){
            $models->where("name","like","%".request("name")."%");
        }
        $this->success($models->get());
    }
    public function apiGetLogistic()
    {
        $this->gate("项目管理-项目-录入");
        $models = OwnerPriceLogistic::query()->with(["details","logistics"])->where(function (Builder $query){
            $query->whereNull("operation")->orWhere("operation","");
        });
        if (request("customer_id")){
            $customerId = request("customer_id");
            $models->whereHas("owners",function ($query)use($customerId){
                /** @var Builder $query */
                $query->where("customer_id",$customerId);
            });
        }
        if (request("owner_id")){
            $ownerId = request("owner_id");
            $models->whereHas("owners",function ($query)use($ownerId){
                /** @var Builder $query */
                $query->where("id",$ownerId);
            });
        }
        if (request("logistic_id")){
            $logisticId = request("logistic_id");
            $models->whereHas("logistics",function ($query)use($logisticId){
                /** @var Builder $query */
                $query->where("id",$logisticId);
            });
        }
        if (request("name")){
            $models->where("name","like","%".request("name")."%");
        }
        $this->success($models->get());
    }
    public function apiGetDirectLogistic()
    {
        $this->gate("项目管理-项目-录入");
        $models = OwnerPriceDirectLogistic::query()->with("details")->where(function (Builder $query){
            $query->whereNull("operation")->orWhere("operation","");
        });
        if (request("customer_id")){
            $customerId = request("customer_id");
            $models->whereHas("owners",function ($query)use($customerId){
                /** @var Builder $query */
                $query->where("customer_id",$customerId);
            });
        }
        if (request("owner_id")){
            $ownerId = request("owner_id");
            $models->whereHas("owners",function ($query)use($ownerId){
                /** @var Builder $query */
                $query->where("id",$ownerId);
            });
        }
        if (request("name")){
            $models->where("name","like","%".request("name")."%");
        }
        $this->success($models->get());
    }

    public function apiDelStorage()
    {
        $this->publicDeleteNode("OwnerStoragePriceModelService");
    }
    public function apiDelOperation()
    {
        $this->publicDeleteNode("OwnerPriceOperationService");
    }
    public function apiDelOperationItem()
    {
        $this->gate("项目管理-项目-录入");
        if (!request("id"))$this->error("非法参数");
        /** @var \stdClass $item */
        $item = OwnerPriceOperationItem::query()->with("ownerPriceOperation")->find(request("id"));
        if ($item->ownerPriceOperation->operation){
            app("OwnerPriceOperationItemService")->destroy(request("id"));
            $this->success();
        }else{
            /** @var OwnerPriceOperation $model */
            $model = app("OwnerPriceOperationService")->copy($item->ownerPriceOperation);
            OwnerPriceOperationItem::query()->where("owner_price_operation_id",$model->id)
                ->where("strategy",$item->strategy)
                ->where("amount",$item->amount)
                ->where("unit_id",$item->unit_id)
                ->where("unit_price",$item->unit_price)
                ->where("feature",$item->feature)
                ->where("priority",$item->priority)
                ->where("discount_price",$item->discount_price)->delete();
            $model->load(["items"=>function($query){
                /** @var Builder $query */
                $query->orderByRaw("CASE strategy  WHEN '起步' THEN 1 WHEN '默认' THEN 2 WHEN '特征' THEN 3 END");
            }]);
            $this->success($model);
        }
    }
    public function apiDelExpress()
    {
        $this->publicDeleteNode("OwnerPriceExpressService");
    }
    public function apiDelExpressItem()
    {
        $this->gate("项目管理-项目-录入");
        if (!request("id"))$this->error("非法参数");
        /** @var \stdClass $item */
        $item = OwnerPriceExpressProvince::query()->with("ownerPriceExpress")->find(request("id"));
        if ($item->ownerPriceExpress->operation){
            app("OwnerPriceExpressService")->destroyDetail(request("id"));
        }else{
            $model = app("OwnerPriceExpressService")->copy($item->ownerPriceExpress);
            OwnerPriceExpressProvince::query()->where("owner_price_express_id",$model->id)
                ->where("province_id",$item->province_id)->delete();
        }
        $this->success();
    }
    public function apiDelLogistic()
    {
        $this->publicDeleteNode("OwnerPriceLogisticService");
    }
    public function apiDelLogisticItem()
    {
        $this->gate("项目管理-项目-录入");
        if (!request("id"))$this->error("非法参数");
        /** @var \stdClass $item */
        $item = OwnerPriceLogisticDetail::query()->with("ownerPriceLogistic")->find(request("id"));
        if ($item->ownerPriceLogistic->operation){
            app("OwnerPriceLogisticService")->destroyDetail(request("id"));
        }else{
            $model = app("OwnerPriceLogisticService")->copy($item->ownerPriceLogistic);
            OwnerPriceLogisticDetail::query()->where("owner_price_logistic_id",$model->id)
                ->where("unit_id",$item->unit_id)->where("range",$item->range)
                ->where("province_id",$item->province_id)
                ->where("city_id",$item->city_id)->delete();
        }
        $this->success();
    }
    public function apiDelDirectLogistic()
    {
        $this->publicDeleteNode("OwnerPriceDirectLogisticService");
    }
    public function apiDelDirectLogisticItem()
    {
        $this->gate("项目管理-项目-录入");
        if (!request("id"))$this->error("非法参数");
        /** @var \stdClass $item */
        $item = OwnerPriceDirectLogisticCar::query()->with("ownerPriceDirectLogistic")->find(request("id"));
        if ($item->ownerPriceDirectLogistic->operation){
            app("OwnerPriceDirectLogisticService")->destroyDetail(request("id"));
        }else{
            $model = app("OwnerPriceDirectLogisticService")->copy($item->ownerPriceDirectLogistic);
            OwnerPriceDirectLogisticCar::query()->where("owner_price_direct_logistic_id",$model->id)
                ->where("car_type_id",$item->car_type_id)->delete();
        }
        $this->success();
    }
    public function apiDelSystem()
    {
        $this->gate("项目管理-系统-录入");
        if (!request("id"))$this->error("非法参数");
        /** @var OwnerPriceSystem|\stdClass $model */
        $model = OwnerPriceSystem::query()->find(\request("id"));
        if ($model->operation && $model->target_id){
            OwnerPriceSystem::query()->where($model->target_id,\request("id"))->update(["operation"=>"D"]);
            $model->delete();
        }
        $this->success();
    }

    private function publicDeleteNode(string $serviceName)
    {
        $this->gate("项目管理-项目-录入");
        $id = request("id");
        if (!$id)$this->error("非法参数");
        $model = app($serviceName)->find($id);
        if ($model->operation && $model->target_id){
            app($serviceName)->destroy($id);
            $id = $model->target_id;
        }
        app($serviceName)->update(["id"=>$id],["operation"=>"D"]);
        $this->success();
    }

    //审核或恢复计费模型
    public function auditOrRecoverModel()
    {
        $this->gate("项目管理-项目-计费模型-审核");
        $ownerId = request("owner_id");
        if (!$ownerId)$this->error("非法参数");
        /** @var \stdClass|Owner $owner */
        $owner = new Owner();
        $owner->id = $ownerId;
        switch (request("type")){
            case "storage":
                app("OwnerStoragePriceModelService")->auditOrRecover(request("isAudit"),$ownerId);//priceModelAuditOrRecoverQuery
                $owner->load("ownerStoragePriceModels");
                $this->success($owner->ownerStoragePriceModels);
                break;
            case "operation":
                app("OwnerPriceOperationService")->auditOrRecover(request("isAudit"),$ownerId);
                $owner->load(["ownerPriceOperations"=>function($query){
                    /** @var Builder $query */
                    $query->with(["items"=>function($query){
                        /** @var Builder $query */
                        $query->orderByRaw("CASE strategy  WHEN '起步' THEN 1 WHEN '默认' THEN 2 WHEN '特征' THEN 3 END");
                    }]);
                }]);
                $features = app("FeatureService")->getMapArray();
                OwnerPriceOperation::$features = $features;
                OwnerPriceOperationItem::$features = $features;
                foreach ($owner->ownerPriceOperations as &$operation){
                    $operation["featureFormat"] = $operation->featureFormat;
                    foreach ($operation->items as &$item){
                        $item["featureFormat"] = $item->featureFormat;
                        if ($operation["operation_type"]==='出库' && $item["strategy"] == "起步"){
                            $item["type"] = $item["amount"] ? 0 : 1;
                        }
                    }
                }
                $this->success($owner->ownerPriceOperations);
                break;
            case "express":
                app("OwnerPriceExpressService")->auditOrRecover(request("isAudit"),$ownerId);
                $owner->load(["ownerPriceExpresses"=>function($query){
                    /** @var Builder $query */
                    $query->with(["details","logistics"]);
                }]);
                $this->success($owner->ownerPriceExpresses);
                break;
            case "logistic":
                app("OwnerPriceLogisticService")->auditOrRecover(request("isAudit"),$ownerId);
                $owner->load(["ownerPriceLogistics"=>function($query){
                    /** @var Builder $query */
                    $query->with(["details","logistics"]);
                }]);
                $this->success($owner->ownerPriceLogistics);
                break;
            case "directLogistic":
                app("OwnerPriceDirectLogisticService")->auditOrRecover(request("isAudit"),$ownerId);
                $owner->load("ownerPriceDirectLogistics.details");
                $this->success($owner->ownerPriceDirectLogistics);
                break;
            case "system":
                $result = app(QueryService::class)->priceModelAuditOrRecoverQuery(request("isAudit"),OwnerPriceSystem::query(),$ownerId,null,true);
                if ($result["delete"]){
                    OwnerPriceSystem::destroy($result["delete"]);
                    app("OwnerService")->refreshRelevance($ownerId,5,true);
                }
                if ($result["update"]){
                    OwnerPriceSystem::query()->whereIn("id",$result["update"])->update(["operation"=>null,"target_id"=>null]);
                    app("OwnerService")->refreshRelevance($ownerId,5);
                }
                $owner->load("ownerPriceSystem");
                $this->success($owner->ownerPriceSystem);
                break;
        }
    }

    /**
     * 获取审核对比信息
     */
    public function getPriceModelAudit()
    {
        $result = null;
        switch (\request("type")){
            case "storage":
                $result = $this->auditInfoQuery(OwnerStoragePriceModel::query(),\request("owner_id"))->get();
                break;
            case "operation":
                $result = $this->auditInfoQuery(OwnerPriceOperation::query(),\request("owner_id"))->with("items")->get();
                $features = app("FeatureService")->getMapArray();
                OwnerPriceOperation::$features = $features;
                OwnerPriceOperationItem::$features = $features;
                foreach ($result as &$operation){
                    $operation->feature = $operation->featureFormat;
                    $operation->type_mark = $operation->type_mark !==null ? OwnerPriceOperation::MARK[$operation->type_mark] : '';
                    foreach ($operation->items as &$item){
                        $item->feature = $item->featureFormat;
                    }
                }
                break;
            case "express":
                $result = $this->auditInfoQuery(OwnerPriceExpress::query(),\request("owner_id"))->with(["details","logistics"])->get();
                break;
            case "logistic":
                $result = $this->auditInfoQuery(OwnerPriceLogistic::query(),\request("owner_id"))->with(["details","logistics"])->get();
                break;
            case "directLogistic":
                $result = $this->auditInfoQuery(OwnerPriceDirectLogistic::query(),\request("owner_id"))->with("details")->get();
                break;
            case "system":
                $result = $this->auditInfoQuery(OwnerPriceSystem::query(),\request("owner_id"),false)->get();
                break;
        }
        $this->success($result);
    }

    /**
     * @param Builder $query
     * @param integer $owner
     * @param bool $isRelevance
     *
     * @return Builder
     */
    private function auditInfoQuery(Builder $query,$owner,$isRelevance = true)
    {
        $childQuery = clone $query;
        $query->where(function ($query)use($childQuery){
            $childQuery = $childQuery->select("target_id")->whereNotNull("target_id");
            /** @var Builder $query */
            $query->whereIn("id",$childQuery)->orWhere(function(Builder $query){
                $query->where("operation","!=","")->orWhereNotNull("operation");
            });
        });
        if ($isRelevance)$query->whereHas("owners",function ($query)use($owner){
            /** @var Builder $query */
            $query->where("id",$owner);
        });else $query->where("owner_id",$owner);
        return $query->orderBy("operation");
    }
}
