<?php

namespace App\Http\Controllers;

use App\Events\AddOrUpdateOrderIssues;
use App\Filters\OrderIssueFilters;
use App\Imports\OrderIssueImport;
use App\Logistic;
use App\OracleDOCOrderHeader;
use App\Order;
use App\OrderIssue;
use App\OrderIssueProcessLog;
use App\OrderIssueRejectedBill;
use App\OrderIssueType;
use App\Owner;
use App\QualityLabel;
use App\RejectedBill;
use App\Services\common\ExportService;
use App\Services\OrderIssueProcessLogService;
use App\Services\OrderIssueService;
use App\Services\OrderService;
use App\Services\OwnerService;
use App\Shop;
use App\UserOwnerGroup;
use App\UserWorkgroup;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class OrderIssueController extends Controller
{

    public function index(Request $request, OrderIssueFilters $filter)
    {
        if (!Gate::allows('订单管理-问题件-查询')) {
            return redirect(url('/'));
        }
        $owners = app(OwnerService::class)->getAuthorizedOwners();
        $orderIssues = OrderIssue::query()->filter($filter)->defaultWith()->paginate($request['paginate'] ?? 50);
//        $orderIssues = OrderIssue::query()->filter($filter)->defaultWith()->toSql();
//        dd($orderIssues);
        $orderIssueType = OrderIssueType::all();
        $qualityLabel = QualityLabel::all();
        $logistics = Logistic::all();
        $userWorkgroup = UserWorkgroup::all();
        $userOwnerGroups = UserOwnerGroup::all();
        return view('order/issue/index', compact('owners', 'orderIssues', 'orderIssueType', 'qualityLabel','userWorkgroup','logistics','userOwnerGroups'));
    }

    public function create()
    {
        if (!Gate::allows('订单管理-订单问题件生成')) {
            return redirect(url('/'));
        }
        $types = OrderIssueType::all();
        $meg = ['success' => true];
        $userWorkGroup = UserWorkgroup::all();
        $logistic = Logistic::all();
        $owners = Owner::all();
        return view('order.issue.create', compact('types', 'meg', 'userWorkGroup', 'logistic', 'owners'));
    }

    public function store(Request $request)
    {
        if (!Gate::allows('订单管理-订单问题件生成')) {
            return redirect(url('/'));
        }
        /**
         * @var OrderIssueService $orderIssueService
         * @var OrderIssue $orderIssue
         */
        $orderIssueService = app('OrderIssueService');
        $orderIssueService->validatorCreate($request)->validate();
        $orderIssue = $orderIssueService->create($request->all());
        event(new AddOrUpdateOrderIssues([$orderIssue['order_id']]));
        if($request->has('logistic_number_return') && !OrderIssueRejectedBill::isExit($orderIssue->id,$request['logistic_number_return'])){
            $orderIssue->joinRejectedBill($request['logistic_number_return']);
        }
        $orderIssue->loadMissing('orderIssueRejectedBills');
        $orderIssue->syncRejectingStatus();
        OrderIssueProcessLog::query()->create(['order_issue_id' => $orderIssue['id'], 'user_id' => Auth::user()['id'], 'content' => $request['content'], 'type' => '创建']);
        return redirect('order/issue/index');
    }

    public function edit($id)
    {
        if (!Gate::allows('订单管理-问题件-编辑')) {
            return redirect(url('/'));
        }
        $orderIssue = OrderIssue::query()->with(['order','secondOrder.packages.commodities.commodity'])->where('id', $id)->first();
        $order = $orderIssue->order;
        $secondOrder = $orderIssue->secondOrder;
        $rejectedBill = RejectedBill::query()->where('id', $orderIssue->rejected_bill_id)->first();
        $userWorkgroup = UserWorkgroup::all();
        $userOwnerGroups = UserOwnerGroup::all();
        $orderIssueType = OrderIssueType::all();
        $owners = Owner::all();
        $shops = Shop::all();
        $logistics = Logistic::all();
        return view('order/issue/edit', compact('orderIssue', 'owners', 'userWorkgroup', 'shops', 'logistics', 'orderIssueType', 'order', 'secondOrder', 'rejectedBill','userOwnerGroups'));
    }

    public function batchImport(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-导入-Excel导入')) {
            return redirect(url('/'));
        }
        $file = $request->file('file');
        $fileSuffix = $file->getClientOriginalExtension();
        if (in_array($fileSuffix, ['xlsx', 'xlsm', 'xltx', 'xltm', 'xls', 'xlt', 'ods', 'ots', 'slk', 'xml', 'gnumeric', 'htm', 'html', 'csv', 'tsv'])) {
            ini_set('max_execution_time', 2100);
            ini_set('memory_limit', '512M');
            $extension = $request->file()['file']->getClientOriginalExtension();
            $extension[0] = strtoupper($extension[0]);
            Excel::import(new OrderIssueImport(), $request->file('file')->path(), null, $extension);
            if (Cache::has('error')) {
                return '<h1 class="text-danger">导入Excel失败<br><p style="color: red">' . Cache::pull('error') . '</p></h1>';
            } else {
                $exception = Cache::get('exception');
                $a = '';
                for ($i = 0; $i < count($exception); $i++) {
                    $a .= implode(',', $exception[$i]) . '&#10';
                };
                app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
                return '<h1 class="text-danger">导入Excel成功<br><textarea style="width: 50%;height: 50%">' . $a . '</textarea></h1>';
            }
        } else {
            return '<h1 class="text-danger">失败<br><p style="color: red">不支持该文件类型</p></h1>';
        }
    }

    public function exportOrderIssue(Request $request)
    {
        ini_set('max_execution_time', 2500);
        ini_set('memory_limit', '1526M');
        if (!Gate::allows('订单管理-问题件-查询')) {
            return redirect(url('/'));
        }
        if ($request->checkAllSign){
            $params = $request->input();
            unset($params['checkAllSign']);

            $sqlList = app('OrderIssueService')->getSqlList($params);
        }else{
            $sqlList = app('OrderIssueService')->getSqlList(['id'=>$request->data,"is_handle"=>true]);
        }
        $post = Http::post(config('go.export.url'),['type'=>'orderIssue','sqlList'=>json_encode($sqlList),'createFormat'=>'merge']);
        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 excelImport()
    {
        if (!Gate::allows('订单管理-问题件-导入')) {
            return redirect(url('/'));
        }
        return view('order.issue.import');
    }

    public function apiOrderIssueTag(Request $request)
    {
        if (!Gate::allows('订单管理-订单问题件生成')) {
            return ['success' => false, 'fail_info' => '没有对应权限'];
        }
        if (!$request->input('orderNos')) {
            return ['success' => false, 'fail_info' => '没有传入的订单编号'];
        }
        /** @var OrderIssueService $service */
        $service = app(OrderIssueService::class);
        $exits_orderNos = $service->校验问题件是否存在_WMS订单号_返回存在的订单号($request->input('orderNos'));
        if(count($exits_orderNos)>0) return ['success'=>false,'fail_info'=>'标记问题件存在已有订单号','exitsOrderNos' =>$exits_orderNos];
        $soft_delete_order_nos = $service->checkOrderIssueIsExistAndSoftDelete($request['orderNos']);
        if(count($soft_delete_order_nos)>0) return ['success'=>false,'fail_info'=>'订单对应问题件存在回收站，如需要请从回收站恢复','exitsOrderNos' =>$soft_delete_order_nos];
        return $service->orderIssueTag($request->all());
    }

    public function apiDestroy(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-删除')) {
            return ['success' => false, 'fail_info' => '没有对应权限'];
        }
        if (!($request->has('id'))) {
            return ['success' => 'false', 'fail_info' => '没有问题题件相关的参数'];
        }
        $orderIssue = OrderIssue::query()->where('id', $request->input('id'))->first();
        $bool = $orderIssue->delete();
        if ($bool) {
            app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
            return ['success' => 'true'];
        } else {
            return ['success' => 'false', 'fail_info' => '删除问题单出现异常,请联系管理员'];
        }
    }

    public function updateApi(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-编辑')) {
            return ['success' => false, 'fail_info' => '没有对应权限'];
        }
        try {
            $data =  $request->only([
                'order_issue_type_id','owner_id','logistic_id', 'logistic_number_return','result_explain','final_status','second_order_id','second_client_no',
                'logistic_indemnity_money','logistic_express_remission','baoshi_indemnity_money','baoshi_express_remission','user_workgroup_id','user_owner_group_id'
            ]);
            $orderIssue = OrderIssue::query()->find($request->id);
            $orderIssue->update($data);
            $orderIssue->syncRejectingStatus();
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request));
            return  ['success' => true];
        } catch (Exception $e) {
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request)."||".$e->getMessage().'||'.$e->getTraceAsString());
            return  ['success' => false ,'fail_info' => $e->getMessage()];
        }
    }

    public function apiEndOrderIssue(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-编辑')) {
            return ['success' => false, 'fail_info' => '没有对应的权限'];
        }
        if (!$request->has('ids')) {
            return ['success' => false, 'fail_info' => '没有传入对应的参数'];
        }
        $count = OrderIssue::query()->whereIn('id', $request->input('ids'))->where('final_status', '已解决')->count();
        if ($count > 0) {
            return ['success' => false, 'fail_info' => '勾选的内容中已有完结的订单问题件,取消勾选后重试'];
        } else {
            OrderIssue::query()->whereIn('id', $request->input('ids'))->update(['final_status' => '已解决']);
            foreach ($request->input('ids') as $id) {
                OrderIssueProcessLog::query()->create(['order_issue_id' => $id, 'user_id' => Auth::user()['id'], 'type' => '结束', 'content' => '完结订单']);
            }
            app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
            return ['success' => true];
        }
    }

    public function apiDisposeOrderIssue(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-编辑')) {
            return ['success' => false, 'fail_info' => '没有对应权限'];
        }
        if (!$request->has('id')) {
            return ['success' => false, 'fail_info' => '没有传入对应参数'];
        }
        try {
            OrderIssue::query()
                ->where('id', $request->input('id'))
                ->update(['is_new_rejecting' => '已处理']);
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->getContent()));
            return ['success'=>true];
        } catch (Exception $e) {
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->getContent())."||".$e->getMessage()."||".$e->getTraceAsString());
            return ['success' => false,'fail_info' => $e->getMessage()];
        }
    }

    public function apiGetOrderInfoByClientNo(Request $request)
    {
        if (!$request->filled('clientNo')) {
            return ['success' => false, 'fail_info' => '缺失WMS订单参数无法查询'];
        }
        $orderInfo = app(OrderService::class)->findOrCreateByClientCode($request->input('clientNo'));
        if (!$orderInfo) {
            return ['success' => true, 'message' => '没有对应的订单信息'];
        }else{
            return ['success' => true, 'data' => $orderInfo];
        }
    }

    public function apiOrderIssueHasClientCode(Request $request)
    {
        if (!$request->filled('clientCode')) {
            return ['success' => false, 'fail_info' => '缺少对应的参数或条件'];
        }
        /** @var $orderService OrderService*/
        $orderService = app('OrderService');
        $clientCode = $request->input('clientCode');
        $order = Order::query()->where('client_code', $clientCode)->first();
        if ($order) {
            if (OrderIssue::query()->where('order_id', $order['id'])->count()) {
                return ['success' => false, 'fail_info' => '该客户订单号已有对应的订单问题件'];
            }
            $order = $orderService->findOrCreateByClientCode($clientCode);
            return ['success' => true, 'order' => $order];
        } else {
            $orderHeader = OracleDOCOrderHeader::query()->where('SOReference1', $clientCode)->first();
            if (!$orderHeader) {
                return ['success' => false, 'fail_info' => '该客户订单号没有对应的订单信息'];
            } else {
                $order = $orderService->findOrCreateByClientCode($clientCode);
                $rejectedBill = $orderService->getRejectedBillOfClientCode($clientCode);
                return ['success' => true, 'order' => $order, 'rejectedBill' => $rejectedBill];
            }
        }
    }

    public function apiOrderIssueHasLogisticNumberReturn(Request $request)
    {
        if (!$request->filled('logisticNumberReturn')) {
            return ['success' => false, 'fail_info' => '缺少对应的参数或条件'];
        }
        $rejectedBill = RejectedBill::query()->with('items')->where('logistic_number_return', $request['logisticNumberReturn'])->first();
        if(!$rejectedBill) return ['success' => true, 'message' => '没有对应的退回单号，不与WMS同步'];
        $exists = OrderIssueRejectedBill::query()->where('logistic_number_return',$request['logisticNumberReturn'])->exists();
        if($exists)return ['success' => false, 'fail_info' => '该退回单号已有对应的问题件'];
        return ['success' => true, 'rejectedBill' => $rejectedBill];
    }

    public function isExistByOrderNoApi(Request $request){
        if (!Gate::allows('订单管理-订单问题件生成')) {
            return ['success'=>false,'fail_info' => '没有对应权限'];
        }
        $orderNos = $request->input('orderNos');
        $orderIssues =OrderIssue::query()->with('order')
            ->whereIn('order_id',function($query) use ($orderNos){
                $query->from('orders')->select('id')->whereIn('code',$orderNos);
            })->get();

        if($orderIssues->count() == 0){
            return ['success'=>true ];
        }else{
            $is_exist_orderNos = '';
            foreach ($orderIssues as $orderIssue) {
                $is_exist_orderNos.= $orderIssue->order->code.',';
            }
            $is_exist_orderNos = rtrim($is_exist_orderNos,',');
            $is_exist_orderNos .= ';';
            return ['success'=>false,'fail_info'=>'选中的订单已有存在的问题件:'.$is_exist_orderNos];
        }
    }

    public function updateColumnApi(Request $request,OrderIssueService $service): array
    {
        if (!Gate::allows('订单管理-问题件-编辑')) {
            return ['success'=>false,'fail_info' => '没有对应权限'];
        }
        if($request['column']=='final_status'  && $request['value'] == '已归档'){
            $orderIssues = OrderIssue::query()->where('id',$request['id'])->get();
            $service->archive($orderIssues);
            return ['success' =>true];
        }
        try {
            OrderIssue::query()
                ->where('id', $request->input('id'))
                ->update([$request->input('column') => $request->input('value')]);
            app('LogService')->log(__METHOD__,'更新问题件',json_encode($request->getContent()));
            return ['success' => true];
        } catch (Exception $e) {
            app('LogService')->log(__METHOD__,'更新问题件error',json_encode($request->getContent()).'||'.$e->getMessage().'||'.$e->getTraceAsString());
            return ['success' => false, $e->getMessage()];
        }
    }

    public function batchDestroyApi(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-删除')) {
            return ['success'=>false,'fail_info' => '没有对应权限'];
        }
        try {
            OrderIssue::query()->whereIn('id', $request->input('ids'))->delete();
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->getContent()));
            return ['success' => true];
        } catch (Exception $e) {
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->getContent())."||".$e->getMessage()."||".$e->getTraceAsString());
            return ['success' => false,'fail_info' => $e->getMessage()];
        }
    }

    public function apiUpdateValidator(array $arr)
    {
        return Validator::make($arr, [
            'order_issue_type_id' => ['required'],
            'handle_status' => ['nullable'],
            'result_explain' => ['nullable'],
            'logistic_indemnity_money' => ['nullable', 'numeric'],
            'logistic_express_remission' => ['nullable'],
            'baoshi_indemnity_money' => ['nullable', 'numeric'],
            'baoshi_express_remission' => ['nullable'],
        ], [
            'required' => [':attribute 为必填项', ':attribute'],
            'numeric' => [':attribute  为可确认的数值', ':attribute']
        ], [
            'order_issue_type_id' => '问题类别',
            'handle_status' => '处理状态',
            'result_explain' => '处理结果说明',
            'logistic_indemnity_money' => '承运商赔偿金额',
            'logistic_express_remission' => '承运商快递减免',
            'baoshi_indemnity_money' => '宝时赔偿金额',
            'baoshi_express_remission' => '宝时快递减免',
        ]);
    }

    public function apiUpdateValidatorRejectedBill(array $arr){
        return Validator::make($arr, [
            'logistic_number_return'=>['required'],
            'id_logistic_return'=>['required'],
        ], [
            'required' => [':attribute 为必填项', ':attribute'],
        ], [
            'logistic_number_return'=> '退回单号',
            'id_logistic_return'=> '退回单号承运商',
        ]);
    }

    public function endOrderIssuesApi(Request $request): array
    {
        if (!Gate::allows('订单管理-问题件-编辑')) {
            return ['success'=>false,'fail_info' => '没有对应权限'];
        }
        $orderIssue_ids = $request->input('ids');
        $bool = app(OrderIssueService::class)->isExistOrderIssueTypeIsEnd($orderIssue_ids);
        if($bool)return ['success'=>false,'fail_info'=> '需要完结的订单问题件中已有完结的订单问题件'];
        $bool = app(OrderIssueService::class)->endOrderIssues($orderIssue_ids);
        if($bool == 0) return ['success'=>false,'fail_info' => '操作失败'];
        $params = ['ids'=>$orderIssue_ids,'content'=>'完结订单','type'=>'结束'];
        $logs = app(OrderIssueProcessLogService::class)->create($params);
        return ['success'=>true,'logs'=>$logs];
    }

    public function editSecondClientNoApi(Request $request): array
    {
        if(!Gate::allows('订单管理-问题件-编辑')){
            return ['success'=>false,'fail_info'=>'没有对应权限'];
        }
        try {
            app(OrderIssueService::class)->editOrderIssueSecondClientNo($request['id'],$request['secondClientNo']);
            $order = Order::query()->with(['packages.commodities.commodity','logistic'])->where('client_code',$request['secondClientNo'])->first();
            if (!$order) {
                return ['success' => true, 'message' => '二次客户单号已修改，没有对应的订单信息'];
            } else {
               return ['success' => true, 'order' => $request['secondClientNo'] == '' ? null : $order];
            }
        } catch (Exception $e) {
            app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($request->getContent()).$e->getMessage().$e->getTraceAsString());
            return  ['success' =>false ,'fail_info' => $e->getMessage()];
        }
    }

    public function editSecondLogisticNumberApi(Request $request): array
    {
        if(!Gate::allows('订单管理-问题件-编辑'))
            return ['success'=>false,'fail_info'=>'没有对应权限'];
        /** @var OrderIssueService $service */
        $service = app(OrderIssueService::class);
        try {
            $message = $service->updateSecondLogisticNumber($request->input('id'), $request->logistic_number);
            return $message;
        } catch (Exception $e) {
            return ['success'=>false,'message' =>$e->getMessage()];
        }
    }

    public function disposeImportApi(Request $request): array
    {
        if(!Gate::allows('订单管理-问题件-编辑'))
            return ['success'=>false,'fail_info'=>'没有对应权限'];
        return app(OrderIssueService::class)->disposeImport($request->input('ids'));
    }

    public function importPasteDataApi(Request $request): array
    {
        if (!Gate::allows('订单管理-问题件-导入-文本导入'))
            return ['success'=>false,'fail_info'=>'没有对应权限'];
        $rows = $request->input('rows');
        $logistic_numbers = [];
        $types = [];
        $maps = [];
        $errors = [];
        $orderIssueTypes = OrderIssueType::all();
        $orderIssueType_map = [];
        foreach ($orderIssueTypes as $orderIssueType) {
            $orderIssueType_map[$orderIssueType->name] = $orderIssueType;
        }
        $array = explode("\n",$request->input('pasteDataText')); //拆分行
        /** @var OrderIssueService $service */
        $service =  app(OrderIssueService::class);
        foreach ($array as $i => $str) {
//            $string= preg_replace('/[\s,\,\，]+/','*++*',$str);
//            $items = explode('*++*',$string);
            $items=[];

            preg_match('/^(\w*?)[\s,，；;]([\x{4e00}-\x{9fa5}]*?)[\s,，；;](.*?)[\s,，；;](\w*?)$/u', $str, $items);
            if(count($items) == 0){
                preg_match('/^(\w*?)[\s,，；;]([\x{4e00}-\x{9fa5}]*?)[\s,，；;](.*?)$/u', $str, $items);
            }
            array_shift($items);
            $head = '第'.($i+1).'行';
            if(count($items)<count($rows)-1){
                $errors[$head] = ['数据不完整'];
                unset($items);
                continue;
            }
            $map = [];
            foreach ($rows as $index=>$row) {
                if($row === '原始运单号'){
                    if(!$items[$index]){
                        $errors[$head][]='快递单号为空';
                        $map =[];
                    }
                    $logistic_numbers = [$items[$index]];
                    $exist_logistic =  $service->校验问题件是否存在_快递单号_返回存在的快递单号($logistic_numbers);
                    $orderHeaders=OracleDOCOrderHeader::query()->with('actAllocationDetails')->whereHas('actAllocationDetails',function($query)use($logistic_numbers){
                        $query->whereIn('picktotraceid',$logistic_numbers);
                    })->get();
                    if(count($exist_logistic) > 0){
                        $errors[$head][]='快递单号存在对应的问题件';
                        $map =[];
                    }else if($orderHeaders->count()==0){
                        $errors[$head][]='快递单号不存在对应的发运订单';
                        $map =[];
                    }
                    $logistic_numbers[] = $items[$index];
                    $map['logistic_number'] = $items[$index];
                }
                if($row==='情况说明'){
                    if(!$items[$index]){
                        $errors[$head][]='情况说明为空';
                        $map =[];
                    }
                    $map['result_explain'] = $items[$index];
                }
                if($row==='自定义订单号'){
                    if($items[$index]??false){
                        $map['custom_code'] = $items[$index];
                    }
                }
                if($row==='问题类别'){
                    if(!$items[$index]){
                        $errors[$head][]='问题类别为空';
                        $map = [];
                    }else{
                        $type =  $orderIssueType_map[$items[$index]] ?? null;
                        if(!$type){
                            $errors[$head][]='问题类型不存在';
                            $map = [];
                        }
                    }
                    $types[] =$items[$index];
                    $map['type'] = $items[$index];
                }
            }
            if(count($map)!==0)$maps[] = $map;
        }

        if(count($errors)>0) return ['success'=>false,'fail_info'=>$errors];
        try {
            foreach ($maps as $map) {
                $logistic_number = $map['logistic_number'];
                $result_explain = $map['result_explain'];
                $type = $map['type'];
                $custom_code = $map['custom_code'] ?? null;
                $service->createOrderIssue($logistic_number, $type, $result_explain,'导入未处理',$custom_code,$request['hiddenTag'] ?? null);
            }
            return ['success'=>true];
        } catch (Exception $e) {
            app('LogService')->log(__METHOD__,__FUNCTION__,'文本导入问题件失败'.json_encode($request->getContent().$e->getMessage().$e->getTraceAsString()));
            return ['success'=>false,'fail_info'=>$e->getMessage()];
        }
    }

    public function exportJsonExcel(Request $request, OrderIssueFilters $filter)
    {
        if (!Gate::allows('订单管理-问题件-查询')) {
            return redirect(url('/'));
        }
        $order_Issues = OrderIssue::query()->filter($filter)->jsonWith()->get();
        return $this->getJson($order_Issues);
    }

    public function getJson($order_Issues){
        $json = [];
        $row = [
            '登记日期','创建日期','客户','客户订单号','原始承运商','收货人','收货电话','省','市','区','收货人地址',
            '原始运单号','原始商品','原始商品名称','原始商品数量',
            '退回单号', '退单商品名','退单商品条码','退单商品数量','是否正品','退单状态','退单备注',
            '操作类型','说明','操作者','情况说明','问题类别',
            '二次订单号','二次承运商','二次运单号','二次商品条码','二次商品名','二次商品数量',
            '最终状态', '承运商赔偿金额', '承运商快递减免', '宝时赔偿金额', '宝时快递减免','事故责任方',/*'项目责任方'*/
        ];
        foreach ($order_Issues as $order_issue){
            $order =  $order_issue->order;
            $orderPackages = $order_issue->order->packages ?? collect();
            $logistic_numbers = '';$order_sku  = '';$order_sku_name  = '';$order_sku_amount  = '';
            $orderPackages->each(function($package,$index)use(&$logistic_numbers,&$order_sku,&$order_sku_name,&$order_sku_amount){
                if(!str_starts_with('null',$package->logistic_number))$logistic_numbers.=$package->logistic_number.",\r\n";
                $package->commodities->each(function($commodities)use(&$order_sku,&$order_sku_name,&$order_sku_amount){
                    $commodity = $commodities->commodity ?? '';
                    $order_sku.= ($commodity->sku ?? '').",\r\n";
                    $order_sku_name.= ($commodity->name ?? '').",\r\n";
                    $order_sku_amount.= ($commodities->amount ?? '').",\r\n";
                });
            });
            $rejected_logistic_number = '';

            $rejected_Bill_remark = '';
            $rejected_is_checked = '';
            $rejected_name = ''; $rejected_barcode = '';$rejected_amount = '';
            if($order_issue->rejectedBills){
                $order_issue->rejectedBills->each(function($rejectedBill)use(
                    &$rejected_name,&$rejected_barcode, &$rejected_amount,&$rejected_Bill_remark,&$rejected_is_checked,&$rejected_logistic_number
                    ) {
                    $rejected_logistic_number.=$rejectedBill->logistic_number_return . ",\r\n";
                    $rejectedBill->items->each(function($item)use(
                        &$rejected_name,&$rejected_barcode, &$rejected_amount,&$rejected_Bill_remark,&$rejected_is_checked
                    ){
                        $rejected_name.= $item->name_goods.",\r\n";
                        $rejected_barcode.= $item->barcode_goods.",\r\n";
                        $rejected_amount.= $item->amount.",\r\n";
                        $rejected_Bill_remark.= $item->remark.",\r\n";
                        $rejected_is_checked.= $item->quality->name.",\r\n";
                    });
                });
            }
            $log_type = ''; $log_content = '';$log_user = '';
            $order_issue->logs->each(function($log)use(&$log_type, &$log_content,&$log_user){
                $log_type.=$log->type.",\r\n";
                $log_content.=$log->content.",\r\n";
                isset($log->user->name) ? $log_user.=$log->user->name.",\r\n" : null;
            });
            $send_order = $order_issue->secondOrder ??  new Order();
            $send_order_numbers = '';$send_order_sku ='';$send_order_name ='';$send_order_amount = '';
            $send_order->packages->each(function($package)use(&$send_order_numbers ,&$send_order_sku ,&$send_order_name ,&$send_order_amount ){
                $send_order_numbers.=($package->logistic_number).",\r\n";
                $package->commodities->each(function ($commodities)use( &$send_order_sku ,&$send_order_name ,&$send_order_amount ){
                    $commodity = $commodities->commodity;
                    $send_order_sku.=$commodity->sku.",\r\n";
                    $send_order_name.=$commodity->name.",\r\n";
                    $send_order_amount.=$commodities->amount.",\r\n";
                });
            });
            $userWorkgroupsName = '';
            $order_issue->userWorkgroups->each(function ($userWorkgroup)use (&$userWorkgroupsName) {
                $userWorkgroupsName.=($userWorkgroup->name).",\r\n";
            });
            if (isset($order_issue->userOwnerGroup->name))$userWorkgroupsName.=$order_issue->userOwnerGroup->name.",\r\n";
            $json[] = [
                isset($order_issue->created_at) ? str_split($order_issue->created_at,10)[0] :'',       // 登记日期
                isset($order->created_at) ? str_split($order->created_at,10)[0] :'',             // 创建日期
                $order->owner->name ?? '',      // 客户
                $order->client_code,              // 客户订单号
                $order->logistic->name ?? '',   // 原始承运商
                $order->consignee_name,         // 收货人
                $order->consignee_phone,        // 收货电话
                $order->province,               // 省
                $order->city,                   // 市
                $order->district,               // 区
                $order->address,                // 收货人地址

                rtrim($logistic_numbers,",\r\n"),              //原始运单号
                rtrim($order_sku,",\r\n"),                     //原始商品
                rtrim($order_sku_name,",\r\n"),                //原始商品名称
                rtrim($order_sku_amount,",\r\n"),              //原始商品数量

                //,'退单商品名','退单商品条码','退单商品数量','退单状态','退单备注'
                rtrim($rejected_logistic_number,",\r\n"),                      //退回单号
                rtrim($rejected_name,",\r\n"),        // 退单商品名
                rtrim($rejected_barcode,",\r\n") ,    // 退单商品条码
                rtrim($rejected_amount,",\r\n"),      // 退单商品数量
                rtrim($rejected_is_checked,",\r\n"),  // 是否正品
                rtrim($rejected_Bill_remark,",\r\n"),   // 退单备注

                $order_issue->rejecting_status ,                                // 退单状态

                // '操作类型','情况说明','问题类别',
                rtrim($log_type,",\r\n"),                        //操作类型
                rtrim($log_content,",\r\n"),                     //情况说明
                rtrim($log_user,",\r\n"),                        //操作者

                // '情况说明','问题类别',
                $order_issue->result_explain,                               // 情况说明
                $order_issue->issueType->name ?? '',                                   // 问题类别

                // '二次订单号','二次承运商','二次运单号','二次商品条码','二次商品名','二次商品数量',
                $order_issue->secondOrder->client_code ?? '',                //二次订单号
                $order_issue->secondOrder->logistic->name ?? '',             //二次承运商
                rtrim($send_order_numbers,",\r\n") ,                                        //二次运单号
                rtrim($send_order_sku,",\r\n"),                                             // 二次商品条码
                rtrim($send_order_name,",\r\n"),                                            // 二次商品名
                rtrim($send_order_amount,",\r\n"),                                          // 二次商品数量

                //'最终状态', '承运商赔偿金额', '承运商快递减免', '宝时赔偿金额', '宝时快递减免','事故责任方'
                $order_issue->final_status??'',
                $order_issue->logistic_indemnity_money ,
                $order_issue->logistic_express_remission,
                $order_issue->baoshi_indemnity_money,
                $order_issue->baoshi_express_remission,
                rtrim($userWorkgroupsName,",\r\n"),
//                $order_issue->userOwnerGroup->name ?? '',
            ];
        }
        return app(ExportService::class)->json($row,$json,"订单问题件");
    }

    public function recycleBin(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-删除')) {
            return redirect(url('/'));
        }
        /**
         * @var OrderIssueService $service
         */
        $service = app('OrderIssueService');
        $orderIssues = $service->getRecycleBinPaginate($request->input());
        $paginate = $request['paginate'] ?? 50;
        return view('order.issue.recycle',compact('orderIssues','paginate'));
    }

    public function recoverOrderIssueApi(Request $request): array
    {
        if (!Gate::allows('订单管理-问题件-删除')) {
            return ['success'=>false,'error'=>'没有对应权限'];
        }
        /**
         * @var OrderIssueService $service
         */
        $service = app('OrderIssueService');
        return  $service->recoverOrderIssue($request['ids']);
    }

    public function financeConfirmApi(Request $request): array
    {
        if (!Gate::allows('订单管理-问题件-财务确认')) {
            return ['success'=>false,'error'=>'没有对应权限'];
        }
        try {
            $bool = OrderIssue::query()->whereIn('id', $request['ids'])->update(['finance_confirm' => $request->flag]);
            if($bool==false)return ['success'=>false,'error'=>'财务确认失败'];
            app('LogService')->log(__METHOD__, __FUNCTION__,'财务确认'. json_encode($request->getContent()), Auth::user()['id']);
            return ['success'=>true];
        } catch (Exception $e) {
            app('LogService')->log(__METHOD__,'Error'. __FUNCTION__,'财务确认 Error'. json_encode($request->getContent()).' || '.json_encode($e->getMessage()).' || '.json_encode($e->getTraceAsString()), Auth::user()['id']);
            return ['success'=>false,'error'=>$e->getMessage()];
        }
    }


    /**
     * 批量归档
     * @param Request $request
     * @param OrderIssueService $service
     * @return array|bool[]
     */
    public function archiveOrderIssueApi(Request $request,OrderIssueService $service): array
    {
        if (!Gate::allows('订单管理-问题件-编辑')) return ['success'=>false,'error'=>'没有对应权限'];

        if(!$request->has('ids'))return ['success'=>false,'error'=>'没有勾选问题件'];

        $orderIssues = OrderIssue::query()->whereIn('id',$request['ids'])->get();

        $archiveOrderIssues = $orderIssues->where('final_status','已归档');

        if($archiveOrderIssues->count() > 0){
            $archiveIds = $archiveOrderIssues->map(function($archiveOrderIssue){
                return $archiveOrderIssue->id;
            });
            return ['success' =>false,'error' => "选中问题件Id{$archiveIds}已有归档信息,请取消选中或刷新页面重试"];
        }

        $service->archive($orderIssues);

        return ['success' =>true];
    }

    public function addUserWorkgroup(Request $request): array
    {
        $orderIssueId = $request->orderIssueId;
        $userWorkgroupId = $request->userWorkgroupId;
        try {
            OrderIssue::query()->find($orderIssueId)->userWorkgroups()->attach($userWorkgroupId);
        } catch (QueryException $e) {
            return ['success' => false,'data' =>'事故责任方已存在'];
        }
        return ['success' => true,'data' =>UserWorkgroup::find($userWorkgroupId)];
    }
    public function destroyUserWorkgroup(Request $request): array
    {
        $orderIssueId = $request->orderIssueId;
        $userWorkgroupId = $request->userWorkgroupId;
        OrderIssue::query()->find($orderIssueId)->userWorkgroups()->detach($userWorkgroupId);
        return ['success' => true,'data' =>UserWorkgroup::find($userWorkgroupId)];
    }

    public function batchOthers(Request $request)
    {
        $orderIssueIds = $request->input("orderIssueIds");
        $data = [];
        if ($request->input("logistic_indemnity_money")) {
            $data['logistic_indemnity_money'] = $request->input("logistic_indemnity_money");
        }
        if ($request->input("logistic_express_remission")) {
            $data['logistic_express_remission'] = $request->input("logistic_express_remission");
        }
        if ($request->input("baoshi_indemnity_money")) {
            $data['baoshi_indemnity_money'] = $request->input("baoshi_indemnity_money");
        }
        if ($request->input("baoshi_express_remission")) {
            $data['baoshi_express_remission'] = $request->input("baoshi_express_remission");
        }
        OrderIssue::query()->whereIn('id',$orderIssueIds)->update($data);
        $userWorkGroupIds = $request->input("userWorkGroupIds");
        if (isset($userWorkGroupIds)) {
            $orderIssues = OrderIssue::query()->whereIn('id', $orderIssueIds)->get();
            foreach ($orderIssues as $orderIssue) {
                $orderIssue->userWorkGroups()->sync($userWorkGroupIds);
            }
        }
        return ['success' => true];
    }

    public function destroySecondLogisticNumberApi(Request $request): array
    {
        if (!Gate::allows('订单管理-问题件-编辑')) return ['success'=>false,'error'=>'没有对应权限'];
        $count = OrderIssue::query()->where("id",$request->id)->update(["second_logistic_number"=>'']);
        if($count == 1){
            return ['success'=>true];
        }else{
            return ['success'=>false,'error'=>'删除失败'];
        }
    }
}
