<?php

namespace App\Http\Controllers;

use App\Events\InformWMSReceivedEvent;
use App\Http\Controllers\Api\thirdPart\flux\ReceiveController;
use App\Logistic;
use App\OracleDOCOrderHeader;
use App\Owner;
use App\QualityLabel;
use App\Rejected;
use App\RejectedBill;
use App\RejectedBillItem;
use App\Services\OrderPackageCommoditiesService;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;
use Ramsey\Uuid\Uuid;

class RejectedBillController extends Controller
{
    function __construct()
    {

//        app()->bind('orderPackageCommoditiesService',OrderPackageCommoditiesService::class);
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        //
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        //
    }
    public function apiGetRecent()
    {
        if(!Gate::allows('退货管理-查询')){
            return ['success'=>'false','fail_info'=>'没有权限'];}
        $user=Auth::user();
        $rejectedBills = RejectedBill::query()->orderByDesc('id')->whereIn('id_owner',
            $user?$user->getPermittingOwnerIdsAttribute():[])->limit(20)->get();
        return ['success'=>'true','rejectedBills'=>$rejectedBills->toArray()];
    }


    public function apiStore(Request $request)
    {
        if(!Gate::allows('退货管理-录入')){
            return ['success'=>'false','fail_info'=>'没有权限'];
        }
        $softDeleted=RejectedBill::withTrashed()->where('logistic_number_return',$request->input('logistic_number_return'))->first();
        if($softDeleted&&$softDeleted->trashed()){
            $softDeleted->forceDelete();
        }
        if($request['is_loaded']=='null')$request['is_loaded']=null;
        $errorFields= $this->validator($request->all())->errors()->getMessages();
        if(!empty($errorFields)){
            return ['success'=>'false','error_fields'=>$errorFields,'fail_info'=>'fileds error'];
        }
        $rejectedBill=new RejectedBill($request->all());
        $rejectedBill['id_operator'] = Auth::user()['id'];
        $rejectedBill->save();
        $rejectedBill->syncOrderIssue();

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

    public function apiUpdate(Request $request)
    {
        if(!Gate::allows('退货管理-编辑')){
            return ['success'=>'false','fail_info'=>'没有权限'];
        }
        if($request['is_loaded']=='null')$request['is_loaded']=null;
        $errorFields= $this->validator($request->all(),true)->errors()->getMessages();
        if(!empty($errorFields)){
            return ['success'=>'false','error_fields'=>$errorFields,'fail_info'=>'fileds error'];
        }
        $rejectedBill=RejectedBill::find($request->input('id'));
        $rejectedBill->fill($request->all());
        $rejectedBill->save();
        $rejectedBill->syncOrderIssue();

        $this->log(__METHOD__,__FUNCTION__.'_'.$rejectedBill['id'],json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>'true'];
    }
    public function apiConfirmBeStored(Request $request)
    {
        if(!Gate::allows('退货管理-编辑')){
            return ['success'=>'false','fail_info'=>'没有权限'];
        }
        $rejectedBill = RejectedBill::find($request->input('id'));

        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"人工确认入库。退单号：".$rejectedBill['logistic_number_return'],Auth::user()['id']);
        $result_TransferToWMS=ReceiveController::accomplishToWMS($rejectedBill);

        $this->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        switch ($result_TransferToWMS){
            case 'success':
                $rejectedBill['is_loaded']=1;
                $rejectedBill->update();
                return ['success'=>true];
            case 'fail':
            case 'exception':return ['success'=>false];
        }
    }


    protected function validator(array $data,$isUpdate=false)
    {
        $mobileShouldBeRequired = 'required';
        $logistic=Logistic::find($data['id_logistic_return']);
        if($logistic){if(strstr($logistic['name'],'顺丰')){
            $mobileShouldBeRequired = 'nullable';
        }}
        $mobileDigits = '';
        if($data['mobile_sender']&&$data['mobile_sender'][0]=='1'){
            $mobileDigits = 'digits:11';
        }
        return Validator::make($data, [
            'id_owner' => ['required', 'numeric', 'exists:owners,id'],
            'order_number' => ['nullable', 'string','max:60'],
            'sender' => ['nullable', 'max:50'],
            'mobile_sender' => [$mobileShouldBeRequired, 'max:20',$mobileDigits],
            'logistic_number' => ['nullable', 'max:60'],
            'logistic_number_return' => ['required','string', 'max:60'],
            'id_logistic_return' => ['required', 'numeric', 'exists:logistics,id'],
            'fee_collected' => ['nullable','between:0,99999','numeric'],
            'is_loaded' => ['nullable'],
        ],[
            'mobile_sender.digits'=>'如果是手机则必须为11位',
        ],[
            'id_owner'=>'客户名称',
            'order_number'=>'订单号',
            'sender'=>'寄件人',
            'mobile_sender'=>'寄件人手机',
            'logistic_number'=>'原单号',
            'logistic_number_return'=>'退回单号',
            'id_logistic_return'=>'物流公司',
            'fee_collected'=>'到付费用',
            'is_loaded'=>'是否入库',
        ]);
    }

