<?php

namespace App\Services;

use App\OracleDOCASNHeader;
use App\OracleDOCOrderHeader;
use App\OrderIssue;
use App\OrderIssueProcessLog;
use App\OrderIssueType;
use App\OrderPackage;
use App\Order;
use App\RejectedBill;
use App\RejectedBillItem;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Ramsey\Uuid\Uuid;

class OrderIssueService
{
    public function __construct()
    {
        app()->bind("orderService", OrderService::class);
        app()->bind("rejectedService", RejectedService::class);
        app()->bind("orderPackageCommoditiesService", OrderPackageCommoditiesService::class);
    }

    public function insert($params)
    {
        OrderIssue::query()->insert($params);
    }

    public function getQuery(array $arr, array $condition = null)
    {
        if (!isset($condition)) {
            $condition = $arr;
        }
        $user = Auth::user();
        $owner_ids = $user ? app('UserService')->getPermittingOwnerIds($user) : [];
        if ($condition['owner_id'] ?? false) {
            $owner_ids = explode(',', $condition['owner_id']);
        }
        $query = OrderIssue::with(['top', 'userWorkGroup', 'issueType', 'logs' => function ($query) use ($arr) {
            $query->with('user')->orderByDesc('created_at');
        }, 'order' => function ($query) {
            $query->with(['shop', 'logistic', 'owner', 'packages.commodities.commodity' => function ($query) {
                $query->with('barcodes');
            }]);
        }, 'rejectedBill' => function ($query) {
            $query->with(['items.quality']);
        }, 'secondOrder' => function ($query) {
            $query->with(['shop', 'logistic', 'owner', 'packages.commodities.commodity' => function ($query) {
                $query->with('barcodes');
            }]);
        }])->whereHas('order.owner', function ($query) use ($owner_ids) {
            $query->whereIn('id', $owner_ids);
        });
        if ($arr['log_content'] ?? false) {
            $query->whereHas('logs', function ($query) use ($arr) {
                $query->where('content', 'like', $arr['log_content']);
                if ($arr['addtime'] ?? false) {
                    $query->where('created_at', '>=', Carbon::now()->subDays($arr['addtime']));
                } else {
                    $query->where('created_at', '>=', Carbon::now()->subDays(31));
                }
            });
        }
        if (isset($arr['is_imported'])) {
            $query->where('imported_status', $arr['is_imported']);
        }

        if (isset($arr['is_new_rejecting'])) {
            $query->where('is_new_rejecting', '=', $arr['is_new_rejecting']);
        }

        if (isset($arr['logistic_id'])) {
            $query->whereHas('order', function ($query) use ($arr) {
                $query->where('logistic_id', $arr['logistic_id']);
            });
        }
        if (isset($arr['custom_code'])) {
            $query->where('custom_code', $arr['custom_code']);
        }
        if(isset($arr['hiddenTag'])){
            $query->where('hidden_tag', $arr['hiddenTag']);
        }else{
            $query->whereNull('hidden_tag');
        }
        $query->selectRaw('order_issues.* ,order_issue_on_tops.id top_id ,order_issue_on_tops.remark,order_issue_on_tops.updated_at top_update')
            ->leftJoin('order_issue_on_tops', 'order_issue_on_tops.order_issue_id', '=', 'order_issues.id')
            ->whereNull('order_issue_on_tops.deleted_at')
            ->orderBy('order_issue_on_tops.updated_at', 'desc');
        $query->orderBy('order_issues.id', 'desc');
        return $query;
    }

