<?php

namespace App\Http\Controllers;

use App\OrderPackage;
use App\PaperBox;
use App\Services\OrderPackageService;
use App\Services\OwnerService;
use App\Services\PackageService;
use App\Services\PackageStatisticsService;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;


class WeighController extends Controller
{
    public function index(Request $request,OwnerService $ownerService)
    {
        if(!Gate::allows('称重管理-查询')){ return redirect(url('/'));  }
        $paginateParams = $request->input();
        /** @var PackageService $application */
        $application = app('PackageService');
        $packages = $application->paginate($request);
        return view('package.weigh.index',['packages'=>$packages,'owners'=>$ownerService->getIntersectPermitting(),'paginateParams'=>$paginateParams]);
    }

    public function create()
    {
        if(!Gate::allows('称重管理-录入')){ return redirect(url('/'));  }
        $paperBoxes=PaperBox::select('id','model')->get();
        return view('package.weigh.create',['paperBoxes'=>$paperBoxes]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void
     * @throws
     */
    public function store(Request $request)
    {
        if(!Gate::allows('称重管理-录入')){ return redirect(url('/'));  }
        $this->validator($request)->validate();
        $logistic_number=$request->input('logistic_number');
        $weight=$request->input('weight');
        $batch_number=strtoupper($request->input('batch_number'));
        $order_code=$request->input('order_code');
        $paper_box_id=$request->input('paper_box_id');
//        $isSamePackBatch=$request->input('is_same_pack_batch');
        if($logistic_number&&$batch_number)return redirect('package/create')->with('successError','录入失败！波次号和快递单号只能填一项！');
        $package=null;
        $successTip = '操作成功';

        /** @var OrderPackage $package */
        if ($order_code){
            $package=OrderPackage::query()->with(['order'=>function($query)use($order_code){
                $query->where('code',$order_code) ;
            }])->first();
        }else{
            if($batch_number){
                $package=OrderPackage::query()->where('batch_number',$batch_number)->first();

            }elseif($logistic_number){
                $package=OrderPackage::query()->where('logistic_number',$logistic_number)->first();
            }
        }
        $accomplishToWMS=new api\thirdPart\flux\PackageController();


        if($batch_number){
            app('LogService')->log(__METHOD__,'活动波次开始同步_'.__FUNCTION__,json_encode($package),Auth::user()['name']);
//            $this->syncBatch($package->batch_number,$weight,null,null,null,Carbon::now(),null);
            $result=$accomplishToWMS->markWMSOnBatch($batch_number,$weight);



            OrderPackage::createPackagesFromBatchCode($batch_number,$weight);


            if($package&&$package->isActivityBatch())
                $package->unifyThisMeasureUnderSameBatch();

            if ($result['result']){
                Controller::logS(__METHOD__,'SUCCESS_'.__FUNCTION__,'批量更改波次上传成功'.$batch_number);
                $successTip = "批量录入波次成功！波次号：$batch_number";
                return redirect('package/create')->with('successTip', $successTip);
            }
            Controller::logS(__METHOD__,'error_'.__FUNCTION__,'批量更改波次上传异常:'.$result['message'].$batch_number);

            return redirect('package/create')->with('successError','录入失败！'.$result['message']);
        }
        if (!$package && !$logistic_number)return redirect('package/create')->with('successError','录入失败！系统内没有对应波次的包裹！');
        if ($package){
            if(!$package->batch_number)$package->batch_number=$batch_number;
            //if(!$package->order_code)$package->order_code=$order_code;
            $package->fetchAllFromOracle();
            $package->weight=$weight;
            if(!$package->paper_box_id)$package->paper_box_id=$paper_box_id;
            $result=$accomplishToWMS->accomplishToWMS($package);
            if ($result['result']){
                $package->uploaded_to_wms="是";
            }else{
                $package->uploaded_to_wms="异常";
            }
            $package->save();
            app('LogService')->log(__METHOD__,'create_'.__FUNCTION__,json_encode($package),Auth::user()['name']);
//            event(new WeighedEvent($package));

        }else{

            /** @var OrderPackageService */
            $package = app('OrderPackageService')->firstOrCreate($logistic_number,[
                'weight'=>$weight,
                'weighed_at'=>Carbon::now(),
                'uploaded_to_wms'=>"是",
            ]);
            $package->fetchAllFromOracle();
            $result=$accomplishToWMS->accomplishToWMS($package);
            $str = "录入包裹成功！";
            $str .= $package['logistic_number']?"快递单号：{$package['logistic_number']}":'';
            $str .= $order_code?", 订单号：{$order_code}":'';
            if(!$result||$result['result']=='false'){
                $package['uploaded_to_wms'] = '异常';
                $str = "录入包裹失败！";
                $str .= $package['logistic_number']?"快递单号：{$package['logistic_number']}":'';
                $str .= $order_code?", 订单号：{$order_code}":'';
                app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($package).json_encode($result).$str,Auth::user()['name']);
            }
            $package->save();
            $successTip = $str;


        }


        return redirect('package/create')->with('successTip', $successTip);
    }

    public function statistics(Request $request){
        $packages = app('PackageStatisticsService')->get($request->input());
        $owners=app('OwnerService')->getIntersectPermitting();
        $logistics=app('LogisticService')->getSelection();
        $ownerTemp = [];
        foreach ($owners as $owner){
            $ownerTemp[$owner->id] = $owner->name;
        }
        $ps = [];
        $logisticsTemp = [];
        foreach ($packages as $package){
            if (!($logisticsTemp[$package->logistic_id] ?? false))$logisticsTemp[$package->logistic_id] = true;
            if ($ps[$package->owner_id] ?? false){
                $ps[$package->owner_id][$package->logistic_id] = $package->count;
                $ps[$package->owner_id]["sum"] += (int)$package->count;
            }else{
                $ps[$package->owner_id] = [
                    $package->logistic_id => $package->count,
                    "sum" => (int)$package->count,
                    "owner_id" => $package->owner_id,
                    "owner_name" => $ownerTemp[$package->owner_id]
                ];
            }
        }
        foreach ($logistics as $index => $logistic){
            if (!($logisticsTemp[$logistic->id] ?? false))unset($logistics[$index]);
        }
        foreach ($ps as &$p){
            $p = json_encode($p,JSON_UNESCAPED_UNICODE);
        }
        return view('package.weigh.statistics',["packages"=>$ps,'owners'=>$owners,'logistics'=>$logistics]);
    }

    public function export(Request $request){
        if(!Gate::allows('称重管理-查询')){ return '没有权限';  }
        if ($request->checkAllSign ?? false){
            $params = $request->input();
            unset($params['checkAllSign']);
            $sql = app('PackageService')->getSql($params);
        }else{
            $sql=app('PackageService')->getSql(['id'=>$request->data]);
        }
        $row = ["货主","快递单号","波次号","订单号","物流公司","设备","重(KG)","长(cm)","宽(cm)","高(cm)","体积(cm³)","纸箱","状态","波次规则","称重时间","收件人","收件人电话"];
        $column = ["owner_name", "logistic_number", "batch_number", "order_code", "logistic_name","measuring_machine_name",
            "weight", "length", "width", "height", "bulk", "paper_box_name", "status","batch_rule","weighed_at","order_consignee_name","order_consignee_phone"];
        $rule = ["weighed_at"=> "mysqlDate"];
        $post = Http::post(config('go.export.url'),['type'=>'unify','sql'=>$sql, 'connection'=>'mysql',
            'row'=>json_encode($row,JSON_UNESCAPED_UNICODE), 'column'=>json_encode($column), 'rule'=>json_encode($rule)]);

        if ($post->status() == 500){
            throw new Exception($post->header("Msg"));
        }
        return response($post,200, [
            "Content-type"=>"application/octet-stream",
            "Content-Disposition"=>"attachment; filename=包裹信息-".date('ymdHis').'.xlsx',
        ]);
    }
    protected function validator(Request $request){
        $validator=Validator::make($request->input(),[
            'logistic_number'=>['required_without_all:batch_number,order_code'],
            'order_code'=>['required_without_all:logistic_number,batch_number'],
            'weight'=>'required|min:0|max:999999|numeric',
            'paper_box_id'=>'nullable|integer',
            'batch_number'=>['required_without_all:logistic_number,order_code']
        ],[
            'required'=>':attribute 为必填项',
            'max'=>':attribute 字符过多或输入值过大',
            'integer'=>':attribute 选择有误',
            'min'=>':attribute 不得为负',
            'numeric'=>':attribute 应为数字',
            'unique'=>':attribute 已存在',
            'required_without_all'=>':attribute 与快递单号或订单号至少选一项'
        ],[
            'logistic_number'=>'快递单号',
            'weight'=>'重量',
            'paper_box_id'=>'纸箱',
            'batch_number'=>'波次号',
            'order_code'=>'订单号',
        ]);
        return $validator;
    }

    public function statisticsExport(Request $request){
        if(!Gate::allows('称重管理-查询')){ return '没有权限';  }
        /** @var PackageStatisticsService $service */
        $service = app('PackageStatisticsService');

        if ($request->checkAllSign){
            $params = $request->input();
            unset($params['checkAllSign']);
            $data = $service->get($params);
        }else{
            /**@var PackageStatisticsService */
            $data = $service->get(['owner_id'=>$request->data]);
        }

        $owners=app('OwnerService')->getIntersectPermitting();
        $ownerTemp = [];
        foreach ($owners as $owner){
            $ownerTemp[$owner->id] = $owner->name;
        }


        $logisticsTemp = [];
        $ps = [];
        foreach ($data as $package){
            if (!($logisticsTemp[$package->logistic_id] ?? false))$logisticsTemp[$package->logistic_id] = true;
            if ($ps[$package->owner_id] ?? false){
                $ps[$package->owner_id][$package->logistic_id] = $package->count;
                $ps[$package->owner_id]["sum"] += (int)$package->count;
            }else{
                $ps[$package->owner_id] = [
                    $package->logistic_id => $package->count,
                    "sum" => (int)$package->count,
                    "owner_id" => $package->owner_id,
                    "owner_name" => $ownerTemp[$package->owner_id]
                ];
            }
        }

        $column = ["货主","总计"];

        $columnMap = [];
        $logistics=app('LogisticService')->getSelection();
        foreach ($logistics as $index => $logistic){
            if (!($logisticsTemp[$logistic->id] ?? false))unset($logistics[$index]);
            else {
                $columnMap[] = $logistic->id;
                $column[] = $logistic->name;
            }
        }

        $list = [];
        foreach ($ps as $p){
            $row = [$p["owner_name"],$p["sum"]];
            foreach ($columnMap as $id){
                $row[] = $p[$id] ?? 0;
            }
            $list[] = $row;
        }
        $post = Http::post(config('go.export.url'),['type'=>'base','data'=>json_encode(["row"=>$column,"list"=>$list],JSON_UNESCAPED_UNICODE)]);
        if ($post->status() == 500){
            throw new Exception($post->header("Msg"));
        }
        return response($post,200, [
            "Content-type"=>"application/octet-stream",
            "Content-Disposition"=>"attachment; filename=称重统计信息单-".date('ymdHis').'.xlsx',
        ]);
    }

}
