<?php

namespace App\Services;

use App\Exports\RejectedExport;
use App\OracleDOCASNHeader;
use App\OracleDOCOrderHeader;
use App\OrderIssue;
use App\RejectedBill;
use App\Services\common\QueryService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Traits\ServiceAppAop;


class RejectedService
{
    use ServiceAppAop;
    protected $modelClass=Rejected::class;
    /** @var CacheService $cacheService */
    private $cacheService;
    function __construct(){
        $this->instant($this->cacheService,'CacheService');
    }
    private function    conditionQuery(array $param)
    {
        $user = Auth::user();
        $rejectedBills = RejectedBill::query()->with('user','owner', 'logistic', 'items.quality','orderIssueRejectedBill:logistic_number_return')
            ->orderBy('rejected_bills.id', 'desc')
            ->whereIn('rejected_bills.id_owner', $user ? (app('UserService')->getPermittingOwnerIds($user) ?? []) : []);
        $columnQueryRules = [
            'created_at_start' => ['alias' => 'created_at', 'startDate' => ' 00:00:00'],
            'created_at_end' => ['alias' => 'created_at', 'endDate' => ' 23:59:59'],
            'owner_id' => ['alias' => 'id_owner', 'multi' => ','],
            'order_number' => ['batch' => ''],
            'remark' => ['batch' => '','timeLimit'=>15],
            'logistic_number' => ['batch' => ''],
            'mobile_sender' => ['batch' => ''],
            'checked_numbers' => ['batch' => ''],
            'id' => ['multi' => ','],
        ];
        if ($param['id_quality_label'] ?? false) {
            if ($param['id_quality_label'] == 1) {
                $rejectedBills->whereDoesntHave('items', function ($query) {
                    $query->where('id_quality_label', 2);
                });
            } else {
                $rejectedBills->whereHas('items', function ($query) {
                    $query->where('id_quality_label', 2);
                });
            }
            unset($param['id_quality_label']);
        }
        if (isset($param["is_checked"])){
            if ($param["is_checked"] == "1"){
                $rejectedBills = $rejectedBills->where('rejected_bills.is_checked', true);
            }else {
                $rejectedBills = $rejectedBills->where(function ($query) {
                    $query->where('rejected_bills.is_checked', false)
                        ->orWhere('rejected_bills.is_checked', null);
                });
            }
            unset($param["is_checked"]);
        }

        if (isset($param["is_loaded"])) {
            $is_loaded = $param["is_loaded"];
            if ($is_loaded == 'null') $is_loaded = null;
            $rejectedBills = $rejectedBills->where('rejected_bills.is_loaded', $is_loaded);
            unset($param["is_loaded"]);
        }
        if ($param["barcode_goods"] ?? false) {
            $barcode_goods = $param["barcode_goods"];
            $rejectedBills->whereHas('items', function ($query) use ($barcode_goods) {
                if (strpos($barcode_goods, ',') || strpos($barcode_goods, '，') || strpos($barcode_goods, ' ')) {
                    $arr = array_filter(preg_split('/[,， ]+/is', $barcode_goods));
                    $query->whereIn('barcode_goods', $arr);
                    unset($barcode_goods);
                } else {
                    $query->where('barcode_goods','like', trim($barcode_goods).'%');
                }
            });
            unset($param["barcode_goods"]);
        }
        if ($param["logistic_number_return"] ?? false) {
            if (strpos($param["logistic_number_return"], ',') || strpos($param["logistic_number_return"], '，') || strpos($param["logistic_number_return"], ' ')) {
                $arr = array_filter(preg_split('/[,， ]+/is', $param["logistic_number_return"]));
                $rejectedBills = $rejectedBills->whereIn('logistic_number_return', $arr);
                unset($param["logistic_number_return"]);
            } else {
                $columnQueryRules['logistic_number_return'] = ['timeLimit' => 15];
            }
        }
        if(isset($param['is_issue'])){
            if($param['is_issue'] == 'true'){
                $rejectedBills->whereHas('orderIssue');
            }else{
                $rejectedBills->doesntHave('orderIssue');
            }
            unset($param['is_issue']);
        }
        $rejectedBills = app(QueryService::class)->query($param, $rejectedBills, $columnQueryRules,"rejected_bills");

        return $rejectedBills;
    }

