<?php

namespace App\Http\Controllers;

use App\Imports\RejectedImport;
use App\Jobs\RejectedBillCreateInstantBill;
use App\Logistic;
use App\Owner;
use App\QualityLabel;
use App\Rejected;
use App\RejectedAnalyzeOwner;
use App\RejectedBill;
use App\Services\LogisticService;
use App\Services\OwnerService;
use App\Services\QualityLabelService;
use App\Services\RejectedService;
use Carbon\Carbon;
use Exception;
use Illuminate\Contracts\Foundation\Application;
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\Http;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;
use Maatwebsite\Excel\Facades\Excel;
use function foo\func;

class RejectedController extends Controller
{
    public function __construct()
    {
        app()->singleton('RejectedService',RejectedService::class);
    }

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @param OwnerService $ownerService
     * @param QualityLabelService $qualityLabelService
     * @param LogisticService $logisticService
     * @return Application|Factory|View|void
     */
    public function index(Request $request,OwnerService $ownerService,
                          QualityLabelService $qualityLabelService,LogisticService $logisticService)
    {
        if(!Gate::allows('退货管理-查询')){ return redirect(url('/login'));  }
        $paginateParams = $request->input();
        /** @var RejectedService $application */
        $application = app('RejectedService');
        $rejectedBills= $application->paginate($request);
//        $issueIds = $application->返回有问题件的ID($request);
        $owners = $ownerService->getIntersectPermitting();
        $qualityLabels = $qualityLabelService->get();
        $logistics=$logisticService->getSelection();
        return view('rejected.search.general',compact('rejectedBills','owners','logistics',
            'paginateParams','qualityLabels'));
    }
    public function recycle(Request $request)
    {
        if(!Gate::allows('退货管理-删除')){ return redirect(url('/'));  }
        $user=Auth::user();
        $paginate = $request->input('paginate')??50;
        $paginateParams = $this->packFilterParams($request);
        $paginateParams['paginate']=$paginate;
        $rejectedQuery=$this->buildFilteredQuery($paginateParams)->orderBy('id','desc')->whereIn('id_owner',
            $user?app('UserService')->getPermittingOwnerIds($user):[])->withTrashed()->whereNotNull('deleted_at');
        $total = $rejectedQuery->count();
        $rejectedBills=$rejectedQuery->paginate($paginate);
        return view('rejected.recycle',compact('rejectedBills','total','paginateParams'));
    }


