<?php

namespace App\Http\Controllers;

use App\Commodity;
use App\Events\InformWMSReceivedEvent;
use App\OrderIssue;
use App\Owner;
use App\RejectedBill;
use App\RejectedBillItem;
use App\Services\CommodityService;
use App\Services\RejectedBillService;
use App\WMSReflectReceive;
use App\WMSReflectReceiveSku;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Zttp\Zttp;

class RejectedBillItemController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    public function apiStore(Request $request)
    {
        if(!Gate::allows('退货管理-录入')){
            return ['success'=>'false','failure_info'=>'没有权限'];
        }
        $errorFields= $this->validator($request->all())->errors()->getMessages();
        if(!empty($errorFields)){
            return ['success'=>'false','error_fields'=>$errorFields,'failure_info'=>'fileds error'];
        }
        $rejectedBillItem=RejectedBillItem::where('barcode_goods',$request->input('barcode_goods'))
            ->where('id_quality_label',$request->input('id_quality_label'))
            ->where('id_rejected_bill',$request->input('id_rejected_bill'))->first();
        if($rejectedBillItem){
            $rejectedBillItem['amount']+=$request->input('amount');
            if($request->input('name_goods')){
                $rejectedBillItem['name_goods']=$request->input('name_goods');
            }
            $rejectedBillItem->update();
        }else{
            $rejectedBillItem=new RejectedBillItem($request->all());
            $rejectedBillItem->save();
        }

        if (!$rejectedBillItem->rejectedBill || !$rejectedBillItem->rejectedBill->owner)return ['success'=>'false','failure_info'=>'退货单或货主不存在'];

//        /** @var CommodityService $commodityService */
//        $commodityService = app('CommodityService');
//        $commodity = $commodityService->ownerBarcodeSeekCommodityFirst(['name'=>$rejectedBillItem->rejectedBill->owner->name],$rejectedBillItem->barcode_goods);
//        if (!$commodity){
//            $commodity = $commodityService->ownerAndBarcodeFirstOrCreate($rejectedBillItem->rejectedBill->owner,$rejectedBillItem->barcode_goods);
//            if (!$commodity){
//                $commodity = $commodityService->create([
//                    "name" => $rejectedBillItem->name_goods,
//                    "owner_id" => $rejectedBillItem->rejectedBill->owner->id,
//                ]);
//                app('CommodityBarcodeService')->first([
//                    'commodity_id' => $commodity->id,
//                    'code' => $rejectedBillItem->barcode_goods,
//                ]);
//            }
//        }


        /** @var RejectedBill $rejectedBill */
        $rejectedBill = RejectedBill::query()->where('id',$request->input('id_rejected_bill'))->first();
        $rejectedBill->updateIsNewRejecting();
        $rejectedBill->syncOrderIssue();     // 同步问题件 修改问题件退货状态
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>'true','id'=>$rejectedBillItem['id']];
    }
    public function apiReviseOwner(Request $request)
    {
        if(!Gate::allows('退货管理-录入')){
            return ['success'=>'false','failure_info'=>'没有权限'];
        }
        $rejectedBill = RejectedBill::query()
            ->where('id',$request->input('id_rejected_bill'))
            ->update(['id_owner'=>$request->input('commodityOwnerId')]);
        if ($rejectedBill) return ['success'=>'true'];
        return ['success'=>'false','message'=>'校正货主失败!'];
    }

    public function apiUpdate(Request $request)
    {
        if(!Gate::allows('退货管理-编辑')){
            return ['success'=>'false','failure_info'=>'没有权限'];
        }
        $errorFields= $this->validator($request->all())->errors()->getMessages();
        if(!empty($errorFields)){
            return ['success'=>'false','error_fields'=>$errorFields,'failure_info'=>'fileds error'];
        }
        $rejectedBillItem=RejectedBillItem::where('id',$request->input('id'))->first();
        if(!$rejectedBillItem){
            return ['success'=>'false','failure_info'=>'数据库没有相应记录，请刷新后重加'];
        }else{
            $rejectedBillItem->fill($request->all());
            $rejectedBillItem->update();
            //$rejectedBillItem->injectCommodityName();  Haozi 2020-12-09
            /** @var RejectedBill $rejectedBill */
            $rejectedBill = RejectedBill::query()->where('id',$rejectedBillItem->id_rejected_bill)->first();
            $rejectedBill->updateIsNewRejecting();
            $rejectedBill->syncOrderIssue(); // 同步问题件 修改问题件退货状态
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            return ['success'=>'true','id'=>$rejectedBillItem['id']];
        }
    }


    public function collectionsToPackConfirm(Collection $rejectedBillItems)
    {
        $ids=[];
        $rejectedBillItems->each(function ($item)use(&$ids){
            $ids[]=$item->id;
        });
        if(!$ids)return ['success'=>'false','fail_info'=>'没有内容'];
        $collections=new Collection($ids);
        $i=0;
        $collections->each(function ($id)use(&$i,$ids){
            $rejectedBillItems=RejectedBillItem::whereIn('id', [$ids[$i]]);
            $rejectedBillItems->each(function(RejectedBillItem $rejectedBillItem)use(&$havingFail){
                $rejectedBill=RejectedBill::find($rejectedBillItem['id_rejected_bill']);
                $owner = Owner::find($rejectedBill['id_owner']);
                if(strstr($owner->name??'','笕尚')){
                    app('LogService')->log(__METHOD__,'找不到表','121行');
//                    $rejected=new Rejected();
//                    $rejected->fill($rejectedBill->toArray());
//                    $rejected->fill($rejectedBillItem->toArray());
                    $rejected=new Rejected();
                    $rejected->fill($rejectedBill->toArray());
                    $rejected->fill($rejectedBillItem->toArray());
                    $rejectedJianshang=new api\thirdPart\jianshang\RejectedController();
                    $sended=$rejectedJianshang->sendRejected($rejected);
                    if(!$sended){
                        echo '<h1>数据发送给笕尚失败，请通知IT相关负责人</h1>';
                        app('LogService')->log(__METHOD__,'error','数据发送给笕尚失败');
                        $havingFail++;
                        return false;
                    }
                }
            });
            $i++;
            if($i%30==0)
                sleep(1);
        });

        return 'yes'.$i;
    }
    public function apiPackConfirm(Request $request)
    {
        if(!Gate::allows('退货管理-录入')){
            return ['success'=>'false','fail_info'=>'没有权限'];
        }
        $ids=$request->input('ids');
        if(!$ids)return ['success'=>'false','fail_info'=>'没有内容'];
        $rejectedBillItems=RejectedBillItem::whereIn('id', $ids)->get();
        if($rejectedBillItems->count()==0){
            return ['success'=>'false','fail_info'=>'没有匹配到相应内容'];
        }
        $item=$rejectedBillItems->first();
        $rejectedBill = RejectedBill::query()->find($item['id_rejected_bill']);
        $rejectedBill->syncOrderIssue();    // 同步问题件 修改问题件退货状态
        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,'请求处理退单：'.$rejectedBill['logistic_number_return'],Auth::user()['id']);
        $downloadedSkus = WMSReflectReceive::downloadedSkus($rejectedBill['logistic_number_return'],true);
        $isGotMoreThenDownloaded=WMSReflectReceiveSku::isItemsOverDownloadedSkus($rejectedBillItems,$downloadedSkus);
        $isJianshang=(function($rejectedBill){
            $owner = Owner::find($rejectedBill['id_owner']);
            if(strstr($owner->name??'','笕尚')){
                return true;
            }
            return false;
        })($rejectedBill);
        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"当前，实收件：（".json_encode($rejectedBillItems)."）}，下载件：（"
            .json_encode($downloadedSkus)."）}，退单号：{$rejectedBill['logistic_number_return']}",null);
        $shouldStore=!$isGotMoreThenDownloaded    //没有录入超过下载货物数
            && !($rejectedBill['is_loaded']==1)//并且不是已入库////去掉了或无需入库的判断：||$rejectedBill['is_loaded']===null
            &&config('api.api_switch_receive_to_wms');//并且配置开
        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"自动入库：{$shouldStore}||isGotMoreThenDownloaded={$isGotMoreThenDownloaded}/rejectedBill['is_loaded']={$rejectedBill['is_loaded']}/rejectedBill['is_loaded']={$rejectedBill['is_loaded']}",null);



        if($shouldStore){
            if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,'满足条件，准备从网页主动请求富勒入库：'.$rejectedBill['logistic_number_return'],Auth::user()['id']);
            $result_transferToWms=(new InformWMSReceivedEvent($rejectedBill))->directRun();
            if($result_transferToWms=='fail')return ['success'=>'false','fail_info'=>'提交至WMS错误，请手动校验、操作WMS并通知相关人员'];
            if($result_transferToWms=='exception')return ['success'=>'exception','fail_info'=>'提交至WMS部分成功，存在异常情况，请校对WMS'];
            $isLoaded=false;
            if($isJianshang){
                $isLoaded=true;
            }
            if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,'标记前端是否入库为：'.$isLoaded,Auth::user()['id']);
            return ['success'=>'true','bill_is_loaded'=>$isLoaded];
        }

        $remoteResultStr='';
        if($isJianshang){
            if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"不满足入库条件，准备发送给笕尚处理，退单号：{$rejectedBill['logistic_number_return']}",Auth::user()['id']);
            $remoteResultStr=$this->sendRejectedToThirdPart2($rejectedBillItems,$rejectedBill);//不能入库所以发送给笕尚处理   !!!!
        }

        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"前端退单处理请求完成：笕尚入库状态为：{$remoteResultStr}，退单号: {$rejectedBill['logistic_number_return']}，退单ID：{$rejectedBill['id']}，form表单：".json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>'true','remote_result'=>$remoteResultStr];
    }

    public function sendRejectedToThirdPart(Collection $items,$rejectedBill):bool {
        $havingFail=0;
        if(!config('api.API_FAKING')){
            $items->each(function(RejectedBillItem $rejectedBillItem)use(&$havingFail,$rejectedBill){
//                $rejected=new Rejected();
//                app('LogService')->log(__METHOD__,'找不到表','200行');
//                $rejected->fill($rejectedBill->toArray());
//                $rejected->fill($rejectedBillItem->toArray());
                $rejected=$rejectedBill->toArray();
                $rejected = array_merge($rejected, $rejectedBillItem->toArray());
                $rejectedJianshang=new api\thirdPart\jianshang\RejectedController();
                $sended=$rejectedJianshang->sendRejected($rejected);
                if(!$sended){
                    echo '<h1>数据发送给笕尚失败，请通知IT相关负责人</h1>';
                    app('LogService')->log(__METHOD__,'error_'.__FUNCTION__.'_'.$rejectedBillItem['id'],'数据发送给笕尚失败');
                    $havingFail++;
                    return false;
                }
            });

            $receives=WMSReflectReceive::where('ASNREFERENCE3',$rejectedBill['logistic_number_return'])->where('is_uploaded',0)->get();
            $receives->each(function ($receive){
                $receive['is_uploaded']=1;
                $receive->save();
            });
        }

        if($havingFail>0){
            app('LogService')->log(__METHOD__,'error_'.__FUNCTION__.'_'.$rejectedBill['id'],"$havingFail/{$items->count()} 条记录没有发送成功",Auth::user()['id']);
            return false;
        }
        return true;
    }

    public function sendRejectedToThirdPart2(Collection $items,$rejectedBill) {
        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"进入发送方法，发送给笕尚处理，退单号：{$rejectedBill['logistic_number_return']}",Auth::user()['id']);
        if($rejectedBill['is_loaded']!=0){
            if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"进入发送方法，但退单已入库，跳出！退单号：{$rejectedBill['logistic_number_return']}",Auth::user()['id']);
            return true;
        }