    public function paginate(Request $request)
    {
        return $this->cacheService->getOrExecute('RejectedsPaginate'.md5(json_encode($request->toArray())),function()use($request){
            return $this->conditionQuery($request->input())->paginate($request->paginate ?? 50);
        },config('cache.expirations.oftenChange'));
    }

    public function get(Request $request)
    {
        return $this->cacheService->getOrExecute('Rejecteds'.md5(json_encode($request->toArray())),function()use($request){
            return $this->conditionQuery($request->input())->get();
        },config('cache.expirations.oftenChange'));
    }
    public function getSql(array $param){
        $sql = $this->conditionQuery($param)->selectRaw('rejected_bills.*')->whereNull('rejected_bills.deleted_at')
            ->leftJoin('owners','rejected_bills.id_owner','=','owners.id')
            ->selectRaw('owners.name owner_name')
            ->leftJoin('logistics','rejected_bills.id_logistic_return','=','logistics.id')
            ->selectRaw('logistics.name logistic_name')
            ->leftJoin('rejected_bill_items','rejected_bills.id','=','rejected_bill_items.id_rejected_bill')
            ->selectRaw('rejected_bill_items.created_at item_created_at,
                rejected_bill_items.barcode_goods item_barcode,
                rejected_bill_items.name_goods item_name,
                rejected_bill_items.amount item_amount,
                rejected_bill_items.batch_number item_batch_number,
                rejected_bill_items.made_at item_made_at,
                rejected_bill_items.validity_at item_validity_at,
                rejected_bill_items.remark item_remark')->whereNull("rejected_bill_items.deleted_at")
            ->leftJoin('quality_labels','rejected_bill_items.id_quality_label','=','quality_labels.id')
            ->selectRaw('quality_labels.name quality_label_name')
            ->leftJoin('users','rejected_bills.id_operator','=','users.id')
            ->selectRaw('users.name operator_name');
        return $sql->sql();
    }

    public function exportData(Request $request)
    {
        $rejectedBills = $this->conditionQuery($request->input());
        if ($rejectedBills->count() > RejectedExport::$max) {
            $rejectedBills->where('is_finished', false);
        }
        return $rejectedBills;
    }

    public function syncOrderIssue($rejectedBillId)
    {
        $rejectedBIll = RejectedBill::where('id', $rejectedBillId)->first();
        $ASNHeader = OracleDOCASNHeader::where('asnreference3', $rejectedBIll->logistic_number_return)->first();
        if (!$ASNHeader) {
            return;
        }
        $orderHeader = OracleDOCOrderHeader::where('soreference1', $ASNHeader->asnreference2)->first();
        if (!$orderHeader) {
            return;
        }
        $order = app("OrderService")->first(['code'=>$orderHeader->orderno]);
        if (!$order) {
            return;
        }
        OrderIssue::where('order_id', $order->id)->where('is_new_rejecting', '<>', 2)->update('is_new_rejecting', 2);
    }

    public function getRejectedByClientNo($clientNo){
        $orderHeader = OracleDOCOrderHeader::where('SOREFERENCE1',$clientNo)->first();
        if(!$orderHeader){
            return null;
        }
        $rejectedBill = RejectedBill::with('items')->where('order_number',$orderHeader->orderno)->first();
        if($rejectedBill){
            return $rejectedBill;
        }
        $ASNHeader =  OracleDOCASNHeader::where('ASNREFERENCE2',$clientNo)->first();
        if(!$ASNHeader){
            return null;
        }
        return RejectedBill::with('items')->where('logistic_number_return',$ASNHeader->asnrefernce3)->first();
    }

    public function 返回有问题件的ID($rejectedBill)
    {
        if(!isset($rejectedBill)){return ;}
        $rejectedBills =  RejectedBill::query()->with('orderIssue')->whereHas('orderIssue')->get();
        return $rejectedBills->map(function($rejectedBill){
            return $rejectedBill->id;
        });
    }
}
