<?php

namespace App;

use App\Traits\ModelTimeFormat;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;


use App\Traits\ModelLogChanging;

/**
 * @method Builder filter
 */

class OrderIssue extends Model
{
    use ModelLogChanging;

    //
    use ModelTimeFormat;
    use SoftDeletes;

    protected $fillable = [
        'order_id', 'created_at', 'rejected_bill_id','user_owner_group_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','archive_at'];
    /*
     * second_client_no 二次客户订单号
     * second_logistic_number 二次运单号 【二次运单号可以单独存在，当二次客户订单号有对应的订单信息时，显示的是二次客户订单号对应的运单号，没有的话显示二次原单号】
     * rejecting_status
     * result_explain 情况说明
     * final_status
     * situation_explain
     * custom_code  自定义订单号 客户客服自定义
     * imported_status 导入处理
     * 退回单号
     * finance_confirm 财务确认
     * hidden_tag 隐藏标识
     * archive_at 归档时间
     */
    protected $appends = [];

    public function order(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Order::class, 'order_id', 'id');
    }

    public function rejectedBills(): BelongsToMany
    {
        return $this->belongsToMany(RejectedBill::class,'order_issue_rejected_bill','order_issue_id','logistic_number_return','id','logistic_number_return');
    }

    public function orderIssueRejectedBills(): HasMany
    {
        return $this->hasMany(OrderIssueRejectedBill::class);
    }

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

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

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

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

    public function userOwnerGroup(): BelongsTo
    {
        return $this->belongsTo(UserOwnerGroup::class);
    }

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

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

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

    public function getProcessingTimeAttribute(): ?string
    {
        $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 syncRejectingStatus()
    {
        $this->syncRejectedBillStatus($this);
    }

    public function syncRejectedBillStatus($orderIssue)
    {
        if (!$orderIssue->order_id) return;
        $orderIssueMap = [];
        $rejectedMap = [];
        $owner_id = $orderIssue->order->owner_id;

        // 获取对应订单的所有商品
        $orderPackageQuery = OrderPackage::query()->selectRaw("id")->where('order_id', $orderIssue->order_id);
        $orderPackageCommodities = OrderPackageCommodities::query()->with('commodity')->whereIn('order_package_id', $orderPackageQuery)->get();
        foreach ($orderPackageCommodities as $orderPackageCommodity) {
            $code = $orderPackageCommodity->commodity->sku;
            if (empty($orderIssueMap[$code])) $orderIssueMap[$code] = $orderPackageCommodity->amount;
            else $orderIssueMap[$code] += $orderPackageCommodity->amount;
        }

        // 获取对应退回单的所有商品
        $orderIssueRejectedBillQuery = OrderIssueRejectedBill::query()->selectRaw("logistic_number_return")->where("order_issue_id", $orderIssue->id);
        $RejectedBills = RejectedBill::query()->with('items.quality')->whereIn("logistic_number_return", $orderIssueRejectedBillQuery)->get();
        /** @var RejectedBill $rejectedBill */
        foreach ($RejectedBills as $rejectedBill) {
            foreach ($rejectedBill->items as $item) {
                $code = $item->barcode_goods;
                $exists = Commodity::query()->where("sku", $code)->where('owner_id',$owner_id)->exists();
                if (!$exists) {
                    $commodityBarcode = CommodityBarcode::query()->with(['commodity' => function ($query) use ($owner_id) {
                        /** @var Builder $query */
                        $query->where('owner_id', $owner_id)->whereNotNull('sku');
                    }])->where('code', $code)->first();
                    if($commodityBarcode && $commodityBarcode->commodity) $code = $commodityBarcode->commodity->sku;
                }
                $qualityName = $item->quality->name;
                if (empty($rejectedMap[$code]) || empty($rejectedMap[$code][$qualityName])) $rejectedMap[$code][$qualityName] = $item->amount;
                else $rejectedMap[$code][$qualityName] += $item->amount;
            }
        }
        // 比较
        $status = $this->getRejectingStatus($orderIssueMap, $rejectedMap);
        $this->update(['rejecting_status' => $status]);
    }

    private function getRejectingStatus($orderIssueMap, $rejectedMap): string
    {
        //未退回，差异退回，全部退回，超量退回，部分退回
        if (count($rejectedMap) == 0) return "未退回";
        $equal = 0;
        $portion = 0;
        foreach ($rejectedMap as $key => $map) {
            if (isset($map['残次']) && $map['残次'] > 0) return "差异退回";
            if (empty($orderIssueMap[$key])) return "差异退回";
            if(isset($rejectedMap[$key]['正品']) && isset($orderIssueMap[$key])){
                if ( $rejectedMap[$key]['正品'] < $orderIssueMap[$key]) $portion += 1;
                if ( $rejectedMap[$key]['正品'] > $orderIssueMap[$key]) return "超量退回";                                 // 超量退回
                if ( $rejectedMap[$key]['正品'] == $orderIssueMap[$key]) $equal += 1;
            }
        }
        if ($equal == count($orderIssueMap) && $equal == count($rejectedMap)  && $portion == 0) return "全部退回";        // 全部退回
        if ($portion > 0) return "部分退回";                                                                              // 部分退回
        // 部分退回
        if (count(array_diff_key($orderIssueMap,$rejectedMap)) > 0)return '部分退回';
        if (count(array_diff_key($rejectedMap,$orderIssueMap)) > 0)return '差异退回';
        return "无";
    }

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

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

    /**
     * 同步退货单号
     */
    public function syncRejectedBills()
    {
        $order_packages = $this->order->packages;
        if($order_packages){
            foreach ($order_packages as $order_package) {
                $logistic_number = $order_package->logistic_number;
                $rejectedBill = RejectedBill::query()->where('logistic_number_return',$logistic_number)->first();
                if($rejectedBill){
                    if(OrderIssueRejectedBill::isExit($this->id,$logistic_number))continue;
                    $this->joinRejectedBill($logistic_number);
                    if(isset($rejectedBill->items))
                        $this->is_new_rejecting = '有';
                }
            }
            $this->save();
        }
    }

    public function syncRejected($logistic_number)
    {
        $query = RejectedBill::query()->selectRaw('id');
        if(is_array($logistic_number)){
            $query->whereIn('logistic_number_return',$logistic_number);
        }elseif (is_string($logistic_number)){
            $query->where('logistic_number_return',$logistic_number);
        }else return;
        $items = RejectedBillItem::query()->whereIn('id_rejected_bill',$query);
        if($items->count() > 0) $this->update(['is_new_rejecting'=>'有']);
        elseif($items->count() == 0) $this->update(['is_new_rejecting'=>'无']);
    }


    /**
     * @param array|string $logistic_number
     * @return array|void
     */
    public function joinRejectedBill($logistic_number)
    {
        if(!$logistic_number)return null;
        $this->syncRejected($logistic_number);
        if(is_array($logistic_number)){
            return $this->rejectedBills()->sync($logistic_number,false);
        }
        return $this->rejectedBills()->attach($logistic_number);
    }

    public function unJoinRejectedBill($logistic_number)
    {
        return $this->rejectedBills()->detach($logistic_number);
    }

    public function reviseJoinRejectedBill($logistic_number,$logistic_number_update)
    {
        return $this->rejectedBills()->updateExistingPivot($logistic_number,['logistic_number_return'=>$logistic_number_update]);
    }

    public function scopeFilter($query, $filters)
    {
        return $filters->apply($query);
    }

    public function scopeDefaultWith($query)
    {
        $this->scopeJsonWith($query);
        return $query->with(['top'])
            ->selectRaw('order_issues.* ,order_issue_on_tops.id top_id ,order_issue_on_tops.remark,order_issue_on_tops.updated_at top_update')
            ->leftJoin('order_issue_on_tops', 'order_issue_on_tops.order_issue_id', '=', 'order_issues.id')
            ->whereNull('order_issue_on_tops.deleted_at')
            ->orderBy('order_issue_on_tops.updated_at', 'desc')
            ->orderBy('order_issues.id', 'desc');
    }

    public function scopeJsonWith($query)
    {
        return $query->with(['issueType', 'logs' => function ($query){
            $query->with('user')->orderByDesc('created_at');
        },'order'=>function($query){
            $query->with(['shop', 'logistic', 'owner', 'packages.commodities.commodity.barcodes']);
        },'secondOrder'=>function($query){
            $query->with(['shop', 'logistic', 'owner', 'packages.commodities.commodity.barcodes']);
        },'orderIssueRejectedBills.rejectedBill'=>function($query){
            $query->with(['owner','logistic','user','items.quality']);
        },'userWorkgroups','userOwnerGroup']);

    }

    public function userWorkgroups(): BelongsToMany
    {
        return $this->belongsToMany(UserWorkgroup::class);
    }
}