    public function apiRecoverSelected(Request $request)
    {
        if(!Gate::allows('退货管理-删除')){ return ['success'=>'false','fail_info'=>"没有权限"];  }
        $ids=$request->input('ids')??'';
        $rejecteds=RejectedBill::withTrashed()->whereIn('id',$ids)->get();
        $rejecteds->each(function(RejectedBill $rejected){
            $rejected->restore();
        });
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>'true','rejecteds'=>$rejecteds];
    }

    private function packFilterParams(Request $request){
        $paginateParams=[
            'page'=> $request->input('page'),
            'created_at_start'=> $request->input('created_at_start'),
            'created_at_end'=> $request->input('created_at_end'),
            'owner_id'=> $request->input('owner_id'),
            'id_quality_label'=> $request->input('id_quality_label'),
            'is_checked'=> $request->input('is_checked'),
            'is_loaded'=> $request->input('is_loaded'),
            'mobile_sender'=> $request->input('mobile_sender'),
            'checked_numbers'=> $request->input('checked_numbers'),
            'order_number'=> $request->input('order_number'),
            'barcode_goods'=> $request->input('barcode_goods'),
            'logistic_number_return'=> $request->input('logistic_number_return'),
            'logistic_number'=> $request->input('logistic_number'),
            'id_logistic_return'=> $request->id_logistic_return,
        ];
        return $paginateParams;
    }
    private function buildFilteredQuery(Array $params){
        $created_at_start = $params['created_at_start'];
        $created_at_end = $params['created_at_end'];
        $owner_id = $params['owner_id'];
        $id_quality_label = $params['id_quality_label'];
        $is_checked = $params['is_checked'];
        $is_loaded = $params['is_loaded'];
        $mobile_sender = $params['mobile_sender'];
        $checked_numbers = $params['checked_numbers'];
        $order_number = $params['order_number'];
        $barcode_goods = $params['barcode_goods'];
        $logistic_number_return = $params['logistic_number_return'];
        $logistic_number = $params['logistic_number'];
        $id_logistic_return= $params['id_logistic_return'];
        $rejectedBillsQuery=RejectedBill::with(['user','owner','logistic','items']);
        if($created_at_start&&!$created_at_end){
            $created_at_end = $created_at_start;
        }
        if(!$created_at_start&&$created_at_end){
            $created_at_start = $created_at_end;
        }
        if($created_at_end){
            $created_at_end.=' 23:59:59';
        }
        if($created_at_start&&$created_at_end){
            if($created_at_start==$created_at_end){
                $rejectedBillsQuery=$rejectedBillsQuery->where('created_at','like',$created_at_start.'%');
            }else
                $rejectedBillsQuery=$rejectedBillsQuery->whereBetween('created_at',[$created_at_start,$created_at_end]);
        }
        if($owner_id){
            $rejectedBillsQuery=$rejectedBillsQuery->where('id_owner',$owner_id);
        }
        if($id_quality_label!=''){
            if($id_quality_label==1){
                $rejectedBillsQuery->whereDoesntHave('items',function ($query){
                    $query->where('id_quality_label',2);
                });
            }else{
                $rejectedBillsQuery->whereHas('items',function ($query){
                    $query->where('id_quality_label',2);
                });
            }
        }
        if($is_checked!=''){
            if(!$is_checked)
                $rejectedBillsQuery=$rejectedBillsQuery->where(function ($query) {
                    $query->where('is_checked', false)
                        ->orWhere('is_checked', null);
                });
            else{
                $rejectedBillsQuery=$rejectedBillsQuery->where('is_checked', true);
            }
        }
        if($is_loaded!=''){
            if($is_loaded=='null')$is_loaded=null;
            $rejectedBillsQuery=$rejectedBillsQuery->where('is_loaded', $is_loaded);
        }
        if($mobile_sender!=''){
            $rejectedBillsQuery=$rejectedBillsQuery->where('mobile_sender', trim($mobile_sender));
        }
        if($checked_numbers!=''){
            $rejectedBillsQuery=$rejectedBillsQuery->where('checked_numbers','like', trim($checked_numbers).'%');
        }
        if($barcode_goods!=''){
            $rejectedBillsQuery->whereHas('items',function ($query)use($barcode_goods){
                $query->where('barcode_goods','like',trim($barcode_goods).'%');
            });
        }
        if($order_number){
            $startDay = Carbon::now()->subDays(15);
            $rejectedBillsQueryTem=clone $rejectedBillsQuery;
            $rejectedBillsQueryTem=$rejectedBillsQueryTem->where('created_at','>',$startDay->format('Y-m-d'));
            $rejectedBillsQueryTem=$rejectedBillsQueryTem->where('order_number','like','%'.$order_number.'%');
            if($rejectedBillsQueryTem->count()==0
                ||$rejectedBillsQueryTem->get()[0]['order_number']==$order_number){
                $rejectedBillsQuery=$rejectedBillsQuery->where('order_number',$order_number);
            }else{
                $rejectedBillsQuery=$rejectedBillsQueryTem;
            }
        }
        if($logistic_number_return){
            if(strpos($logistic_number_return,',')||strpos($logistic_number_return,'，')||strpos($logistic_number_return,' ')){
                $arr=array_filter(preg_split('/[,， ]+/is', $logistic_number_return));
                $rejectedBillsQuery=$rejectedBillsQuery->whereIn('logistic_number_return',$arr);
            }else{
                $startDay = Carbon::now()->subDays(15);
                $rejectedBillsQueryTem=clone $rejectedBillsQuery;
                $rejectedBillsQueryTem=$rejectedBillsQueryTem->where('created_at','>',$startDay->format('Y-m-d'));
                $rejectedBillsQueryTem=$rejectedBillsQueryTem->where('logistic_number_return','like','%'.$logistic_number_return.'%');
                if($rejectedBillsQueryTem->count()==0
                    ||$rejectedBillsQueryTem->get()[0]['logistic_number_return']==$logistic_number_return){
                    $rejectedBillsQuery=$rejectedBillsQuery->where('logistic_number_return',$logistic_number_return);
                }else{
                    $rejectedBillsQuery=$rejectedBillsQueryTem;
                }
            }
        }
        if($logistic_number){
            $startDay = Carbon::now()->subDays(15);
            $rejectedBillsQueryTem=clone $rejectedBillsQuery;
            $rejectedBillsQueryTem=$rejectedBillsQueryTem->where('created_at','>',$startDay->format('Y-m-d'));
            $rejectedBillsQueryTem=$rejectedBillsQueryTem->where('logistic_number','like','%'.$logistic_number.'%');

            if($rejectedBillsQueryTem->count()==0
                ||$rejectedBillsQueryTem->get()[0]['logistic_number']==$logistic_number){
                $rejectedBillsQuery=$rejectedBillsQuery->where('logistic_number',$logistic_number);
            }else{
                $rejectedBillsQuery=$rejectedBillsQueryTem;
            }
        }
        if ($id_logistic_return){
            $rejectedBillsQuery=$rejectedBillsQuery->where('id_logistic_return',$id_logistic_return);
        }

        return $rejectedBillsQuery;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Application|RedirectResponse|Response|Redirector
     */
    public function create()
    {
        if(!Gate::allows('退货管理-录入')){ return redirect(url('/'));}
        $user=Auth::user();
        $owners=Owner::all()->whereIn('id',
            $user?app('UserService')->getPermittingOwnerIds($user):[])->sortBy('name');
        $logistics=Logistic::all()->sortBy('name');
        $qualityLabels=QualityLabel::all()->sortBy('name');
        $rejectedBills = RejectedBill::query()->orderByDesc('id')->whereIn('id_owner',
            $user?app('UserService')->getPermittingOwnerIds($user):[])->limit(20)->get();
        foreach($rejectedBills as $bill){
            $bill['is_loaded'] = $bill['is_loaded_null'];
            $bill['isEditing'] = false;
        }
        return view('rejected.create',compact('owners','logistics','qualityLabels','rejectedBills'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return Application|RedirectResponse|Response|Redirector
     */
    public function store(Request $request)
    {
        if(!Gate::allows('退货管理-录入')){ return redirect(url('/'));  }
        $this->validatorCreate($request->all())->validate();
        app('LogService')->log(__METHOD__,'找不到表','247行');
        $rejected=new Rejected($request->all());
        $rejected->save();
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('rejected/create')->with('successTip',"成功录入退货信息（退单：{$request->input('logistic_number_return')}）");
    }
    public function ajaxCheck(Request $request)
    {
        if(!Gate::allows('退货管理-审核')){ return ['success'=>'false','fail_info'=>"没有权限"]; }
        $rejected=RejectedBill::find($request->input('id')??'');
        $rejected['is_checked']=true;
        $rejected->makeCheckedNumbers();
        $re=$rejected->update();
        if ($re){
            return ['success'=>'true','checked_numbers'=>$rejected['checked_numbers']];
        }
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>'false','fail_info'=>'数据更新失败'];
    }
    public function ajaxCheckAll(Request $request)
    {
        if(!Gate::allows('退货管理-审核')){ return ['success'=>'false','fail_info'=>"没有权限"];  }
        $ids=$request->input('ids')??'';
        $rejecteds=RejectedBill::whereIn('id',$ids)->get();
        $checkNumbersArr=[];
        $rejecteds->each(function($rejected)use(&$checkNumbersArr){
            if($rejected['is_checked'])return true;
            $rejected['is_checked']=true;
            if(isset($checkNumbersArr[$rejected->owner->id])){
                $rejected['checked_numbers']=$checkNumbersArr[$rejected->owner->id];
            }else{
                $checkNumbersArr[$rejected->owner->id]=$rejected->makeCheckedNumbers();
            }
            $re=$rejected->update();
            if (!$re){
                return ['success'=>'false','fail_info'=>"数据 {$rejected['id']} 更新失败"];
            }
        });
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>'true','rejecteds'=>$rejecteds];
    }
    public function ajaxFinishAll(Request $request)
    {
        if(!Gate::allows('退货管理-编辑')){return ['success'=>'false','fail_info'=>"没有权限"];   }
        $ids=$request->input('ids')??'';
        $rejecteds=RejectedBill::whereIn('id',$ids)->get();
        $rejecteds->each(function($rejected){
            $rejected['is_finished']=true;
            $re=$rejected->update();
            if (!$re){
                return ['success'=>'false','fail_info'=>"数据 {$rejected['id']} 更新失败"];
            }
            dispatch(new RejectedBillCreateInstantBill($rejected));
        });
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>'true'];
    }
    protected function validatorCreate(array $data)
    {
        return Validator::make($data, [
            'id_owner' => ['required', 'numeric', 'exists:owners,id'],
            'order_number' => ['nullable', 'string','max:60'],
            'sender' => ['nullable', 'max:50'],
            'mobile_sender' => ['nullable', 'max:20'],
            'logistic_number' => ['nullable', 'max:60'],
            'logistic_number_return' => ['required','string', 'max:60'],
            'id_logistic_return' => ['required', 'numeric', 'exists:logistics,id'],
            'fee_collected' => ['nullable','numeric'],
            'is_loaded' => ['nullable'],
            'barcode_goods' => ['nullable','string', 'max:60'],
            'name_goods' => ['nullable','string', 'max:50'],
            'amount' => ['required','numeric'],
            'id_quality_label' => ['required', 'numeric', 'exists:quality_labels,id'],
            'batch_number' => ['nullable', 'string', 'max:60'],
            'validity_at' => ['nullable', 'date'],
            'remark' => ['nullable', 'string', 'max:60'],
        ],[],[

        ]);
    }
    protected function validatorUpdate(array $data)
    {
        return Validator::make($data, [
//            'name' => ['required', 'string', 'max:50'],
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param Rejected $rejected
     * @return void
     */
    public function show(Rejected $rejected)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Rejected $rejected
     * @return Response
     */
    public function edit(RejectedBill $rejectedBill)
    {
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param Rejected $rejected
     * @return Response
     */
    public function update(Request $request, Rejected $rejected)
    {
        if(!Gate::allows('退货管理-编辑')){ return redirect(url('/'));  }
        $this->validatorUpdate($request->all())->validate();
        $rejected->fill($request->all());
        $rejected->update();
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('rejected/')->with('successTip',"成功修改退货信息“{$rejected['name']}”！");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Rejected $rejected
     * @return array|Response
     * @throws Exception
     */
    public function destroy(Rejected $rejected)
    {
//        if(!Gate::allows('退货管理-删除')){ return redirect(url('/'));}
//        app('LogService')->log(__METHOD__,__FUNCTION__,$rejectedBill->toJson(),Auth::user()['id']);
//        $items=$rejectedBill->items();
//        $items->delete();
//        app('LogService')->log(__METHOD__,__FUNCTION__,$items->toJson(),Auth::user()['id']);
//        $re=$rejectedBill->delete();
//        return ['success'=>$re];
    }
    public function export(Request $request){
        if(!Gate::allows('退货管理-查询')){ return '没有权限';  }
        if ($request->checkAllSign){
            $param = $request->input();
            unset($param["checkAllSign"]);
        }else{
            $param = ["id"=>$request->data];
        }
        $sql = app('RejectedService')->getSql($param);
        $post = Http::post(config('go.export.url'),['type'=>'rejected','sql'=>$sql]);
        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',
        ]);
    }


    /*public function exportExcel(Request $request)
    {
        if(!Gate::allows('退货管理-查询')){ return '没有权限';  }
        ini_set('max_execution_time',2500);
        ini_set('memory_limit','1526M');
        $ids=$request->input('ids')??'';
        $ids=json_decode($ids,true);
        $export=new RejectedExport();
        $export->setIds($ids);
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return Excel::download($export,'退货表'.Carbon::now().'.xlsx');
    }
    public function exportExcelOnFilterParams(Request $request)
    {
        if(!Gate::allows('退货管理-查询')){ return '没有权限';  }
        ini_set('max_execution_time',2500);
        ini_set('memory_limit','1526M');
        $filterParams=json_decode($request->input('filterParams'),true);
        $user=Auth::user();
        $rejectedBills=$this->buildFilteredQuery($filterParams)->orderBy('id','desc')->whereIn('id_owner',
            $user?app('UserService')->getPermittingOwnerIds($user):[]);
        if($rejectedBills->count()>RejectedExport::$max){
            $rejectedBills->where('is_finished',false);
        }
        $rejectedBills->get();
        $export=new RejectedExport();
        $export->setRejectedBills($rejectedBills);
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return Excel::download($export,'退货表'.Carbon::now().'.xlsx');

    }*/
    public function import(Request $request)
    {
        return view('rejected.import');
    }
    public function importExcel(Request $request)
    {
        $isOverride = $request->input('isOverride');
        try{
            ini_set('max_execution_time',2500);
            ini_set('memory_limit','1526M');
            $extension=$request->file()['file']->getClientOriginalExtension();
            $extension[0] = strtoupper($extension[0]);
            Excel::import(new RejectedImport(), $request->file()['file']->path(),null,$extension);
            return '<h1 class="text-success">导入成功</h1>';
        }catch (Exception $e){
            if(strstr($e->getMessage(),'No ReaderType')){return '<h1 class="text-danger">没有上传写权限，请修改php.ini 对应的upload_tmp_dir 目录或其权限</h1>'.$e->getMessage();}
            if(strstr($e->getMessage(),'SQLSTATE')){return '<h1 class="text-danger">数据库插入错误，数据不支持，可能有重复或异常字符</h1>'.$e->getMessage();}
            return '<h1 class="text-danger">失败</h1>'.$e->getMessage();
        }
    }

    //analyzeSearch 统计查询 zengjun
    public function indexAnalyze(Request $request)
    {
        if(!Gate::allows('退货管理-查询')){ return redirect(url('/'));  }
        $paginateParams = $this->getAnalyzeSearchParams($request);
        $rejectedBills =  RejectedAnalyzeOwner::findBy($paginateParams);
        $owners = Owner::filterAuthorities()->get();
        $qualityLabels = QualityLabel::all();
        return view('rejected.search.analyze',compact('rejectedBills','owners',
            'paginateParams','qualityLabels'));
    }

    // 统计查询参数获取 zengjun
    private function getAnalyzeSearchParams(Request $request)
    {
        $searchParams = [
            'owner_id' => $request->input('owner_id'),
            'data'=> $request->input('data'),
            'created_at_start' => $request->input('created_at_start'),
            'created_at_end' => $request->input('created_at_end'),
            'uncheck_amount' => $request->input('uncheck_amount'),
            'not_in_storage' => $request->input('not_in_storage'),
        ];
        return $searchParams;
    }

    //统计页导出
    public function exportAnalyze(Request $request){
        $searchParams = $this->getAnalyzeSearchParams($request);
        $sql = RejectedAnalyzeOwner::getQuerySQL($searchParams);
        $post = Http::post(config('go.export.url'),['type'=>'rejectedStatistics','sql'=>$sql]);
        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',
        ]);
    }

    public function apiGetRejectedByLogisticNumberReturn(Request $request){
        if(!$request->filled('logisticNumberReturn')){
            return ['success' => false,'fail_info' => '没有传入对应的参数'];
        }
        $rejectedBill =  RejectedBill::with(['items'])->where('logistic_number_return',$request->input('logisticNumberReturn'))->first();
        if(!$rejectedBill){
            return ['success' => false,'fail_info' => '没有对应的退回单号，请先录入退件单'];
        }
        return ['success'=>true,'rejectedBill' => $rejectedBill];
    }
    public function changeRejectedBillRemark(Request $request){
        if(!Gate::allows('退货管理-编辑备注')){return ['success'=>'false','fail_info'=>'没有权限'];}
        $id= $request->input('id');
        $remark = $request->input('remark');
        if(is_null($id) ){
            return ['success'=>false,'fail_info'=>'参数异常'];
        }
        $rejectedBill=RejectedBill::query()->updateOrCreate([
            'id'=>$id,
        ],[
            'id'=>$id,
            'remark'=>$remark
        ]);
        app('LogService')->log(__METHOD__,'添加或者修改退单备注'.__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return ['success'=>true,'status'=>$rejectedBill];
    }
}