//        $rejected=new Rejected();
        $rejected=$rejectedBill->toArray();
//        $rejected->fill($rejectedBill->toArray());
        $goodses=[];
        $items->each(function(RejectedBillItem $item)use(&$goodses){
            $goodses[]=$item->toArray();
        });
        $rejectedJianshang=new api\thirdPart\jianshang\RejectedController();
        $rejected['goodses']=$goodses;
        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"进入发送方法，将商品转成数组，准备进入接口！退单号：{$rejectedBill['logistic_number_return']}",Auth::user()['id']);
        $resultStr= $rejectedJianshang->sendRejected2($rejected);   //！！！

        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"发送笕尚取得结果是：{$resultStr}！退单号：{$rejectedBill['logistic_number_return']}",Auth::user()['id']);
        if($resultStr=='fail'){
            if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"发送失败，笕尚取得结果是：{$resultStr}！返回前端。退单号：{$rejectedBill['logistic_number_return']}",Auth::user()['id']);
            return $resultStr;
        }
        //
        if($resultStr=='storable'){
            if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"发送成功，可入，但待推单，笕尚取得结果是：{$resultStr}！返回前端。退单号：{$rejectedBill['logistic_number_return']}",Auth::user()['id']);
            $rejectedBill = RejectedBill::find($rejectedBill['id']);
            $rejectedBill->is_loaded=2;
            $rejectedBill->save();
            $items->each(function(RejectedBillItem $item)use(&$goodses){
                $item['is_loaded']='待推单';
                $item->save();
            });

            if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"标记退单和商品为待推单！退单号：{$rejectedBill['logistic_number_return']}",Auth::user()['id']);
            //标记WMS所有该退单下的作废（为已上传) 。应检查这里是否正确！
