<?php

namespace App\Services;

use App\OracleDOCOrderHeader;
use App\OrderIssue;
use App\RejectedBill;
use App\Services\common\BatchUpdateService;
use App\Services\common\DataHandlerService;
use Carbon\Carbon;

Class RejectedBillService
{
    private function conditionQuery(array $params)
    {
        $query = RejectedBill::query();
        if ($params['order_number'] ?? false) {
            $query->whereIn('order_number', $params['order_number']);
        }
        return $query;
    }

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

    public function create(array $params)
    {
        return RejectedBill::query()->create($params);
    }

    public function syncOrderIssue($rejectedBill)
    {
        /**
         * @var OrderIssue $orderIssue
         */
        $orderIssue = $rejectedBill->orderIssue()->first();
        if (!$orderIssue && $rejectedBill['logistic_number'] === '原单退回') {   // 原单退回
            $orderIssue = OrderIssue::query()->with('order')->whereHas('order', function ($query) use ($rejectedBill) {
                $query->where('client_code', $rejectedBill['order_number']);
            })->first();
        } else if (!$orderIssue && isset($rejectedBill->logistic_number_return)) {
            $orderIssue = OrderIssue::query()->with('order.packages')->whereHas('order.packages', function ($query) use ($rejectedBill) {
                $query->where('logistic_number', $rejectedBill->logistic_number_return);
            })->first();
        }
        if (!isset($orderIssue)) { // 没有对应的问题发货订单
            $orderHeader = OracleDOCOrderHeader::query()->where('soreference1', function ($query) use ($rejectedBill) {
                $query->select('asnreference2')->from('DOC_ASN_HEADER')->where('asnreference3', $rejectedBill->logistic_number_return)->first();
            })->first();
//                $orderHeader = OracleDOCOrderHeader::query()->where('soreference1',function($query)use($rejectedBill){
//                    $query->select('asnreference2')->from('DOC_ASN_HEADER')->where('asnreference3',$rejectedBill->logistic_number_return)->first();
//                })->first();
            if (!isset($orderHeader)) return;
            $orderIssue = OrderIssue::query()->with('order')->whereHas('order', function ($query) use ($orderHeader) {
                $query->where('code', $orderHeader->orderno);
            })->first();
        }
        if (isset($orderIssue)) {
            // 更新问题件的退回单号
            if ($orderIssue['logistic_number_return'] != $rejectedBill['logistic_number_return'])
                $orderIssue->update(['logistic_number_return' => $rejectedBill['logistic_number_return']]);
            //确认问题件有的时候需要更新状态和提示
            $orderIssue->同步退单状态();
            $orderIssue->update(['is_new_rejecting' => '有']);
            app('LogService')->log(__METHOD__, __FUNCTION__, '退回单同步问题件' . json_encode($rejectedBill) . json_encode($orderIssue));
        }
    }

    public function syncLoadedStatusByAsnHerder($asnHerders)
    {
        $updateParams=$this->getNeedUpdateLoadedStatusByWms($asnHerders);
        if (!$updateParams)return;
        if (count($updateParams) > 1) {
            $this->batchUpdate($updateParams);
        }
    }

    public function getNeedUpdateLoadedStatusByWms($asnHerders)
    {
        if ($asnHerders->isEmpty()) return null;
        $updateCollect = $this->getUpdateCollect($asnHerders);
        if ($updateCollect->isEmpty()) return null;
        $logisticNumberReturn = $this->getLogisticNumberReturn($updateCollect);
        $rejectedBills = $this->getRejectedBills($logisticNumberReturn);
        if ($rejectedBills->isEmpty()) return null;
        $updateParams = [[
            'logistic_number_return', 'is_loaded', 'updated_at'
        ]];
        $updated_at = Carbon::now()->toDateTimeString();
        /** @var DataHandlerService $dataHandlerService */
        $dataHandlerService = app(DataHandlerService::class);
        $rejectedBills_map = $dataHandlerService->dataHeader(['logistic_number_return'], $rejectedBills);
        foreach ($updateCollect as $data) {
            if (!$data->asnreference3 && !$data->notes) {
                continue;
            }
            $result = [];
            if ($data->asnreference3) {
                $rejectedBill = $dataHandlerService->getKeyValue(['logistic_number_return' => $data->asnreference3], $rejectedBills_map);
                if ($rejectedBill && $rejectedBill->is_loaded != 1) $updateParams[] = [
                    'logistic_number_return' => $data->asnreference3,
                    'is_loaded' => 1,
                    'updated_at' => $updated_at,
                ];
            } else {
                preg_match("/[a-zA-Z]{0,5}\d{6,20}/", $data->notes, $result);
                if (count($result)<1) continue;
                $rejectedBill = $dataHandlerService->getKeyValue(['logistic_number_return' => $result[0]], $rejectedBills_map);
                if ($rejectedBill && $rejectedBill->is_loaded != 1) $updateParams[] = [
                    'logistic_number_return' => $result[0],
                    'is_loaded' => 1,
                    'updated_at' => $updated_at,
                ];
                $result = [];
            }
        }
        return $updateParams;
    }
    public function getUpdateCollect($asnHerders)
    {
        $updateCollect = collect();
        foreach ($asnHerders as $asnHerder) {
            if (($asnHerder->asnType->codename_c == '退货入库'
                    || $asnHerder->asnType->codename_c == '其他入库')
                && ($asnHerder->asnStatus->codename_c == '已入库'
                    ||$asnHerder->asnStatus->codename_c == 'ASN关闭')) {
                $updateCollect->add($asnHerder);
            }
        }
        return $updateCollect;
    }

    public function getLogisticNumberReturn($updateCollect)
    {
        $logisticNumberReturn = [];
        foreach ($updateCollect as $data) {
            if (!$data->asnreference3 && !$data->notes) {
                continue;
            }
            $result = [];
            if ($data->asnreference3) {
                array_push($logisticNumberReturn, $data->asnreference3);
            } else {
                preg_match("/[a-zA-Z]{0,5}\d{6,20}/", $data->notes, $result);
                if (count($result) > 0) array_push($logisticNumberReturn, $result[0]);
                $result = [];
            }
        }
        return $logisticNumberReturn;
    }

    public function batchUpdate($params)
    {
        return app(BatchUpdateService::class)->batchUpdate('rejected_bills', $params);
    }

    public function getRejectedBills(array $logisticNumberReturn)
    {
        if (count($logisticNumberReturn) < 1) {
            return null;
        }
        return RejectedBill::query()->whereIn('logistic_number_return', $logisticNumberReturn)->get();
    }
}