    public function apiSetIsLoadedAll(Request $request)
    {
        if(!Gate::allows('退货管理-编辑')){ return redirect(url('/'));  }
        $ids=$request->input('ids')??'';
        $rejecteds=RejectedBill::with('items')->whereIn('id',$ids)->get();
        $is_loaded = $request->input('is_loaded');
        switch ($is_loaded){
            case '0':$is_loaded=0;break;
            case '1':$is_loaded=1;break;
            case '2':$is_loaded=2;break;
            case '3':$is_loaded=3;break;
            case 'null':$is_loaded=null;break;
        }
        $rejecteds->each(function($rejected)use($is_loaded,$request){
            $rejected['is_loaded']=$is_loaded;
            $re=$rejected->update();
            if (!$re){
                return ['success'=>'false','fail_info'=>"数据 {$rejected['id']} 更新失败"];
            }
            $is_loadedItem='未入库';
            switch ($request->input('is_loaded')){
                case '1':$is_loadedItem='已入库';break;
                case '2':$is_loadedItem='待推单';break;
                case '0':$is_loadedItem='未入库';break;
                case '3':$is_loadedItem='未入库';break;
                case 'null':$is_loadedItem='无需入库';break;
            }
            $rejected->items()->each(function($item)use($is_loadedItem){
                $item['is_loaded']=$is_loadedItem;
                $item->save();
            });
        });
        return ['success'=>'true'];
    }

    /**
     * Display the specified resource.
     *
     * @param RejectedBill $rejectedBill
     * @return Response
     */
    public function show(RejectedBill $rejectedBill)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param RejectedBill $rejectedBill
     * @param Request $request
     * @return Factory|RedirectResponse|Response|Redirector|View
     */
    public function edit(RejectedBill $rejectedBill,Request $request)
    {
        if(!Gate::allows('退货管理-编辑')){ return redirect(url('/'));  }
        $user=Auth::user();
        $owners=Owner::all()->whereIn('id',
            $user?$user->getPermittingOwnerIdsAttribute():[])->sortBy('name');
        $logistics=Logistic::all()->sortBy('name');
        $qualityLabels=QualityLabel::all()->sortBy('name');
        return view('rejected.edit',compact('owners','logistics','qualityLabels','rejectedBill'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param RejectedBill $rejectedBill
     * @return Response
     */
    public function update(Request $request, RejectedBill $rejectedBill)
    {
        //
    }

    public function destroy(RejectedBill $rejectedBill)
    {
        if(!Gate::allows('退货管理-删除')){ return redirect(url('/'));}
        $re=$rejectedBill->delete();
        $this->log(__METHOD__,__FUNCTION__,$rejectedBill->toJson(),Auth::user()['id']);
        return ['success'=>$re];
    }

    public function apiLogisticNumberReturnIsUnique(Request $request)
    {
        if(!Gate::allows('退货管理-查询')){ return redirect(url('/'));}
        $logistic_number_return = $request->input('logistic_number_return');
        $bill=RejectedBill::select('logistic_number_return')->where('logistic_number_return',$logistic_number_return)->first();
        if(!$bill)return ['success'=>'true','result'=>'false'];
        return ['success'=>'true','result'=>'true'];
    }

    function seekOrder(Request $request){
        if (!$request->soreference5)return ['success'=>false];
        $order=OracleDOCOrderHeader::select('soreference1','customerid','c_contact','c_tel2','carrierid')->where('soreference5',$request->soreference5)->first();
        if ($order)return ['success'=>true,'data'=>$order];
    }
}
