<?php

namespace App\Http\Controllers\api\thirdPart\flux;

use App\Batch;
use App\Http\Controllers\Controller;
use App\OracleActAllocationDetails;
use App\Order;
use App\OrderBin;
use App\OrderCommodity;
use App\Owner;
use App\Services\CommodityService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Zttp\Zttp;

class SortingController extends Controller
{
    /**
     * 新增被通知的波次列表（一个以上的波次），并且保存在本地数据库，供get波次使用
     * 接收：request[(下边newBatch的字段)]
     * 返回：Response{return{returnFlag(1/0),returnCode(0000/0001),returnDesc,resultInfo}}
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|Response|\Symfony\Component\HttpFoundation\JsonResponse
     *
     * 2021-01-20 zzd 因同步订单,波次等已上线,弃用该通知接口
     */
    public function newBatch(Request $request)
    {
//       $requestArr=$request->all();
        app('LogService')->log(__METHOD__, 'issued_' . __FUNCTION__, json_encode($request->all()));
//        !$requestArr?$requestArr=json_decode($request->getContent(),true):false;
//        $errors=$this->newBatchValidator($requestArr)->errors();
//        if(count($errors)>0){
//            app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, 'fields wrong, see Errors report please.'.'|'.json_encode($request->all()).'|'.json_encode($errors));
//            return response()->json(['Response'=>['return'=>['returnFlag'=>'0','returnCode'=>'0001',
//                'returnDesc'=>':Failure','resultInfo'=>'','errors'=>$errors]]])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
//        }
//        $requestBatches = $requestArr['request']?? '';
//
//        foreach ($requestBatches as $requestBatch){
//            $requestBatch['edittime']&&strpos(trim($requestBatch['edittime']),' ')?$editTimeFormat='Y-m-d H:i:s':$editTimeFormat='YmdHis';
//            $batch=Batch::query()->firstOrCreate(['code' => $requestBatch['waveno']]);
//
//            if(!$batch)$batch=new Batch();
//            $batch->fill([
//                    'code' => $requestBatch['waveno'],
//                    'wms_type' => $requestBatch['batch_type']??'',
//                    'wms_status' => $requestBatch['docstatus']??'',
//                    'status' => '未处理',
//                    'wms_created_at' => $requestBatch['edittime']?Carbon::createFromFormat($editTimeFormat,$requestBatch['edittime']):'',
//            ]);
//            $batch->save();
//            $oracleAlloactions=OracleActAllocationDetails::query()->where('waveno',$requestBatch['waveno'])->get();
//            foreach($requestBatch['order_list'] as $requestOrder){
//                $owner=Owner::query()->where('code',$requestOrder['customerid'])->first();
//                $order=app("OrderService")->first(['code'=>$requestOrder['docno']]);
//                if(!$order){
//                    $order=app("OrderService")->createOrder([
//                        'batch_id' => $batch['id'],
//                        'code' => $requestOrder['docno'],
//                        'owner_id' => $owner['id'],
//                        'wms_status' => $requestOrder['docstatus']??'波次下发',
//                        'status' => '未处理',
//                    ]);
//                    app('LogService')->log(__METHOD__,__FUNCTION__,'创建 Order'.json_encode($order));
//                }else{
//                    $order['batch_id']= $batch['id'] ;
//                    $order['owner_id']=$order['owner_id']??$owner['owner_id'];
//                    $order['wms_status']=$order['wms_status']??$requestOrder['docstatus']??'波次下发';
//                    $order['status']=$order['status']??'未处理';
//                }
//                $order->save();
//                OrderBin::query()->firstOrCreate([
//                    'order_id' => $order['id'],
//                    'number' => $requestOrder['reservedfield01'],
//                ]);
//                foreach($requestOrder['barcode_list'] as $requestBarcode){
//                    $orderCommodity=OrderCommodity::query()
//                        ->where('order_id',$order['id'])->where('wms_ptltaskid',$requestBarcode['ptltaskid'])->first();
//                    if(!$orderCommodity){
//                        /** @var CommodityService $commodityService */
//                        $commodityService=app('CommodityService');
//                        $commodity=$commodityService->syncBarcodes($requestBarcode['alternate_sku1'],$owner['id'],$requestBarcode['sku']);
//                        $orderCommodity=OrderCommodity::query()->firstOrCreate(['order_id'=>$order['id'],'commodity_id'=>$commodity['id']]);
//                        if(!$orderCommodity){
//                            $orderCommodity = new OrderCommodity([
//                                'order_id' => $order['id'],
//                                'commodity_id' => $commodity['id'],
//                                'amount' => $requestBarcode['fmqty_each']??0,
//                                'wms_ptltaskid' => $requestBarcode['ptltaskid'],
//                            ]);
//                        }else{
//                            $orderCommodity['order_id']=$order['id'];
//                            $orderCommodity['commodity_id']=$commodity['id'];
//                            $orderCommodity['amount']=$requestBarcode['fmqty_each']??0;
//                            $orderCommodity['wms_ptltaskid']=$requestBarcode['ptltaskid']??0;
//                        }
//                        $allocation=$oracleAlloactions->where('orderno',$requestOrder['docno'])->where('sku',$commodity['sku'])->where('qty',$requestBarcode['fmqty_each'])->first();
//                        if($allocation)
//                            $orderCommodity['location'] = $allocation['location'];
//                        $orderCommodity->save();
//                    }
//                }
//            }
//        }
        return response()->json(['Response'=>['return'=>['returnFlag'=>'1','returnCode'=>'0000',
            'returnDesc'=>'消息处理成功:Success','resultInfo'=>'']]])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    protected function newBatchValidator(array $data)
    {
        return Validator::make($data, [
            'request' => ['required', 'array', 'min:1'],
            'request.*.waveno' => ['required', 'string', 'max:191'],
            'request.*.taskprocess' => ['nullable', 'string', 'max:191'],
            'request.*.edittime' => ['nullable', 'string', 'max:191'],
            'request.*.batch_type' => ['nullable', 'string', 'max:191'],
            'request.*.docstatus' => ['nullable', 'string', 'max:191'],
            'request.*.batch_created_at' => ['nullable', 'string', 'max:191'],
            'request.*.order_list' => ['required', 'array', 'min:1'],
            'request.*.order_list.*.docno' => ['required', 'string', 'max:191'],
            'request.*.order_list.*.customerid' => ['required', 'string', 'max:191','exists:owners,code'],
            'request.*.order_list.*.docstatus' => ['nullable', 'string', 'max:191'],
            'request.*.order_list.*.reservedfield01' => ['required',  'max:191'],
            'request.*.order_list.*.barcode_list' => ['required_unless:request.*.order_list.*.docstatus,90', 'array'],
            'request.*.order_list.*.barcode_list.*.alternate_sku1' => ['required', 'string', 'max:191'],
            'request.*.order_list.*.barcode_list.*.descr_c' => ['required', 'string', 'max:191'],
            'request.*.order_list.*.barcode_list.*.fmqty_each' => ['required', 'numeric'],
            'request.*.order_list.*.barcode_list.*.ptltaskid' => ['required', 'string', 'max:191'],
        ]);
    }

    /**
     * 新增被通知的取消订单
     * 接收：docno（订单号）,docstatus（状态，唯一:canceled）
     * 返回：Response{return{returnFlag(1/0),returnCode(0000/0001),returnDesc,resultInfo}} 1和0000成功，0和0001失败
     */
    public function newCanceledOrder(Request $request)
    {
        $requestArr=$request->all();
        !$requestArr?$requestArr=json_decode($request->getContent(),true):false;
        Controller::logS(__METHOD__,__FUNCTION__,"接收到WMS下发取消单：".$request->getContent());
        $errors=$this->newCanceledOrderValidator($requestArr)->errors();
        if(count($errors)>0){
            app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, 'fields wrong, see Errors report please.'.'|'.json_encode($request->all()).'|'.json_encode($errors));
            return response()->json(['Response'=>['return'=>['returnFlag'=>'0','returnCode'=>'0001',
                'returnDesc'=>':Failure','resultInfo'=>'','errors'=>$errors]]])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }
        $order = app("OrderService")->first(['code'=>$requestArr['docno']]);
        $order->cancel();
        return response()->json(['Response'=>['return'=>['returnFlag'=>'1','returnCode'=>'0000',
            'returnDesc'=>'消息处理成功:Success','resultInfo'=>'']]])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    protected function newCanceledOrderValidator(array $data)
    {
        return Validator::make($data, [
            'docno' => ['required', 'string', 'max:191', 'exists:orders,code'],
            'docstatus' => ['required', 'string', 'max:191'],
        ]);
    }



    public function informBinAssignment(Batch $batch)
    {
        $apiUrl=config('api.flux.inform.binAssignment');
        if(config('api.faking')){$apiUrl=url(config('api.fake_flux_informBinAssignment'));}
        $sendingData=['request'=>[]];
        $batch->orders()->each(function(Order $order)use($batch,&$sendingData){
            $sendingData['request'][]=[
                'batch_id'=>$batch['code'],
                'status'=>'00',//原来是beforeSorting，改成了00
                'order_id'=>$order['code'],
                'bin'=>$order->bin()->first()['number']
            ];
        });
        $response=null;
        try {
            $response=Zttp::post($apiUrl,$sendingData);
        }catch (\Exception $e){
            app('LogService')->log(__METHOD__,'error_'.__FUNCTION__,json_encode($sendingData).'|catch:'.$e->getMessage());
            return false;
        }
        $reJson=$response->json();
        if(!$reJson || (!isset($reJson['Response'])||!isset($reJson['Response']['return'])) || $reJson['Response']['return']['returnFlag']!='1'){
            app('LogService')->log(__METHOD__,'error_'.__FUNCTION__,'$sending:'.json_encode($sendingData).'$response:'.$response->body());
            return false;
        }
        return true;
    }

    public function informBatchFinished(Batch $batch){
        $sendingData=['request'=>[]];
        $batch->orders()->each(function (Order $order)use($batch,&$sendingData){
            $order->orderCommodities()->each(function (OrderCommodity $orderCommodity)use($batch,$order,&$sendingData){
                $bin=$order->bin()->first();
                $sendingData['request'][]=[
                    'ptltaskid'=>$orderCommodity['wms_ptltaskid'],
                    'batch_id'=>$batch['code'],
                    'status'=>'80', //原来是isSorted,改成了80
                    'order_id'=>$order['code'],
                    'bin'=>$bin?$bin['number']:'',
                    'docstatus'=>'success',
                    'sku'=>$orderCommodity->commodity()->first()?$orderCommodity->commodity()->first()['sku']:'',
                    'amount'=>'0',
                ];
            });
        });
        $informApiUrl = config('api.flux.inform.batchFinished');
        try{
            $response=Zttp::post($informApiUrl,$sendingData);
            $result=$response->json();
            if(!$result||!$result['Response']['return']['returnFlag']||$result['Response']['return']['returnCode']!='0000'){
                app('LogService')->log(__METHOD__,'error_'.__FUNCTION__,'$sending:'.json_encode($sendingData).'|$response:'.$response->body());
                return false;
            }
        }
        catch(\Exception $e){
            app('LogService')->log(__METHOD__,'error_'.__FUNCTION__,'catch:'.$e->getMessage());
            return false;
        }
        app('LogService')->log(__METHOD__,'temp_'.__FUNCTION__,'$sending:'.json_encode($sendingData).'|$response:'.$response->body());
        return true;
    }
}
