<?php

namespace App\Http\Controllers;

use App\Region;
use App\WaybillPriceModel;
use App\Events\WaybillPriceModelEvent;
use App\Imports\WaybillPriceModelsImport;
use App\Unit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class WaybillPriceModelController extends Controller
{
    public function index(Request $request)
    {
        if(!Gate::allows('计费模型-查询')){ return redirect(url('/'));  }
        $logistics=app('LogisticService')->getSelection(["id","name"],"物流");
        $provinces=Region::query()->where("type",1)->get();
        $data=$request->input();
        $waybillPriceModels= WaybillPriceModel::query()->with(["logistic","province","city","unit"])->orderBy('id', 'DESC');
        if ($data){
            if ($request->input('logistic_id')){
                $waybillPriceModels=$waybillPriceModels->where('logistic_id',$request->input('logistic_id'));
            }
            if ($request->input('province_id')){
                $waybillPriceModels=$waybillPriceModels->where('province_id',$request->input('province_id'));
            }
            $waybillPriceModels=$waybillPriceModels->paginate($request->input('paginate')?$request->input('paginate'):50);
            return view('maintenance.priceModel.waybillPriceModel.index',['waybillPriceModels'=>$waybillPriceModels,'logistics'=>$logistics,'provinces'=>$provinces,'filterData'=>$data]);
        }else{
            $waybillPriceModels= $waybillPriceModels->paginate(50);
            return view('maintenance.priceModel.waybillPriceModel.index',['waybillPriceModels'=>$waybillPriceModels,'logistics'=>$logistics,'provinces'=>$provinces,'filterData'=>$data]);
        }
    }


    public function create()
    {
        if(!Gate::allows('计费模型-录入')){ return redirect(url('/'));  }
        $logistics=app('LogisticService')->getSelection(["id","name"],"物流");
        $regions=Region::query()->whereIn("type",[1,2])->get();
        $units=Unit::query()->get();
        return view('maintenance.priceModel.waybillPriceModel.create',['logistics'=>$logistics,'regions'=>$regions,'units'=>$units]);
    }


    public function store(Request $request)
    {
        if(!Gate::allows('计费模型-录入')){ return redirect(url('/'));  }
        $this->validateWaybillPriceModel($request)->validate();
        $waybillPriceModel=$request->input('WaybillPriceModel');
        $waybillPriceModelIs=WaybillPriceModel::query()->where('logistic_id',$waybillPriceModel['logistic_id'])->where('province_id',$waybillPriceModel['province_id'])->where('unit_id',$waybillPriceModel['unit_id']);
        if (isset($waybillPriceModel['city_id'])){
            $waybillPriceModelIs=$waybillPriceModelIs->where('city_id',$waybillPriceModel['city_id']);
        }
        if (isset($waybillPriceModel['range_min'])){
            $waybillPriceModelIs=$waybillPriceModelIs->where('range_min',$waybillPriceModel['range_min']);
        }
        if (isset($waybillPriceModel['range_max'])){
            $waybillPriceModelIs=$waybillPriceModelIs->where('range_max',$waybillPriceModel['range_max']);
        }
        $waybillPriceModelIs=$waybillPriceModelIs->first();
        if (!$waybillPriceModelIs){
            if (isset($waybillPriceModel['city_id'])){
                $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NULL',[$waybillPriceModel['logistic_id'],$waybillPriceModel['province_id']])->first();
                if ($waybillPriceModelProvince){
                    return redirect()->back()->with('successTip','已存在省份模型，无需录入城市模型');
                }
            }else{
                $waybillPriceModelProvince=WaybillPriceModel::query()->whereRaw('logistic_id = ? AND province_id = ? AND city_id IS NOT NULL',[$waybillPriceModel['logistic_id'],$waybillPriceModel['province_id']])->first();
                if ($waybillPriceModelProvince){
                    return redirect()->back()->with('successTip','已存在城市模型，无法录入省份模型');
                }
            }
            if ($waybillPriceModel['base_fee']==null){ unset($waybillPriceModel['base_fee']);}
            if ($waybillPriceModel['initial_weight']==null){unset($waybillPriceModel['initial_weight']);}
            $waybillPriceModel=WaybillPriceModel::query()->create($waybillPriceModel);
            event(new WaybillPriceModelEvent($waybillPriceModel));
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            return redirect('maintenance/priceModel/waybillPriceModel')->with('successTip','新计费模型录入成功');
        }else{
            return redirect()->back()->with('successTip','该计费模型已存在');
        }
    }



    public function edit($id)
    {
        if(!Gate::allows('计费模型-编辑')){ return redirect(url('/'));  }
        $waybillPriceModel=WaybillPriceModel::query()->find($id);
        $logistics=app('LogisticService')->getSelection(["id","name"],"物流");
        $regions=Region::query()->whereIn("type",[1,2])->get();
        $units=Unit::query()->get();
        return view('maintenance.priceModel.waybillPriceModel.edit',['waybillPriceModel'=>$waybillPriceModel,'logistics'=>$logistics,'regions'=>$regions,'units'=>$units]);
    }


    public function update(Request $request, $id)
    {
        if(!Gate::allows('计费模型-编辑')){ return redirect(url('/'));  }
        $this->validateWaybillPriceModel($request)->validate();
        $waybillPriceModel=WaybillPriceModel::query()->find($id);
        $data=$request->input('WaybillPriceModel');
        if ($data['base_fee']==null){ unset($data['base_fee']);}
        if ($data['initial_weight']==null){unset($data['initial_weight']);}
        $waybillPriceModel->fill($data);
        if ($waybillPriceModel->save()){
            event(new WaybillPriceModelEvent($waybillPriceModel));
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            return redirect('maintenance/priceModel/waybillPriceModel')->with('successTip','新计费模型修改成功');
        }
    }

    public function destroy($id)
    {
        if(!Gate::allows('计费模型-删除')){ return redirect(url('/'));  }
        $waybillPriceModel=WaybillPriceModel::query()->find($id);
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($waybillPriceModel),Auth::user()['id']);
        $result=$waybillPriceModel->delete();
        return ['success'=>$result];
    }


    public function import(Request $request){
        if(!Gate::allows('计费模型-录入')){ return redirect(url('/'));  }
        $fileSuffix=$request->file('file')->getClientOriginalExtension();
        if ($fileSuffix=='xlsx'||$fileSuffix=='xlsm'||$fileSuffix=='xltx'||$fileSuffix=='xltm'||$fileSuffix=='xls'||$fileSuffix=='xlt'||$fileSuffix=='ods'||$fileSuffix=='ots'||$fileSuffix=='slk'
            ||$fileSuffix=='xml'||$fileSuffix=='gnumeric'||$fileSuffix=='htm'||$fileSuffix=='html'||$fileSuffix=='csv'||$fileSuffix=='tsv'){
            $isOverride = $request->input('isOverride');
            ini_set('max_execution_time',2500);
            ini_set('memory_limit','1526M');
            $extension=$request->file()['file']->getClientOriginalExtension();
            $extension[0] = strtoupper($extension[0]);
            Excel::import(new WaybillPriceModelsImport($isOverride),$request->file()['file']->path(),null,$extension);
            if (Cache::has('error')){
                return '<h1 class="text-danger">导入Excel失败<br><p style="color: red">'.Cache::pull('error').'</p></h1>';
            }else{
                $exception=Cache::get('exception');
                $a='';
                for ($i=0;$i<count($exception);$i++){$a.=implode(',',$exception[$i]).'&#10'; };
                app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
                return '<h1 class="text-danger">导入Excel成功<br><textarea style="width: 50%;height: 50%">'.$a.'</textarea></h1>';
            }
        }else{
            return '<h1 class="text-danger">失败<br><p style="color: red">不支持该文件类型</p></h1>';
        }
    }

    protected function validateWaybillPriceModel(Request $request){
        $min = $request->input('WaybillPriceModel.range_min');
        $validator= Validator::make($request->input(),[
            'WaybillPriceModel.province_id'=>'required|integer',
            'WaybillPriceModel.logistic_id'=>'required|integer',
            'WaybillPriceModel.unit_id'=>'required|integer',
            'WaybillPriceModel.city_id'=>'nullable|integer',
            'WaybillPriceModel.range_min'=> 'nullable|min:0|numeric|max:999999',
            'WaybillPriceModel.range_max'=> "nullable|min:{$min}|numeric|max:999999",
            'WaybillPriceModel.unit_price'=>'required|min:0|numeric|max:999999',
            'WaybillPriceModel.base_fee'=>'nullable|min:0|numeric|max:999999',
            'WaybillPriceModel.initial_weight'=>'nullable|min:0|numeric|max:999999',
        ],[
            'required'=>':attribute 为必填项',
            'min'     =>':attribute 数值过小',
            'max'      => ':attribute 数值过大',
            'numeric' =>':attribute 应为数字',
            'integer'=> ':attribute 选择错误',
        ],[
            'WaybillPriceModel.province_id'=>'省份',
            'WaybillPriceModel.logistic_id'=>'承运商',
            'WaybillPriceModel.unit_id'=>'计重单位',
            'WaybillPriceModel.city_id'=>'城市',
            'WaybillPriceModel.range_min'=>'价格区间最小值',
            'WaybillPriceModel.range_max'=>'价格区间最大值',
            'WaybillPriceModel.unit_price'=>'单价',
            'WaybillPriceModel.base_fee'=>'起步费',
            'WaybillPriceModel.initial_weight'=>'始重',
        ]);
        return $validator;
    }
}
