<?php

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

use App\Batch;
use App\CommodityBarcode;
use App\Http\Controllers\Controller;
use App\OracleDOCWaveDetails;
use App\Order;
use App\OrderCommodity;
use App\Services\LogService;
use App\SortingStation;
use App\User;
use App\UserToken;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class SortingController extends Controller
{

    function login(Request $request){
        $name = $request->input('name');
        $password = $request->input('password');
        $station_id = $request->input('station_id');
        $errors=$this->loginValidator($request->all())->errors();
        if(count($errors)>0){
            app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, json_encode($request->all()).'|'.json_encode($errors));
            return response()->json(['result'=>'failure','fail_info'=>'error','errors'=>$errors])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }
        $user=User::query()->where('name',$name)->first();
        if(!$user||!Hash::check($password, $user['password'])){
            return ['result'=>'failure','fail_info'=>'认证错误'];
        }
        $station = SortingStation::findOrCreate($station_id);
        $station->login();
        return ['result'=>'success','token'=>$user->token()];
    }

    protected function loginValidator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:191'],
            'password' => ['required', 'string', 'max:191'],
            'station_id' => ['required', 'string', 'max:191'],
        ],[
            'required' => ':attribute 不能为空',
        ],[
            'name' => '用户名',
            'password' => '密码',
            'station_id' => '设备ID',
        ]);
    }


    function process(Request $request){
        $token = trim($request->input('token'));
        $station_id = $request->input('station_id');
        $batch_id = $request->input('batch_id');
        $errors=$this->processValidator($request->all())->errors();
        if(count($errors)>0){
            app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, json_encode($request->all()).'|'.json_encode($errors));
            return response()->json(['result'=>'failure','fail_info'=>'error','errors'=>$errors])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }
//        if(!UserToken::getUser($token)){
//            return ['result'=>'unauthority','fail_info'=>'无效令牌或令牌过期'];
//        }

        /** @var Batch $batch */
        $batch=Batch::query()->where('code',$batch_id)->orderBy('id','desc')->first();
        $data=[
            'result'=>'success',
            'station_id'=>$station_id,
            'batch_id'=>$batch_id,
            'orders'=>[]
        ];
        $ordersSorted=$batch->orders()->get()->sortBy(function(Order $order){
            return $order->bin()->first()['number'];
        });
        $ordersSorted->each(function(Order $order)use(&$data,$request){
            if($order['status']=='取消')return;
            $orderData=[
                'order_id'=>$order['code'],
                'owner'=>$order->owner()->first()['code'],
                'status'=>$order['status']=='未处理'?'available':$order['status'],
                'created_at'=>$order['created_at']->toDateTimeString(),
                'bin'=>(function()use($order){
                    $bin=$order->bin()->first()['number']??'';
                    if(!$bin){
                        $bin=OracleDOCWaveDetails::query()->where('orderno', 'SO201230003574')->get('seqno')->first()['seqno']??'';
                        LogService::log(__METHOD__,__FUNCTION__,'bin缺失补查:'.$bin.'. order:'.$order->toJson());
                        return $bin;
                    }
                    return $bin;
                })(),
                'barcodes'=>[]
            ];
            $order->orderCommodities()->each(function(OrderCommodity $orderCommodity)use(&$orderData,$request){
                $commodity=$orderCommodity->commodity()->first();
                if(!$commodity){
                    app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, '播种位数据准备出错，找不到订单对应的Commodity id的对象'.$orderCommodity['commodity_id'].'，是否表数据在波次生成后丢失？'.json_encode($request->all()));
                    return;
                }
                $barcodeStr=$commodity->barcodes()->get()->map(function(CommodityBarcode $barcode){
                    return $barcode['code'];
                })->filter(function($code){
                    return $code&&(!preg_match('/[\x{4e00}-\x{9fa5}]/u',$code));
                })->join(',');
                $orderData['barcodes'][]=[
                    'id'=>$orderCommodity['id']??'',
                    'barcode_id'=>$barcodeStr??'',
                    'name'=>$commodity['name']??'',
                    'sku'=>$commodity['sku']??'',
                    'amount'=>$orderCommodity['amount']??'',
                    'location'=>$orderCommodity['location']??'',
                ];
            });
            $data['orders'][]=$orderData;
        });

        $sendToWms=(new \App\Http\Controllers\api\thirdPart\flux\SortingController())->informBinAssignment($batch);
        if(!$sendToWms){
            app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, '播种位发送给WMS错误：'.json_encode($request->all()));
            return response()->json(['result'=>'failure','fail_info'=>'播种位发送给WMS错误，请联系管理员检查错误'])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }

        $station = SortingStation::findOrCreate($station_id);
        $station->setProcessingBatch($batch);
        return $data;
    }

    protected function processValidator(array $data)
    {
        return Validator::make($data, [
            'token' => ['required', 'string', 'max:191'],
            'station_id' => ['required', 'string', 'max:191'],
            'batch_id' => ['required', 'string', 'max:191','exists:batches,code'],
        ],[
            'required' => ':attribute 不能为空',
            'exists' => ':attribute 不存在',
        ],[
            'station_id' => '设备ID',
            'batch_id' => '波次号',
        ]);
    }

    function done(Request $request){
        $token = $request->input('token');
        $station_id = $request->input('station_id');
        $batch_id = $request->input('batch_id');
        app('LogService')->log(__METHOD__,  __FUNCTION__.'_request', '浩创的完成请求：'.json_encode($request->all()));
        $errors=$this->doneValidator($request->all())->errors();
        $failInfo='';
        foreach ($errors as $error){$failInfo.=$error[0].'; ';}
        if(count($errors)>0){
            app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, json_encode($request->all()).'|'.json_encode($errors));
            return response()->json(['result'=>'failure','fail_info'=>$failInfo,'errors'=>$errors])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }
        if(!UserToken::getUser($token)){
            return ['result'=>'unauthority','fail_info'=>'无效令牌或令牌过期'];
        }
        $batch=Batch::query()->where('code',$batch_id)->first();
        if($batch->status=='已处理'){
            app('LogService')->log(__METHOD__,'alert_'.__FUNCTION__,$batch['code'].'重复发送，波次已处理');
            return ['result'=>'failure','fail_info'=>$batch['code'].'重复发送，波次已处理'];
        }
        $sendToWms=(new \App\Http\Controllers\api\thirdPart\flux\SortingController())->informBatchFinished($batch);
        if(!$sendToWms){
            app('LogService')->log(__METHOD__, 'error' . __FUNCTION__, '发送给WMS错误：'.json_encode($request->all()));
            return response()->json(['result'=>'failure','fail_info'=>'发送给WMS错误，请联系管理员检查错误'])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }
        $batch->setProcessed();
        $station = SortingStation::query()->where('name',$station_id)->first();
        $station->clearProcessingBatch();
        return ['result'=>'success','batch_id'=>$batch_id];
    }
    protected function doneValidator(array $data)
    {
        return Validator::make($data, [
            'token' => ['required', 'string', 'max:191'],
            'station_id' => ['required', 'string', 'max:191','exists:sorting_stations,name'],
            'batch_id' => ['required', 'string', 'max:191','exists:batches,code'],
        ],[
            'required' => ':attribute 不能为空',
            'exists' => ':attribute 不存在',
        ],[
            'station_id' => '设备ID',
            'batch_id' => '波次号',
        ]);
    }

}