    private function getOrderQuery(array $arr, $query)
    {
        $query->whereHas('order', function ($query) use ($arr) {
            if ($arr['client_code'] ?? false) {
                return $this->searchWay($query, $arr['client_code'], 'client_code');
            }
            if ($arr['consignee_name'] ?? false) {
                return $this->searchWay($query, $arr['consignee_name'], 'consignee_name');
            }
            if ($arr['consignee_phone'] ?? false) {
                return $this->searchWay($query, $arr['consignee_phone'], 'consignee_phone');
            }
            if ($arr['logistic_number'] ?? false) {
                $logistic_number = $arr['logistic_number'];
                $query->whereHas('packages', function ($query) use ($logistic_number) {
                    return $this->searchWay($query, $logistic_number, 'logistic_number');
                });
            }
            if (($arr['good_barcode'] ?? false) || ($arr['good_name'] ?? false)) {
                $query->whereHas('packages.commodities.commodity', function ($query) use ($arr) {
                    if ($arr['good_barcode'] ?? false) {
                        return $this->searchWay($query, $arr['good_barcode'], 'sku');
                    }
                    if ($arr['good_name'] ?? false) {
                        $query->where('name', 'like', '%' . $arr['good_name'] . '%');
                    }
                });
            }
        });
        if ($arr['send_client_code'] ?? false) {
            $query->whereHas('secondOrder', function ($query) use ($arr) {
                return $this->searchWay($query, $arr['send_client_code'], 'client_code');
            });
        }
        return $query;
    }

    public function getRejectedBillQuery(array $arr, $query)
    {
        if (($arr['logistic_number_return'] ?? false) || ($arr['id_quality_label'] ?? false)) {
            $query->whereHas('rejectedBill', function ($query) use (&$arr) {
                if ($arr['logistic_number_return'] ?? false) {
                    return $this->searchWay($query, $arr['logistic_number_return'], 'logistic_number_return');
                }
                if ($arr['id_quality_label'] ?? false) {
                    $query->whereHas('items', function ($query) use ($arr) {
                        $query->where('id_quality_label', $arr['id_quality_label']);
                    });
                }
            });
        }
        return $query;
    }

    public function getConditionQuery(array $arr, array $condition = null)
    {
        $query = $this->getQuery($arr, $condition);
        $query = $this->getOrderQuery($condition ?? $arr, $query);
        $query = $this->getRejectedBillQuery($condition ?? $arr, $query);

        if (!isset($condition)) {
            $condition = $arr;
        }
        if ($condition['id'] ?? false) {
            $query->whereIn('order_issues.id', explode(',', $condition['id']));
        }
        if (isset($condition['created_at_start'])) {
            $query->where('order_issues.created_at', '>=', $condition['created_at_start'] . " 00:00:00");
        }
        if (isset($condition['created_at_end'])) {
            $query->where('order_issues.created_at', '<=', $condition['created_at_end'] . " 23:59:59");
        }
        if (isset($condition['final_status'])) {
            if ($condition['final_status'] == 'null') {
                $query->whereNull('final_status');
            } else {
                $query->where('final_status', $condition['final_status']);
            }
        }
        if (isset($condition['order_issue_type_id'])) {
            $type_ids = explode(',',$condition['order_issue_type_id']);
            $query->whereIn('order_issue_type_id', $type_ids);
        }
        if (!($condition['is_handle'] ?? false) && !($condition['final_status'] ?? false)) {
            if (!(isset($condition['settlement_at_start']) || isset($condition['settlement_at_end']))) {
                $query->where(function ($query) {
                    $query->where('final_status', '<>', '已解决')->orWhereNull('final_status');
                });
            }
        }
        if (isset($condition['logistic_indemnity_money'])) {
            if($condition['logistic_indemnity_money']== '是'){
                $query->whereNotNull('logistic_indemnity_money');
            }elseif($condition['logistic_indemnity_money']== '否'){
                $query->whereNull('logistic_indemnity_money');
            }
        }
        if (isset($condition['baoshi_indemnity_money'])) {
            if($condition['baoshi_indemnity_money']== '是'){
                $query->whereNotNull('baoshi_indemnity_money');
            }elseif($condition['baoshi_indemnity_money']== '否'){
                $query->whereNull('baoshi_indemnity_money');
            }
        }
        if (isset($condition['rejectingStatus'])) {
            $query->where('rejecting_status',$condition['rejectingStatus']);
        }
        if (isset($condition['order_issue_ids'])) {
            $orderIssuesId = $condition['order_issue_ids'];
            if (is_string($orderIssuesId)) {
                $orderIssuesId = explode(',', $orderIssuesId);
            }
            $query->whereIn('order_issues.id', $orderIssuesId);
        }
        if (isset($condition['settlement_at_start']) || isset($condition['settlement_at_end'])) {
            $query->whereHas('logs', function ($query) use ($condition) {
                if (isset($condition['settlement_at_start'])) {
                    $query->where('created_at', '>=', $condition['settlement_at_start'] . ' 00:00:00')->where('type', '结束');
                }
                if (isset($condition['settlement_at_end'])) {
                    $query->where('created_at', '<=', $condition['settlement_at_end'] . ' 23:59:59')->where('type', '结束');
                }
            });
        }
        if(isset($condition['sendOrderClientCode'])){
            $query->whereHas('secondOrder',function($query)use($condition){
                $this->searchWay($query,$condition['sendOrderClientCode'],'client_code');
            });
            $query->orWhere('second_client_no',$condition['sendOrderClientCode']);
        }
        if(isset($condition['sendOrderLogisticNumber'])){
            $query->whereHas('secondOrder.packages',function($query)use($condition){
                $this->searchWay($query,$condition['sendOrderLogisticNumber'],'logistic_number');
            });
            $query->orWhere('second_logistic_number',$condition['sendOrderLogisticNumber']);
        }
        return $query;
    }

