<?php

namespace App\Services;

use App\Feature;
use App\OracleActAllocationDetails;
use App\OracleDOCASNHeader;
use App\OracleDOCOrderHeader;
use App\Order;
use App\OrderIssue;
use App\OrderIssueRejectedBill;
use App\OrderPackage;
use App\OwnerFeeDetail;
use App\Owner;
use App\RejectedBill;
use App\Services\common\BatchUpdateService;
use App\Services\common\DataHandlerService;
use App\Store;
use App\StoreRejected;
use Carbon\Carbon;
use App\Traits\ServiceAppAop;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
use Overtrue\LaravelPinyin\Facades\Pinyin;
use function Symfony\Component\String\s;


class RejectedBillService
{
    use ServiceAppAop;
    protected $modelClass=RejectedBill::class;
    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);
    }

    /**
     * 连接问题件
     *
     * @param RejectedBill $rejectedBill
     */
    public function joinOrderIssue($rejectedBill)
    {
        $rejectedBill->joinOrderIssue();
    }


    /**
     * 同步退回单号
     * @param RejectedBill $rejectedBill
     */
    public function syncOrderIssue($rejectedBill)
    {
        $rejectedBill->syncOrderIssue();
    }

    public function syncLoadedStatusByAsnHerder($asnHerders)
    {
        //是否审核
        $updates=$this->getNeedUpdateCheckedStatusByWms($asnHerders);
        if ($updates && count($updates) > 1) $this->batchUpdate($updates);
        //是否入库
        $updateParams=$this->getNeedUpdateLoadedStatusByWms($asnHerders);
        if ($updateParams && count($updateParams) > 1) $this->batchUpdate($updateParams);
    }

    public function getNeedUpdateLoadedStatusByWms($asnHerders)
    {

        if (!$asnHerders) return null;
        $updateCollect = $this->getUpdateCollect($asnHerders);
        if (!$updateCollect) return null;
        $logisticNumberReturn = $this->getLogisticNumberReturn($updateCollect);
        $checkedNumbers = $this->getCheckNumbers($updateCollect);
        $rejectedBills = $this->getRejectedBills($logisticNumberReturn,$checkedNumbers);
        if (!$rejectedBills) return null;
        $updateParams = [[
            'id', '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;
            if ($data->asnreference3) {
                $param=[];
                preg_match("/[a-zA-Z]{0,5}\d{6,20}/", $data->asnreference3, $param);
                if (count($param)<1) continue;
                $rejectedBill = $dataHandlerService->getKeyValue(['logistic_number_return' => $param[0]], $rejectedBills_map);
                if ($rejectedBill && $rejectedBill->is_loaded != 1) $updateParams[] = [
                    'id'=>$rejectedBill->id,
                    'is_loaded' => 1,
                    'updated_at' => $updated_at,
                ];
                unset( $param);
            } else {
                $result = [];
                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[] = [
                    'id'=>$rejectedBill->id,
                    'is_loaded' => 1,
                    'updated_at' => $updated_at,
                ];
                if (!$rejectedBill && $data->customerid && $data->notes){
                    $checkedNumber=$this->screenCheckNumber($data->customerid,$data->notes);
                    if (!$checkedNumber)continue;
                    $rejects=RejectedBill::query()->where('checked_numbers',$checkedNumber)->get();
                   foreach ($rejects as $reject){
                       $updateParams[] = [
                           'id'=>$reject->id,
                           'is_loaded' => 1,
                           'updated_at' => $updated_at,
                       ];
                   }
                }

               unset($result);
            }
        }
        return $updateParams;
    }
    public function getUpdateCollect($asnHerders)
    {
        $updateCollect = collect();
        foreach ($asnHerders as $asnHerder) {
            if ($asnHerder->asnType && $asnHerder->asnStatus &&
                ($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;
            if ($data->asnreference3) {
                $param=[];
                preg_match("/[a-zA-Z]{0,5}\d{6,20}/", $data->asnreference3, $param);
                if (count($param) > 0) array_push($logisticNumberReturn, $param[0]);
                unset($param);
            } else {
                $result = [];
                preg_match("/[a-zA-Z]{0,5}\d{6,20}/", $data->notes, $result);
                if (count($result) > 0) array_push($logisticNumberReturn, $result[0]);
                unset($result);
            }
        }
        return $logisticNumberReturn;
    }
    public function getCheckNumbers($updateCollect): array
    {
        $checkNumbers=[];
        foreach ($updateCollect as $data){
            if (!$data->notes) continue;
            $checkedNumber=$this->screenCheckNumber($data->customerid,$data->notes);
            if (!$checkedNumber) continue;
            array_push($checkNumbers, $checkedNumber);
        }
        return $checkNumbers;
    }

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

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

    public function getNeedUpdateCheckedStatusByWms($asnHerders)
    {
        if (!$asnHerders) return null;
        $logisticNumberReturn = $this->getLogisticNumberReturn($asnHerders);
        $rejectedBills = $this->getRejectedBills($logisticNumberReturn);
        if (!$rejectedBills) return null;
        $updateParams = [[
            'id', 'is_checked','checked_numbers','updated_at'
        ]];
        $updated_at = Carbon::now()->toDateTimeString();
        /** @var DataHandlerService $dataHandlerService */
        $dataHandlerService = app(DataHandlerService::class);
        $rejectedBills_map = $dataHandlerService->dataHeader(['logistic_number_return'], $rejectedBills);
        foreach ($asnHerders as $data) {
            if (!$data->asnreference3 && !$data->notes) continue;
            if ($data->asnreference3) {
                $param=[];
                preg_match("/[a-zA-Z]{0,5}\d{6,20}/", $data->asnreference3, $param);
                if (count($param)<1) continue;
                $rejectedBill = $dataHandlerService->getKeyValue(['logistic_number_return' => $param[0]], $rejectedBills_map);
                if ($rejectedBill && $rejectedBill->is_checked != 1) $updateParams[] = [
                    'id'=>$rejectedBill->id,
                    'is_checked' => 1,
                    'checked_numbers' => $rejectedBill->makeCheckedNumbers(),
                    'updated_at' => $updated_at,
                ];
                unset($param);
            } else {
                $result = [];
                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_checked != 1)
                    $updateParams[] = [
                        'id'=>$rejectedBill->id,
                        'is_checked' => 1,
                        'checked_numbers' => $rejectedBill->makeCheckedNumbers(),
                        'updated_at' => $updated_at,
                    ];
                unset($result);
            }
        }
        return $updateParams;
    }

    public function updateCheckedStatusByWms($logistic_number_return)
    {
        $asnHeader=OracleDOCASNHeader::query()
            ->select('asnno','customerid','notes','warehouseid','asnreference3')
            ->where('asnreference3',$logistic_number_return)
            ->orWhere('notes','like','%'.$logistic_number_return.'%')
            ->first();
        if ($asnHeader){
            $rejectBill=RejectedBill::query()->where('logistic_number_return',$logistic_number_return)->first();
            if ($rejectBill->is_checked==1)return null;
            $rejectBill->update([
                'is_checked'=>1,
                'checked_numbers' => $rejectBill->makeCheckedNumbers(),
            ]);
            return $rejectBill;
        }
        return null;
    }
    public function screenCheckNumber($ownerCode,$note){
        $ownerName=Owner::query()->where('code',$ownerCode)->value('name');
        $result = [];
        $pinyinOwnerName=Pinyin::convert($ownerName);
        $pinyinArr=array_map(function($pinyin){
            return $pinyin[0];
        },$pinyinOwnerName);
        $initials=implode("", $pinyinArr);
        if (!$initials) {
            preg_match("/[a-z0-9]{0,5}\d{6,20}/", $note, $result);
        }else{
            preg_match("/$initials{0,5}\d{6,20}/", $note, $result);
        }
        if (count($result)<1) return null;
        return $result[0];
    }

    /**
     * @param string $logisticNumber
     * @return array|Builder|Model|object|null
     */
    public function findOrderByOrderPackage($logisticNumber)
    {
        // 本地订单的快递单号 原单退回
        $order_package_query =  OrderPackage::query()->selectRaw('order_id')->where('logistic_number',$logisticNumber);
        /** @var Order $order */
        $order = Order::query()->whereIn('id',$order_package_query )->first();
        if($order){
            $order = $order->toArray();
            $order['logistic_number'] = '原单退回';
            return $order;
        }
        return null;
    }

    public function findOrderByStoreRejected($logisticNumber)
    {
        $store_rejected_query = StoreRejected::query()->selectRaw('order_id')->where('logistic_number_return',$logisticNumber);
        $order = Order::query()->whereIn('id',$store_rejected_query)->first();
        if($order){
            $order_package = OrderPackage::query()->where('order_id',$order->id)->first();
            $order = $order->toArray();
            $order['logistic_number'] = $order_package['logistic_number'] ?? '';
            return $order;
        }
        return null;
    }


    public function findOrderByOrderHeader($logisticNumber)
    {
        $act_allocation_details_query = OracleActAllocationDetails::query()->selectRaw('OrderNo')->where('pickToTraceId',$logisticNumber);
        /** @var OracleDOCOrderHeader $order_header */
        $order_header = OracleDOCOrderHeader::query()->whereIn('OrderNo',$act_allocation_details_query)->first();
        if($order_header){
            return [
                'logistic_id' => $order_header->getLogistic()['id'] ?? '',
                'owner_id' => $order_header->getOwner()['id'] ?? '',
                'consignee_name' => $order_header['c_contact'] ?? '' ,
                'consignee_phone' =>  $order_header['c_tel2'] ?? $order_header['c_tel1'],
                'client_code'  => $order_header['soreference1'] ?? '',
                'logistic_number'  => $order_header['soreference5'] ?? '',
            ];
        }
        return null;
    }
    public function findOrderByOrderIssue($logisticNumberReturn)
    {
        // 问题件关联的退回单
        $order_issue_rejected_bill_query = OrderIssueRejectedBill::query()->selectRaw('order_issue_id')->where('logistic_number_return',$logisticNumberReturn);
        $oder_issue_query = OrderIssue::query()->selectRaw('order_id')->whereIn('id',$order_issue_rejected_bill_query);
        $order = Order::query()->whereIn('id',$oder_issue_query)->first();
        if($order){
            $order_package = OrderPackage::query()->where('order_id',$order->id)->first();
            $order = $order->toArray();
            $order['logistic_number'] = $order_package['logistic_number'] ?? '';
            $order['logistic_id'] = null;
            return $order;
        }
        return null;
    }

    /**
     * 建立即时账单，已存在覆盖，不存在补录
     *
     * @param RejectedBill $rejectedBill
     *
     */
    public function buildInstantBill(RejectedBill $rejectedBill)
    {
        /** @var \stdClass $rejectedBill */
        $number = array_column(StoreRejected::query()->where("logistic_number_return",$rejectedBill->logistic_number_return)->get()->toArray(),"store_id");

        foreach (Store::query()->with("storeItems")->whereIn("id",$number)->get() as $store){
            /** @var OwnerPriceOperationService $service */
            $service = app("OwnerPriceOperationService");
            list($id,$money,$taxFee) = $service->matching($store, Feature::MAPPING["store"], $store->owner_id, "入库",0);
            $bill = OwnerFeeDetail::query()->where("outer_id",$store->id)->where("outer_table_name","stores")->first();
            if ($bill) $bill->update([
                    "work_fee" => $money,
                    "owner_price_operation_id" => $id,
            ]); else app("OwnerFeeDetailService")->create([
                "owner_id" => $store->owner_id,
                "worked_at" => $store->created_at,
                "type" => "收货",
                "operation_bill" => $store->asn_code,
                "commodity_amount" => array_sum(array_column($store->storeItems->toArray(), "amount")),
                "work_fee" => $money,
                "owner_price_operation_id" => $id,
                "created_at" => date('Y-m-d H:i:s'),
                "outer_id" => $store->id,
                "outer_table_name" => "stores",
                "work_tax_fee" => $taxFee,
            ]);
        }
    }
}
