<?php

namespace App\Http\Controllers;

use App\Imports\ExpressImport;
use App\Imports\OwnerPriceDirectLogisticDetailImport;
use App\Imports\OwnerPriceLogisticDetailImport;
use App\Owner;
use App\OwnerOutStorageRule;
use App\OwnerPriceDirectLogistic;
use App\OwnerPriceExpress;
use App\OwnerPriceExpressProvince;
use App\OwnerPriceLogistic;
use App\OwnerPriceOperation;
use App\Services\common\ExportService;
use App\Services\LogService;
use App\Services\OwnerOutStorageRuleService;
use App\Services\OwnerPriceOperationService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Facades\Excel;

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

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

    public function storageStore(Request $request)
    {
        if(!Gate::allows('计费模型-仓储-录入')){ return redirect('denied');  }
        $this->storageValidator($request->input())->validate();
        app('OwnerStoragePriceModelService')->create($request->input());
        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);
        $units = app('UnitService')->getSelection();
        return response()->view('maintenance.priceModel.storage.create',compact("units","model"));
    }

    public function storageUpdate(Request $request)
    {
        if(!Gate::allows('计费模型-仓储-编辑')){ return redirect('denied');  }
        app('OwnerStoragePriceModelService')->update(["id"=>$request->input("id")],[
            "counting_type" => $request->input("counting_type"),
            "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"),
        ]);
        LogService::log(__METHOD__,"计费模型-修改仓储计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return response()->redirectTo('maintenance/priceModel/storage')->with('successTip',"更新成功！");
    }

    public function storageDestroy($id)
    {
        app("OwnerStoragePriceModelService")->destroy($id);
        LogService::log(__METHOD__,"计费模型-删除仓储计费",$id);
        return ["success"=>true];
    }

    private function storageValidator(array $params)
    {
        return Validator::make($params,[
            'counting_type'=>['required'],
            'using_type'=>['required'],
            'minimum_area'=>['nullable','numeric','min:0'],
            'discount_value'=>['nullable','numeric','min:0'],
            'price'=>['required','numeric','min:0'],
            'discount_type'=>['required'],
            'unit_id'=>['required','integer'],
        ],[
            'required'=>':attribute 为必填项',
            'min'=>':attribute 不得小于0',
            'integer'=>':attribute 未选择',
        ],[
            'counting_type' =>"计费类型",
            'using_type'    =>"用仓类型",
            'minimum_area'  =>"最低起租面积",
            'price'         =>"单价",
            'discount_type' =>"减免类型",
            'discount_value'=>"减免值",
            '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(),["ownerPriceOperationOwners","ownerInStorageRule"=>function($query){$query->with("unit");}])->append("featureFormat");
        $owners = app("OwnerService")->getIntersectPermitting();
        return response()->view('maintenance.priceModel.operation.index',compact("models","owners"));
    }

    /* 获取出库模型规则 */
    public function operationGetOutStorageRule(Request $request)
    {
        if(!Gate::allows('计费模型-作业-查询')){ return ["success"=>false,"data"=>"无权操作"];  }
        /** @var OwnerOutStorageRuleService $service */
        $service = app('OwnerOutStorageRuleService');
        $ownerOutStorageRules = $service->get(["owner_price_operation_id"=>$request->input("id")],["unit"],true)->append("featureFormat");
        return ["success"=>true,"data"=>$ownerOutStorageRules];
    }
    /* 修改出库模型规则 */
    public function updateOutStorageRule(Request $request)
    {
        if(!Gate::allows('计费模型-作业-编辑')){ return ["success"=>false,"data"=>"无权操作"];  }
        /** @var OwnerOutStorageRuleService $service */
        $service = app('OwnerOutStorageRuleService');
        $row = $service->update(["id"=>$request->input("id")],[
            "amount"=>$request->input("amount"),
            "unit_id"=>$request->input("unit_id"),
            "priority"=>$request->input("priority"),
            "unit_price"=>$request->input("unit_price")]);
        if ($row == 1){
            LogService::log(__METHOD__,"计费模型-修改出库规则",json_encode($request->input()));
            return ["success"=>true];
        }
        return ["success"=>false,"data"=>"受影响数据数为：".$row];
    }

    public function createOutStorageRule(Request $request)
    {
        if(!Gate::allows('计费模型-作业-编辑')){ return ["success"=>false,"data"=>"无权操作"];  }
        /** @var OwnerOutStorageRuleService $service */
        $service = app('OwnerOutStorageRuleService');
        switch ($request->input("strategy")){
            case "起步":
                $c = $service->isExist(["owner_price_operation_id"=>$request->input("owner_price_operation_id"),"strategy"=>"起步"]);
                if ($c > 0)return ["success"=>false,"data"=>"已存在起步策略"];
                break;
            case "默认":
                $c = $service->isExist(["owner_price_operation_id"=>$request->input("owner_price_operation_id"),"strategy"=>"默认"]);
                if ($c > 0)return ["success"=>false,"data"=>"已存在默认策略"];
                break;
        }
        $data = $service->create($request->input());
        LogService::log(__METHOD__,"计费模型-录入出库规则",json_encode($request->input()));
        $data->load("unit");
        return ["success"=>true,"data"=>$data];
    }
    public function getFeatures(Request $request)
    {
        return ["success"=>true,"data"=>app("FeatureService")->translationFeature($request->input("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('OwnerOutStorageRuleService')->update(["id"=>$id],["feature"=>$feature]);
        if ($row != 1)return ["success"=>false,"data"=>"影响了“".$row."”行"];
        LogService::log(__METHOD__,"计费模型-修改出库特征",json_encode($request->input()));
        OwnerOutStorageRule::$features = $result["map"];
        $rule = app('OwnerOutStorageRuleService')->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"=>"组标记错误，起始与结束标记必须对应"];
        return ["success"=>true,"data"=>$feature];
    }

    public function operationDestroy($id)
    {
        if(!Gate::allows('计费模型-作业-删除')){ return ["success"=>false,"data"=>"无权操作"];  }
        $row = app("OwnerPriceOperationService")->destroy($id);
        if ($row == 1){
            LogService::log(__METHOD__,"计费模型-删除作业计费",$id);
            return ["success"=>true];
        }
        return ["success"=>false,"data"=>"影响了“".$row."”行"];
    }

    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("rules",json_decode($request->input("rules"),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"),
        ]);
        //录入子表
        if ($request->input("operation_type") == '入库') $service->insertRule([
            "owner_price_operation_id" => $ownerPriceOperation->id,
            "amount" => $request->input("rules")[0]["amount"],
            "unit_id" => $request->input("rules")[0]["unit_id"],
            "unit_price" => $request->input("rules")[0]["unit_price"],
        ],"入库");
        else{
            $insert = [];
            foreach ($request->input("rules") as $rule){
                $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"],
                ];
            }
            $service->insertRule($insert);
        }
        //录入中间表
        /** @var OwnerPriceOperation $ownerPriceOperation */
        if ($request->input("owner_id"))$ownerPriceOperation->ownerPriceOperationOwners()->sync($request->input("owner_id"));
        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,true,["ownerPriceOperationOwners"]);
        $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("rules",json_decode($request->input("rules"),true));
        $request->offsetSet("owner_id",explode(',',$request->input("owner_id")));
        $this->operationValidator($request->input(),$id)->validate();

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

        $model = $service->find($id);
        $service->findUpdate($model,[
            "name" => $request->input("name"),
            "priority" => $request->input("priority"),
            "remark" => $request->input("remark"),
            "feature" => $request->input("feature"),
        ]);
        $service->destroyRule($id, $model->operation_type);
        //录入子表
        if ($request->input("operation_type") == '入库') $service->insertRule([
            "owner_price_operation_id" => $model->id,
            "amount" => $request->input("rules")[0]["amount"],
            "unit_id" => $request->input("rules")[0]["unit_id"],
            "unit_price" => $request->input("rules")[0]["unit_price"],
        ],"入库");
        else{
            $insert = [];
            foreach ($request->input("rules") 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"],
                ];
            }
            $service->insertRule($insert);
        }
        //录入中间表
        /** @var OwnerPriceOperation $model */
        if ($request->input("owner_id"))$model->ownerPriceOperationOwners()->sync($request->input("owner_id"));
        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,[
            //required_with:id
            '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',$id?"unique:owner_price_operations,name,$id":'unique:owner_price_operations,name'],
            'priority'=>['required','integer','min:0','max:100'],
            'rules.*.strategy'=>['required_if:operation_type,出库'],
            'rules.*.amount'=>[Rule::requiredIf(function () use ($params) {
                if ("operation_type" == "入库")return true;
                return false;
            }),"integer"],
            'rules.*.unit_id'=>['required','integer'],
            'rules.*.unit_price'=>['required','numeric',"min:0"],
            'rules.*.priority'=>['required_if:operation_type,出库','integer','min:0','max:100'],
        ],[
            'required'=>':attribute 为必填项',
            'min'=>':attribute 不得小于0',
            'integer'=>':attribute 必须为整数',
            'numeric'=>':attribute 必须为数字',
            'max'=>':attribute 超出最大值',
            'required_if'=>':attribute 操作类型为出库时不得为空',
        ],[
            'operation_type' =>"操作类型",
            'strategy'    =>"计费策略",
            'name'  =>"名称",
            'priority' =>"优先级",
        ]);
    }

    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)
    {
        if(!Gate::allows('计费模型-快递-查询')){ return ["success"=>false,"data"=>"无权操作"];  }
        $model = new OwnerPriceExpress();
        $model->id = $request->input("id");
        $model->load(["details"=>function($query){$query->with("province");}]);
        return ["success"=>true,"data"=>$model->details];
    }

    public function expressUpdateDetail(Request $request)
    {
        if(!Gate::allows('计费模型-快递-编辑')){ return ["success"=>false,"data"=>"无权操作"];  }
        $detail = $request->input("detail");
        if ($detail["id"]){
            app('OwnerPriceExpressService')->updateDetail(["id"=>$detail["id"]],[
                "additional_weight_price" => $detail["additional_weight_price"],
                "initial_weight_price" => $detail["initial_weight_price"],
            ]);
        }else{
            $row = app('OwnerPriceExpressService')->isExistDetail(["owner_price_express_id"=>$request->input("id"),"province_id"=>$detail["province_id"]]);
            if ($row>0)return ["success"=>false,"data"=>"已存在该省份计费模型"];
            /** @var OwnerPriceExpressProvince $detail */
            $detail = app('OwnerPriceExpressService')->createDetail([
                "owner_price_express_id" =>  $request->input("id"),
                "province_id" => $detail["province_id"],
                "additional_weight_price" => $detail["additional_weight_price"],
                "initial_weight_price" => $detail["initial_weight_price"],
            ]);
            $detail->load("province");
        }
        LogService::log(__METHOD__,"计费模型-修改快递计费",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return ["success"=>true,"data"=>$detail];
    }

    public function expressDestroyDetail(Request $request)
    {
        if(!Gate::allows('计费模型-快递-删除')){ return ["success"=>false,"data"=>"无权操作"];  }
        $id = $request->input("id");
        if (!$id)return ["success"=>false,"data"=>"非法参数"];
        app("OwnerPriceExpressService")->destroyDetail($id);
        LogService::log(__METHOD__,"计费模型-删除快递计费",$id);
        return ["success"=>true];
    }

    public function expressImport(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);
        /** @var OwnerPriceExpress $model */
        $model = app('OwnerPriceExpressService')->find($request->input("id"),["details"]);
        Excel::import(new ExpressImport($model),$request->file('file')->path(),null,$fileSuffix);
        if (Cache::has('express'))return Cache::pull('express');

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

    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"),
        ]);
        $model->owners()->sync($request->input("owner_id"));
        $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")));
        $this->expressValidator($request->input(),$id)->validate();
        /** @var OwnerPriceExpress $model */
        app("OwnerPriceExpressService")->update(["id"=>$id],[
            "name" => $request->input("name"),
            "initial_weight" => $request->input("initial_weight"),
            "additional_weight" => $request->input("additional_weight"),
        ]);
        $model = new OwnerPriceExpress();
        $model->id = $id;
        $model->owners()->sync($request->input("owner_id"));
        $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")."”成功");
    }

    private function expressValidator(array $params, $id=null)
    {
        return Validator::make($params,[
            'name'=>['required',$id?"unique:owner_price_expresses,name,$id":'unique:owner_price_expresses,name'],
            'initial_weight'=>['required','numeric','min:0'],
            'additional_weight'=>['required','numeric','min:0'],
            'owner_id'=>[function ($attribute, $value, $fail)use($id) {
                $owners = app("OwnerPriceExpressService")->getExistOwnerName($value,$id);
                if ($owners)$fail("(".implode(',',$owners).') 已经绑定计费模型');
            }],
            'logistic_id'=>[function ($attribute, $value, $fail)use($id) {
                $logistics = app("OwnerPriceExpressService")->getExistLogisticName($value,$id);
                if ($logistics)$fail("(".implode(',',$logistics).') 已经绑定计费模型');
            }],
        ],[
            'required'=>':attribute 为必填项',
            'unique' => ':attribute 已存在',
        ],[
            'name' =>"名称",
            'initial_weight'  =>"首重",
            'additional_weight'  =>"续重",
        ]);
    }

    public function expressDestroy($id)
    {
        if(!Gate::allows('计费模型-快递-删除')){ return ["success"=>false,"data"=>"无权操作"]; };
        app("OwnerPriceExpressService")->destroy($id);
        LogService::log(__METHOD__,"计费模型-删除快递计费",$id);
        return ["success"=>true];
    }

    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"),
        ]);
        $model->owners()->sync($request->input("owner_id"));
        $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();
        $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();
        app("OwnerPriceLogisticService")->update(["id"=>$id],[
            "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 = new OwnerPriceLogistic();
        $model->id = $id;
        $model->owners()->sync($request->input("owner_id"));
        $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 logisticGetDetail(Request $request)
    {
        if(!Gate::allows('计费模型-物流-查询')){ return ["success"=>false,"data"=>"无权操作"];  }
        $model = new OwnerPriceLogistic();
        $model->id = $request->input("id");
        $model->load(["details"=>function($query){
            /** @var Builder $query */
            $query->with(["unit","province","city"]);
        }]);
        return ["success"=>true,"data"=>$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);
        /** @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)
    {
        if(!Gate::allows('计费模型-物流-查询')){ return ["success"=>false,"data"=>"无权操作"];  }
        $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)
    {
        if(!Gate::allows('计费模型-物流-编辑')){ return ["success"=>false,"data"=>"无权操作"];  }
        $detail = $request->input("detail");
        if ($detail["id"]){
            app('OwnerPriceLogisticService')->updateDetail(["id"=>$detail["id"]],[
                "unit_price" => $detail["unit_price"],
                "delivery_fee" => $detail["delivery_fee"],
                "initial_fee" => $detail["initial_fee"],
                "initial_amount" => $detail["initial_amount"],
                "rate" => $detail["rate"],
            ]);
        }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)return ["success"=>false,"data"=>"已存在该计费模型"];
            /** @var OwnerPriceExpressProvince $detail */
            $detail = app('OwnerPriceLogisticService')->createDetail([
                "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"],
                "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));
        return ["success"=>true,"data"=>$detail];
    }

    public function logisticDestroyDetail(Request $request)
    {
        if(!Gate::allows('计费模型-物流-删除')){ return ["success"=>false,"data"=>"无权操作"];  }
        $id = $request->input("id");
        if (!$id)return ["success"=>false,"data"=>"非法参数"];
        app("OwnerPriceLogisticService")->destroyDetail($id);
        LogService::log(__METHOD__,"计费模型-删除物流计费详情",$id);
        return ["success"=>true];
    }
    public function logisticDestroy($id)
    {
        if(!Gate::allows('计费模型-物流-删除')){ return ["success"=>false,"data"=>"无权操作"];  }
        if (!$id)return ["success"=>false,"data"=>"非法参数"];
        app("OwnerPriceLogisticService")->destroy($id);
        LogService::log(__METHOD__,"计费模型-删除物流计费",$id);
        return ["success"=>true];
    }

    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("格式错误,值必须为连续的且最后一个值不允许封闭");
            }],
        ],[
            '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'  =>"区间值",
        ]);
    }

    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"),
        ]);
        $model->owners()->sync($request->input("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 directLogisticDestroy($id)
    {
        if(!Gate::allows('计费模型-直发-删除')){ return ["success"=>false,"data"=>"无权操作"];  }
        $row = app("OwnerPriceDirectLogisticService")->destroy($id);
        if ($row == 1){
            LogService::log(__METHOD__,"计费模型-删除直发车计费",$id);
            return ["success"=>true];
        }
        return ["success"=>false,"data"=>"影响了“".$row."”行"];
    }

    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();
        app("OwnerPriceDirectLogisticService")->update(["id"=>$id],[
            "name" => $request->input("name"),
            "base_km" => $request->input("base_km"),
        ]);
        $model = new OwnerPriceDirectLogistic();
        $model->id = $id;
        $model->owners()->sync($request->input("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)
    {
        if(!Gate::allows('计费模型-直发-查询')){ return ["success"=>false,"data"=>"无权操作"];  }
        $model = new OwnerPriceDirectLogistic();
        $model->id = $request->input("id");
        $model->load(["details"=>function($query){
            /** @var Builder $query */
            $query->with("carType");
        }]);
        return ["success"=>true,"data"=>$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);
        $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)
    {
        if(!Gate::allows('计费模型-直发-编辑')){ return ["success"=>false,"data"=>"无权操作"];  }
        $detail = $request->input("detail");
        if ($detail["id"]){
            app('OwnerPriceDirectLogisticService')->updateDetail(["id"=>$detail["id"]],[
                "base_fee" => $detail["base_fee"],
                "additional_fee" => $detail["additional_fee"],
            ]);
        }else{
            $row = app('OwnerPriceDirectLogisticService')->isExistDetail([
                "owner_price_direct_logistic_id"=>$request->input("id"),
                "car_type_id"=>$detail["car_type_id"],
            ]);
            if ($row>0)return ["success"=>false,"data"=>"已存在该计费模型"];
            /** @var OwnerPriceExpressProvince $detail */
            $detail = app('OwnerPriceDirectLogisticService')->createDetail([
                "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"],
            ]);
            $detail->load("carType");
        }
        LogService::log(__METHOD__,"计费模型-修改直发车计费详情",json_encode($request->input(),JSON_UNESCAPED_UNICODE));
        return ["success"=>true,"data"=>$detail];
    }

    public function directLogisticDestroyDetail(Request $request)
    {
        if(!Gate::allows('计费模型-直发-删除')){ return ["success"=>false,"data"=>"无权操作"];  }
        $id = $request->input("id");
        if (!$id)return ["success"=>false,"data"=>"非法参数"];
        app("OwnerPriceDirectLogisticService")->destroyDetail($id);
        LogService::log(__METHOD__,"计费模型-删除直发车计费详情",$id);
        return ["success"=>true];
    }

    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'  =>"起步公里数",
        ]);
    }

}