//            $receives=WMSReflectReceive::where('ASNREFERENCE3',$rejectedBill['logistic_number_return'])->where('is_uploaded',0)->get();
//            $receives->each(function ($receive){
//                $receive['is_uploaded']=1;
//                $receive->save();
//            });
//            if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"标记退单在WMS映射表为已上传！退单号：{$rejectedBill['logistic_number_return']}",Auth::user()['id']);
        }
        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"处理完成，返回前端入库状态，标记笕尚取得结果是：{$resultStr}！退单号：{$rejectedBill['logistic_number_return']}",Auth::user()['id']);
        return $resultStr;
    }


    public function apiPackDestroy(Request $request)
    {
        if(!(Gate::allows('退货管理-录入')||Gate::allows('退货管理-编辑'))){
            return ['success'=>'false','failure_info'=>'没有权限'];
        }
        $ids=$request->input('ids');
        if(!$ids)return ['success'=>'false','fail_info'=>'没有内容'];
        $rejectedBillItems=RejectedBillItem::whereIn('id', $ids);

        $rejectedBillItems->each(function(RejectedBillItem $rejectedBillItem){
            $rejectedBillItem->delete();
        });

        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>'true'];
    }

    protected function validator(array $data,$isUpdate=false)
    {
        return Validator::make($data, [
            'id_rejected_bill' => ['required', 'numeric', 'exists:rejected_bills,id'],
            'barcode_goods' => ['required', 'string','max:60'],
            'name_goods' => ['nullable', 'string','max:219'],
            'amount' => ['numeric','required', 'max:99999'],
            'id_quality_label' => ['required','numeric',  'max:11'],
            'batch_number' => ['string', 'nullable',],
            'validity_at' => ['nullable','date_format:Y-m-d'],
            'remark' => ['nullable','string','max:191'],
        ],[],[
            'id_rejected_bill' =>'退单头',
            'barcode_goods' => '商品条码',
            'name_goods' => '商品名称',
            'amount' => '数量',
            'id_quality_label' => '品质',
            'batch_number' => '批次',
            'validity_at' => '效期',
            'remark' => '备注'
        ]);
    }
    public function apiGet(Request $request)
    {
        if(!Gate::allows('退货管理-查询')){
            return ['success'=>'false','failure_info'=>'没有权限'];}
        if(!$request->input('id_rejected_bill')){
            return ['success'=>'false','failure_info'=>'表头id不能为空'];
        }
        $rejectedBillItems = RejectedBillItem::where('id_rejected_bill',$request->input('id_rejected_bill'))->get();
        return ['success'=>'true','items'=>$rejectedBillItems->toArray()];
    }
    public function apiDelete(Request $request)
    {
        if(!Gate::allows('退货管理-删除')){
            return ['success'=>'false','failure_info'=>'没有权限'];}
        if(!$request->input('id')){
            return ['success'=>'false','failure_info'=>'传入id不能为空'];
        }
        $rejectedBillItem = RejectedBillItem::find($request->input('id'));
        if(!$rejectedBillItem)return ['success'=>'false','id'=>$request->input('id')];
        $rejectedBillItem->forceDelete();
        /** @var RejectedBill $rejectedBill */
        $rejectedBill = RejectedBill::query()->where('id',$rejectedBillItem->id_rejected_bill)->first();
        $rejectedBill->syncOrderIssue(); // 同步问题件 修改问题件退货状态
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($rejectedBillItem),Auth::user()['id']);
        return ['success'=>'true','id'=>$request->input('id')];
    }
    /**
     * Display the specified resource.
     *
     * @param  \App\RejectedBillItem  $rejectedBillItem
     * @return \Illuminate\Http\Response
     */
    public function show(RejectedBillItem $rejectedBillItem)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\RejectedBillItem  $rejectedBillItem
     * @return \Illuminate\Http\Response
     */
    public function edit(RejectedBillItem $rejectedBillItem)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\RejectedBillItem  $rejectedBillItem
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, RejectedBillItem $rejectedBillItem)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\RejectedBillItem  $rejectedBillItem
     * @return \Illuminate\Http\Response
     */
    public function destroy(RejectedBillItem $rejectedBillItem)
    {
        //
    }
}
