<?php

namespace App\Services;

use App\Exports\RejectedExport;
use App\Logistic;
use App\OracleDOCASNDetail;
use App\OracleDOCASNHeader;
use App\OracleDOCOrderHeader;
use App\Order;
use App\OrderIssue;
use App\Owner;
use App\RejectedBill;
use App\Services\common\QueryService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RejectedService
{
    private function conditionQuery(Request $request)
    {
        $user = Auth::user();
        $rejectedBills = RejectedBill::query()->with('owner', 'logistic', 'items')->orderBy('id', 'desc')->whereIn('id_owner',
            $user ? $user->getPermittingOwnerIdsAttribute() : []);
        $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' => ['like' => ''],
            'logistic_number' => ['like' => ''],
            'mobile_sender' => ['like' => ''],
            'checked_numbers' => ['like' => ''],
        ];
        if ($request->id_quality_label != '') {
            if ($request->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);
                });
            }
            $request->offsetUnset('id_quality_label');
        }
        if ($request->is_checked != '') {
            if (!$request->is_checked)
                $rejectedBills = $rejectedBills->where(function ($query) {
                    $query->where('is_checked', false)
                        ->orWhere('is_checked', null);
                });
            else {
                $rejectedBills = $rejectedBills->where('is_checked', true);
            }
            $request->offsetUnset('is_checked');
        }
        if ($request->is_loaded != '') {
            $is_loaded = $request->is_loaded;
            if ($is_loaded == 'null') $is_loaded = null;
            $rejectedBills = $rejectedBills->where('is_loaded', $is_loaded);
            $request->offsetUnset('is_loaded');
        }
        if ($request->barcode_goods != '') {
            $barcode_goods = $request->barcode_goods;
            $rejectedBills->whereHas('items', function ($query) use ($barcode_goods) {
                $query->where('barcode_goods', 'like', trim($barcode_goods) . '%');
            });
            $request->offsetUnset('barcode_goods');
        }
        if ($request->logistic_number_return) {
            if (strpos($request->logistic_number_return, ',') || strpos($request->logistic_number_return, '，') || strpos($request->logistic_number_return, ' ')) {
                $arr = array_filter(preg_split('/[,， ]+/is', $request->logistic_number_return));
                $rejectedBills = $rejectedBills->whereIn('logistic_number_return', $arr);
                $request->offsetUnset('logistic_number_return');
            } else {
                $columnQueryRules['logistic_number_return'] = ['timeLimit' => 15];
            }
        }
        $rejectedBills = app(QueryService::class)->query($request, $rejectedBills, $columnQueryRules);
        return $rejectedBills;
    }

    public function paginate(Request $request)
    {
        return $this->conditionQuery($request)->paginate($request->paginate ?? 50);
    }

    public function get(Request $request)
    {
        return $this->conditionQuery($request)->get();
    }

    public function exportData(Request $request)
    {
        $rejectedBills = $this->conditionQuery($request);
        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 = Order::where('code', $orderHeader->orderno)->first;
        if (!$order) {
            return;
        }
        OrderIssue::where('order_id', $order->id)->where('is_new_rejecting', '<>', 2)->update('is_new_rejecting', 2);
    }

    public function getRejectedByWMSOrderNo($WMSOrderNo){
        $orderHeader = OracleDOCOrderHeader::where('orderNo',$WMSOrderNo)->first();
        if(!$orderHeader){
            return null;
        }
        $ASNHeader =  OracleDOCASNHeader::where('ASNReference3',$orderHeader->sorefernce1)->first();
        if(!$ASNHeader){
            return null;
        }
        return RejectedBill::with('items')->where('logistic_number_return',$ASNHeader->asnrefernce3)->first();
    }
}