    private function isSearchLike($str)
    {
        if (substr($str, 0, 1) == "%" || substr($str, strlen($str) - 1, 1) == "%") {
            return true;
        }
        return false;
    }

    private function searchWay($query, $param, $column)
    {
        if ($this->isSearchLike($param)) {
            $query->where($column, 'like', $param);
        } else {
            $query->whereIn($column, array_filter(preg_split('/[,， ]+/is', $param)));
        }
        return $query;
    }

    public function getSqlList(array $params)
    {
        $orderPackageSql = OrderPackage::query()->selectRaw('order_packages.logistic_number order_package_logistic_number')
            ->leftJoin('order_package_commodities','order_packages.id','order_package_commodities.order_package_id')
            ->selectRaw('order_package_commodities.amount commodity_amount')
            ->leftJoin('commodities','order_package_commodities.commodity_id','commodities.id')
            ->selectRaw('commodities.name commodity_name,commodities.sku commodity_sku')
            ->leftJoin('order_issues','order_packages.order_id','order_issues.order_id')
            ->selectRaw('order_issues.id order_issue_id')
            ->sql();
        $secondOrderPackageSql = Order::query()->from('order_packages','s_o_p')->selectRaw('s_o_p.logistic_number')
            ->leftJoin("orders as o_d","s_o_p.order_id","o_d.id")
            ->leftJoin('order_package_commodities as s_o_p_c','s_o_p_c.order_package_id','s_o_p.id')
            ->selectRaw('s_o_p_c.amount s_o_p_c_amount')
            ->leftJoin('commodities as s_c','s_o_p_c.commodity_id','s_c.id')
            ->selectRaw('s_c.sku s_c_sku,s_c.name s_c_name')
            ->leftJoin('order_issues','o_d.client_code','order_issues.second_client_no')
            ->selectRaw('order_issues.id order_issue_id')
            ->sql();
        $rejectedBillItemSql = RejectedBillItem::query()->selectRaw('rejected_bill_items.remark,rejected_bill_items.amount rejected_bill_amount,rejected_bill_items.name_goods,rejected_bill_items.barcode_goods')
            ->leftJoin('rejected_bills',"rejected_bill_items.id_rejected_bill","rejected_bills.id")
            ->leftJoin('order_issues','rejected_bills.logistic_number_return','order_issues.logistic_number_return')
            ->selectRaw('order_issues.id order_issue_id')
            ->sql();
        $logSql = OrderIssueProcessLog::query()->selectRaw('order_issue_process_logs.content log_content,order_issue_process_logs.type log_type')
            ->leftJoin('users','order_issue_process_logs.user_id','users.id')
            ->selectRaw('users.name user_name')
            ->leftJoin('order_issues','order_issue_process_logs.order_issue_id','order_issues.id')
            ->selectRaw('order_issues.id order_issue_id')
            ->sql();
        $column = "order_issues.id,order_issues.rejected_bill_id,order_issues.rejecting_status,order_issues.created_at order_issues_created_at,order_issues.result_explain,order_issues.final_status,";
        $column .= "order_issues.logistic_indemnity_money,order_issues.logistic_express_remission,order_issues.baoshi_indemnity_money,order_issues.baoshi_express_remission";
        $orderIssueSql =  $this->getConditionQuery($params)->selectRaw($column)
            ->leftJoin('order_issue_types','order_issues.order_issue_type_id','order_issue_types.id')
            ->selectRaw('order_issue_types.`name` order_issue_type_name')
            ->leftJoin('orders','order_issues.order_id','orders.id')
            ->selectRaw('orders.id order_id,orders.address,orders.district,orders.city,orders.province,orders.consignee_phone,orders.consignee_name,orders.client_code,orders.created_at order_created_at')
            ->leftJoin('logistics','logistics.id','orders.logistic_id')
            ->selectRaw('logistics.name logistic_name')
            ->leftJoin('owners','owners.id','orders.owner_id')
            ->selectRaw('owners.name owner_name')
            ->leftJoin('shops','orders.shop_id','shops.id')
            ->selectRaw('shops.name shop_name')
            ->leftJoin('orders as s_o','s_o.client_code','order_issues.second_client_no')
            ->selectRaw('s_o.id s_o_id,s_o.client_code s_o_client_code')
            ->leftJoin('logistics as s_logistics','s_o.logistic_id','s_logistics.id')
            ->selectRaw('s_logistics.name s_logistics_name')
            ->leftJoin('user_workgroups','user_workgroups.id','order_issues.user_workgroup_id')
            ->selectRaw('user_workgroups.name user_workgroup_name')
            ->sql();
        return compact('orderPackageSql','secondOrderPackageSql','orderIssueSql','rejectedBillItemSql','logSql');
    }

