<?php

namespace App;

use App\Traits\ModelTimeFormat;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class OrderIssue extends Model
{
    //
    use ModelTimeFormat;
    use SoftDeletes;

    protected $fillable = [
        'order_id', 'created_at', 'rejected_bill_id',
        'rejecting_status', 'result_explain','logistic_number_return',
        'situation_explain', 'order_issue_type_id', 'second_order_id',
        'is_new_rejecting','second_client_no','second_logistic_number',
        'final_status',
        'logistic_indemnity_money', 'logistic_express_remission',
        'baoshi_indemnity_money', 'baoshi_express_remission', 'user_workgroup_id',
        'custom_code','imported_status','finance_confirm',
        'hidden_tag'];
    /*
     * second_client_no 二次客户订单号
     * second_logistic_number 二次运单号 【二次运单号可以单独存在，当二次客户订单号有对应的订单信息时，显示的是二次客户订单号对应的运单号，没有的话显示二次原单号】
     * rejecting_status
     * result_explain 情况说明
     * final_status
     * situation_explain
     * custom_code  自定义订单号 客户客服自定义
     * imported_status 导入处理
     * 退回单号
     * finance_confirm 财务确认
     * hidden_tag 隐藏标识
     */
    protected $appends = [
//        'secondLogisticNumber',
//        'createLog',
//        'endLog',
//        'processingTime',
//        'createUser',
//        'endUser',
    ];

    public function order()
    {
        return $this->belongsTo(Order::class, 'order_id', 'id');
    }

    public function rejectedBill()
    {
        return $this->belongsTo(RejectedBill::class, 'logistic_number_return', 'logistic_number_return');
    }

    public function issueType()
    {
        return $this->belongsTo('App\OrderIssueType', 'order_issue_type_id', 'id');
    }

    public function logs()
    {
        return $this->hasMany('App\OrderIssueProcessLog', 'order_issue_id', 'id');
    }

    public function top()
    {
        return $this->hasOne('App\OrderIssueOnTop', 'order_issue_id', 'id');
    }

    public function userWorkGroup()
    {
        return $this->belongsTo('App\UserWorkgroup', 'user_workgroup_id', 'id');
    }

    public function secondOrder()
    {
        return $this->hasOne('App\Order', 'client_code', 'second_client_no');
    }

//    public function getSecondLogisticNumberAttribute()
//    {
//        return $this['secondOrder']['code'] ?? '';
//    }

    public function getCreateLogAttribute()
    {
        return $this->logs->where('type', '创建')->first();
    }

    public function getEndLogAttribute()
    {
        return $this->logs->where('type', '结束')->last();
    }

    public function getProcessingTimeAttribute()
    {
        $createLogs = $this->getCreateLogAttribute();
        $endLogs = $this->getEndLogAttribute();
        if (($createLogs ?? false) && ($endLogs ?? false)) {
            $time = date_diff($createLogs->created_at, $endLogs->created_at);
            return $time->format('%a天, %h小时');
        }
        return null;
    }

    public function getCreateUserAttribute()
    {
        $createLog = $this->getCreateLogAttribute();
        return $createLog->user->name ?? '';
    }

    public function getEndUserAttribute()
    {
        $createLog = $this->getEndLogAttribute();
        return $createLog->user->name ?? '';
    }

    public function 同步退单状态(){
        $rejectedItems = [];
        $orderItems = [];
        $orderIssueId = $this['id'];
        if ($this->logistic_number_return ?? false) {
            $rejectedBillItems = RejectedBillItem::query()->with('quality')
                ->whereHas('rejectedBill.orderIssue', function ($query) use ($orderIssueId) {
                    $query->where('id',$orderIssueId);
                })->get();
            if($rejectedBillItems->where('quality.name','残次')->count() > 0){
                $this->update(['rejecting_status' => '差异退回']);
                return;
            }
            if (count($rejectedBillItems) == 0) {
                $this->update(['rejecting_status' => '未退回']);
                return;
            }
            $barcodeGoods = data_get($rejectedBillItems,'*.barcode_goods');
            $commodityBarcodes = CommodityBarcode::query()->with('commodity')->whereIn('code',$barcodeGoods)->get();
            $commodities = Commodity::query()->whereIn('sku',$barcodeGoods)->get();

            foreach ($rejectedBillItems as $item) {
                $barcode_goods = (string)$item->barcode_goods;
                $commodity = $commodities->where('sku',$barcode_goods)->first();
                if(!$commodity){
                    $commodityBarcode = $commodityBarcodes->where('code',$barcode_goods)->first();
                    $barcode_goods = $commodityBarcode->commodity->sku ?? $barcode_goods;
                }
                if (!isset($rejectedItems[$barcode_goods])){
                    $rejectedItems[$barcode_goods] = 0;
                }
                $rejectedItems[(string)$barcode_goods] += $item->amount;
            }
        } else {
            $this->update(['rejecting_status' => '未退回']);
            return;
        }
        if ($this->order_id  ?? false) {
            $items = OrderPackageCommodities::query()
                ->with(['commodity','package.order.issue'])
                ->whereHas('package.order.issue', function ($query) use ($orderIssueId) {
                    $query->where('id', $orderIssueId);
                })->get();
            if (count($items) > 0) {
                foreach ($items as $item) {
                    $sku = $item['commodity']['sku'];
                    if (! isset($orderItems[$sku])  ?? false){
                        $orderItems[$sku] = 0;
                    }
                    $orderItems[$sku] += $item->amount;
                }
            } else {
                $this->update(['rejecting_status' => '无']);
                return;
            }
        }
        $rejectedExcess = 0;    // 退回差异
        $rejectedReview = 0;    // 退回复核  $rejectedItems == $orderItems
        foreach ($rejectedItems as $key => $items) {
            if ($orderItems[$key] ?? false) {
                if ($rejectedItems[$key] == $orderItems[$key])
                    $rejectedReview++;
            } else
                $rejectedExcess++;
        }
        if ($rejectedExcess > 0) {
            $this->update(['rejecting_status' => '差异退回']);
            return;
        }
        // 全部退回 部分退回 超量退回 差异退回 未退回 无
        $isExcess = 0; // 超量 $orderItems < $rejectedItems
        $isDiff = 0;   // 部分 $orderItems > $rejectedItems
        $isAccord = 0; // 相同 $orderItems == $rejectedItems
        $isLack = 0;   // 缺少 $orderItems != $rejectedItems
        foreach ($orderItems as $key => $item) {
            if ($rejectedItems[$key] ?? false) {
                if ($orderItems[$key] < $rejectedItems[$key])
                    $isExcess++;
                else if ($orderItems[$key] > $rejectedItems[$key])
                    $isDiff++;
                else if ($orderItems[$key] == $rejectedItems[$key])
                    $isAccord++;
            } else
                $isLack++;
        }

        if($isAccord == $rejectedReview && $isLack == 0 && $isExcess == 0 && $isDiff==0 && $rejectedExcess == 0 )
            $this->update(['rejecting_status' => '全部退回']);
        else if($isExcess > 0 && $isAccord ==  $rejectedReview && $isDiff == 0 && $isLack == 0)
            $this->update(['rejecting_status' => '超量退回']);
        else if($isDiff >=0 && $isAccord == $rejectedReview && $isLack >=0 && $rejectedExcess ==0 && $isExcess==0)
            $this->update(['rejecting_status' => '部分退回']);
        else if($isLack >= 0 && $rejectedExcess>=0 && $isDiff>=0 && $isLack>=0 && $isExcess>=0 && $rejectedReview>=0)
            $this->update(['rejecting_status' => '差异退回']);
    }



    public function delete()
    {
        $this->logs()->delete();
        $this->top()->delete();
        return parent::delete();
    }

    public function deleteSafe()
    {
        return parent::delete();
    }


    // 同步退回单
    public function syncRejectedBill()
    {
        if(!isset($this['logistic_number_return'])){
            $order = $this->order;
            $rejectedBill = RejectedBill::query()->where('logistic_number','like','原单退回'.'%')->where('order_number',$order->client_code)->whereNotNull('order_number')->first();
            if($rejectedBill){
                $this->update(['logistic_number_return'=>$rejectedBill->logistic_number_return,'is_new_rejecting'=>'有']);
            }
        }
    }
}