    public function paginate(array $params)
    {
        return $query = $this->getConditionQuery($params)->paginate($params['paginate'] ?? 50);
    }

    public function orderIssueTag(array $params)
    {
        $orderNos = $params['orderNos'];
        $orderHeaders = OracleDOCOrderHeader::query()->with(['oracleDOCOrderDetails', 'actAllocationDetails', 'oracleBASCode'])->whereIn('orderNo', $orderNos)->get();
        $bool = $this->createOrderIssueByWmsOrder($orderHeaders, $params['typeId'], $params['result_explain']);
        if ($bool) {
            return ['success' => $bool];
        } else {
            return ['success' => $bool, 'fail_info' => '问题件创建失败,请检查勾选订单的状态'];
        }
    }

    public function createOrderIssueByWmsOrder($orderHeaders, $order_issue_type_id, $result_explain, $imported_status = '正常', $custom_code = null,$hiddenTag = null)
    {
        /** @var OrderService $orderService */
        $orderService = app('OrderService');
//        $orderService->updateByWmsOrders($orderHeaders);
//        $orders = $orderService->getByWmsOrders($orderHeaders);
        $orderService->createByWmsOrder($orderHeaders);
        $orders = Order::query()->whereIn('code',data_get($orderHeaders,'*.orderno'))->whereHas('packages')->get();
        if($orders->count()==0)return false;
        $innerParams = [];
        $data = Carbon::now()->format('Y-m-d H:i:s');
        foreach ($orderHeaders as $orderHeader) {
            $order = $orders->where('code',$orderHeader->orderno)->first();
            if($order==null){
                $order = Order::query()->where('code',$orderHeader->orderno)->first();
            }
            $innerParams[] = [
                'order_id' => $order->id,
                'order_issue_type_id' => $order_issue_type_id,
                'result_explain' => $result_explain,
                'imported_status' => $imported_status,
                'custom_code' => $custom_code,
                'hidden_tag' => $hiddenTag,
                'updated_at' => $data,
                'created_at' => $data
            ];
        }
        try {
            $this->insert($innerParams);
            $ordersIssues = OrderIssue::query()->whereIn('order_id', data_get($innerParams, '*.order_id'))->get();
            $this->同步退单状态($ordersIssues);
            $param = [
                'ids' => data_get($ordersIssues, '*.id'),
                'content' => '',
                'user_id' => Auth::user()['id'],
                'type' => '创建'
            ];
            app(OrderIssueProcessLogService::class)->create($param);
            app('LogService')->log(__METHOD__, __FUNCTION__, '创建问题件' . count($innerParams) . json_encode($innerParams));
            return true;
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__, __FUNCTION__, '创建问题件 error' . count($innerParams) . json_encode($innerParams) . $e->getMessage() . $e->getTraceAsString());
            return false;
        }
    }

    public function 同步退单状态($orderIssues)
    {
        if(!$orderIssues)return;
        foreach ($orderIssues as $orderIssue) {
            $orderIssue->syncRejectedBill();
            $orderIssue->同步退单状态();
        }
    }

    public function createOrFindByOrderNo($orderNo)
    {
        $orderHeader = OracleDOCOrderHeader::query()->where('orderNo', $orderNo)->first();
        if (!$orderHeader) {
            return null;
        }
        return $this->createOrFind($orderHeader['soreference1']);
    }

    public function createOrFind($clientCode)
    {
        /** @var OrderService $orderService */
        $orderService = app('OrderService');
        $orderHeader = OracleDOCOrderHeader::query()->where('SOReference1', $clientCode)->first();
        if ($orderHeader === null) {
            return null;
        }
        $order = $orderService->findOrCreateByClientCode($clientCode);
        $rejectedBill = RejectedBill::query()->where('order_number', $orderHeader['soreference1'])->first();
        if ($rejectedBill === null) {
            $asnHeader = OracleDOCASNHeader::query()->where('ASNReference2', $orderHeader['soreference1'])->first();
            if ($asnHeader['asnreference3'] ?? false) {
                $rejectedBill = RejectedBill::query()->where('logistic_number_return', $asnHeader['asnreference3'])->first();
            }
        }
        $arr = [
            'order_id' => $order['id'],
            'logistic_number_return' => $rejectedBill['logistic_number_return'] ?? '',
        ];
        $orderIssue = null;
        try {
            $orderIssue = OrderIssue::query()->create($arr);
            $orderIssue->同步退单状态();
            $orderIssue->order = $order;
            app('LogService')->log(__METHOD__, __FUNCTION__, '创建问题件' . json_encode($orderIssue));
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__, __FUNCTION__, '创建问题件error' . json_encode($arr) . $e->getMessage() . $e->getTraceAsString());
        } finally {
            unset($orderHeader, $rejectedBill, $order);
            return $orderIssue;
        }
    }

    public function validatorCreate(Request $request)
    {
        return Validator::make($request->input(), [
            'rejected_bill_id' => ['nullable'],
            'order_id' => ['nullable'],
            'owner_id' => ['required'],
            'second_order_id' => ['nullable'],
            'logistic_id' => ['nullable'],
            'order_issue_type_id' => ['required'],
            'baoshi_indemnity_money' => ['numeric', 'nullable'],
            'logistic_indemnity_money' => ['numeric', 'nullable'],
            'final_status' => ['nullable'],
            'result_explain' => ['nullable']
        ], [
            'required' => ':attribute 为必填项',
            'unique' => ':attribute 已存在',
            'numeric' => ':attribute 为数组',
        ], [
            'owner_id' => '货主',
            'rejected_bill_id' => '退回单号',
            'order_id' => '订单ID',
            'second_order_id' => '退回订单id',
            'logistic_id' => '承运人',
            'order_issue_type_id' => '问题类别',
            'baoshi_indemnity_money' => '宝时赔偿金额',
            'logistic_indemnity_money' => '承运商赔偿金额',
            'final_status' => '最终状态',
            'result_explain' => '处理结果说明',
        ]);
    }

    public function create(array $arr)
    {
        $orderIssue = OrderIssue::query()->create($arr);
        if (!$arr['order_id']) {
            $order = Order::query()->create($arr);
            $orderIssue->order_id = $order['id'];
            $orderIssue->save();
            app('LogService')->log(__METHOD__,__FUNCTION__,'创建 Order'.json_encode($order));
        }
        $orderIssue->同步退单状态();
        return $orderIssue;
    }

    public function createByLogisticNumber(array $arr)
    {
        $order = new Order($arr);
        $order['code']='null_'.Uuid::uuid4();
        $order->save();
        app('LogService')->log(__METHOD__,__FUNCTION__,'创建 Order'.json_encode($order));
        $orderIssue = OrderIssue::query()->create($arr);
        $orderIssue['order_id'] = $order['id'];
        OrderPackage::query()->create(['order_id' => $order['id'], 'logistic_number' => $arr['logistic_number_return']]);
        $orderIssue->同步退单状态();
        $orderIssue->update(['order_id' => $order['id']]);
        return $orderIssue;
    }

    public function batchDestroy($ids)
    {
        try {
            $bool = OrderIssue::query()->whereIn('id', $ids)->delete();
            app('LogService')->log(__METHOD__, __FUNCTION__, json_encode($ids));
            return ['success' => $bool];
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__, __FUNCTION__, 'error' . json_decode($ids) . '||' . $e->getMessage() . '||' . $e->getTraceAsString());
            return ['success' => false];
        }
    }

    public function endOrderIssues(array $ids)
    {
        return OrderIssue::query()->whereIn('id', $ids)->update(['final_status' => '已解决']);
    }

    public function isExistOrderIssueTypeIsEnd($ids)
    {
        return OrderIssue::query()->whereIn('id', $ids)->where('final_status', '已解决')->count() > 0;
    }

    public function editOrderIssueSecondClientNo($id, $secondClientNo, &$order = null)
    {
        $order = Order::query()->where('client_code', $secondClientNo)->first();
        if (!$order) {
            /** @var OrderService $orderService */
            $orderService = app(OrderService::class);
            $orderHeaders = OracleDOCOrderHeader::query()->where('SoReference1', $secondClientNo)->get();
            $orders = $orderService->createByWmsOrder($orderHeaders);
            if ($orders->count() > 0) $order = $orders->first();
        }
        return OrderIssue::query()->where('id', $id)->update(['second_client_no' => $secondClientNo]) > 0;
    }

    public function updateSecondLogisticNumber($id, $logisticNumber)
    {
        $orderIssue = OrderIssue::query()->where('id', $id)->first();
        $order = app(OrderService::class)->getOrderByLogisticNumber($logisticNumber);
        if (!$order) {
            $orderIssue->update(['second_logistic_number' => $logisticNumber]);
            return ['success' => true, 'second_logistic_number' => $logisticNumber];
        }
        $orderIssue->update(['second_client_no' => $order->client_code]);
        $order = Order::query()->with(['packages.commodities.commodity', 'logistic'])
            ->where('id', $order->id)->first();
        return ['success' => true, 'order' => $order];
    }


    public function createOrderIssue($logisticNumber, $type, $result_explain, $importedStatus = '正常', $custom_code = null,$hiddenTag = null)
    {
        $orderHeaders = OracleDOCOrderHeader::query()->with(['oracleDOCOrderDetails', 'actAllocationDetails', 'oracleBASCode','orderType'])
            ->whereHas('actAllocationDetails', function ($query) use ($logisticNumber) {
                $query->where('picktotraceid', $logisticNumber);
            })->get();
        $orderIssueType = OrderIssueType::query()->where('name', $type)->first();
        return $this->createOrderIssueByWmsOrder($orderHeaders, $orderIssueType->id, $result_explain, $importedStatus, $custom_code,$hiddenTag);
    }

    /**
     * @param array $logisticNumbers
     * @return array
     */
    public function 校验问题件是否存在_快递单号_返回存在的快递单号($logisticNumbers)
    {
        $orderIssues = OrderIssue::query()->with('order.packages')->whereHas('order.packages', function ($query) use ($logisticNumbers) {
            $query->whereIn('logistic_number', $logisticNumbers);
        })->get();
        $exits_logistic_number = array_diff(array_unique(data_get($orderIssues, '*.order.packages.*.logistic_number')), ['', null]);
        return array_intersect($exits_logistic_number, $logisticNumbers);
    }

    /**
     * @param array $orderNos
     * @return array
     */
    public function 校验问题件是否存在_WMS订单号_返回存在的订单号($orderNos)
    {
        $orderIssues = OrderIssue::query()->with('order')->whereHas('order', function ($query) use ($orderNos) {
            $query->whereIn('code', $orderNos);
        })->get();
        $exits_logistic_number = array_diff(array_unique(data_get($orderIssues, '*.order.code')), ['', null]);
        return array_intersect($exits_logistic_number, $orderNos);
    }

    /**
     * 导入处理字段
     * @param array $ids
     * @return array|bool[]
     */
    public function disposeImport(array $ids)
    {
        $orderIssues = OrderIssue::query()->with('order')->whereIn('id', $ids)->get();
        if ($orderIssues->count()<count($ids)) {
            $is_exits_ids = array_diff($ids, data_get($orderIssues, '*.code'));
            return ['success' => false, 'fail_info' => json_encode($is_exits_ids) . '没有存在对应的问题件'];
        }
        if ($orderIssues->where('imported_status', '导入已梳理')->count() > 0) {
             $is_dispose_orderNos = data_get($orderIssues->where('imported_status', '导入已梳理'), '*.order.code');
            return ['success' => false, 'fail_info' => json_encode($is_dispose_orderNos) . '导入已处理'];
        }
        try {
            OrderIssue::query()->whereIn('id', $ids)->update(['imported_status' => '导入已梳理']);
            app('LogService')->log(__METHOD__,__FUNCTION__,'导入处理 '.json_encode($ids).'导入处理');
            return ['success' => true];
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__,__FUNCTION__,'导入处理 error'.json_encode($e->getMessage()).$e->getTraceAsString());
            return ['success' => false,'fail_info'=>$e->getMessage()];
        }
    }

    public function getJsonObj(array $params)
    {
        return  $this->getConditionQuery($params)->get();
    }


    public function getRecycleBinPaginate($params){
        return OrderIssue::query()
            ->with(['order'=>function($query){
                $query->with(['logistic','shop','owner','packages'=>function($query){
                $query->with('commodities');
            }]);
        },'rejectedBill.items','issueType','secondOrder.packages.commodities'])->onlyTrashed()->paginate($params['paginate'] ?? 50);
    }

    public function recoverOrderIssue($ids)
    {
        try {
            $bool = OrderIssue::query()->withTrashed()->whereIn('id', $ids)->restore();
            app('LogService')->log(__METHOD__, __FUNCTION__, '恢复问题件 ids = ' . json_encode($ids));
            return ['success'=>$bool];
        } catch (\Exception $e) {
            app('LogService')->log(__METHOD__, 'ERROR '.__FUNCTION__, '恢复问题件 Error' . json_encode($ids).' || '.json_encode($e->getMessage()).' || '.json_encode($e->getTraceAsString()));
            return ['success'=>false,'error'=>$e->getMessage()];
        }
    }
}
