<?php

namespace App;

use App\Http\Controllers\Controller;
use App\Http\Controllers\LogisticNumberFeatureController;
use App\Services\OrderPackageCommoditiesService;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Overtrue\LaravelPinyin\Facades\Pinyin;

/**
 * @method static find(array|string|null $param)
 */use App\Traits\ModelTimeFormat;

class RejectedBill extends Model
{
    use ModelTimeFormat;
    use SoftDeletes;
    protected $fillable=['id_owner','order_number','sender','mobile_sender',
        'logistic_number','logistic_number_return','id_logistic_return',
        'is_loaded','fee_collected','remark','id_operator','is_checked'
        ,'is_finished','checked_numbers','remark','common_01','common_02'];

    protected $appends = ['owner_name','logistic_name','created_at_short'
        ,'is_loaded_str','goods_amount','is_loaded_null','operator_name'];
    function owner(){
        return $this->hasOne('App\Owner','id','id_owner');
    }
    function logistic(){
        return $this->hasOne('App\Logistic','id','id_logistic_return');
    }
    function items(){
        return $this->hasMany('App\RejectedBillItem','id_rejected_bill','id');
    }
    function rejectedBillItems(){
        return $this->items();
    }
    function wmsReflectReceive(){
        return $this->belongsTo('App\WMSReflectReceive','id','id_rejected_bill');
    }
    function setIsLoaded_toWaitConfirm(){
        if(config('api.jianshang_rejecteds_log_switch'))Controller::logS(__METHOD__,__FUNCTION__,"将待推单修改为待确认! 退单号：".$this['logistic_number_return'],Auth::user()['id']);
        $bill=RejectedBill::find($this['id']);
        $bill['is_loaded']=4;
        $bill->save();
    }
    function logisticName(){
        $logistic=$this->hasOne('App\Logistic','id','id_logistic_return')->first();
        return $logistic?$logistic['name']:'';
    }
    function makeCheckedNumbers(){
        $owner = $this->owner()->first();
        if(!$owner)return '';
        $pinyinOwnerName=Pinyin::convert($owner->name);
        $pinyinArr=array_map(function($pinyin){
            return $pinyin[0];
        },$pinyinOwnerName);
        $initials=implode("", $pinyinArr);
        $this['checked_numbers']=$initials.Carbon::now()->format('Ymd').$owner->getIncreasedCheckingCount();
        return $this['checked_numbers'];
    }
    function orderIssue(){
        return $this->hasOne('App\OrderIssue','rejected_bill_id','id');
    }

    function update(array $attributes = [], array $options = [])
    {
        (new LogisticNumberFeatureController())->createFeatures($this['logistic_number_return'],$this['id_logistic_return']);
        return parent::update($attributes, $options);
    }
    function save(array $options = [])
    {
        (new LogisticNumberFeatureController())->createFeatures($this['logistic_number_return'],$this['id_logistic_return']);
        return parent::save($options);
    }


    public function getOwnerNameAttribute(){
        $id_owner=$this['id_owner']??0;
        $owner=Owner::find($id_owner);
        return $this['owner_name']=$owner['name'];
    }
    public function getLogisticNameAttribute(){
        $id_logistic=$this['id_logistic_return']??0;
        $logistic=Logistic::find($id_logistic);
        return $this['logistic_name']=$logistic['name'];
    }
    public function getIsLoadedStrAttribute(){
        $val=$this['is_loaded']===null?'null':$this['is_loaded'];
        $val=$val===0?'0':$val;
        switch ($val){
            case 'null':return '无需入库';
            case '0':return '否';
            case 1:return '是';
            case 2:return '待推单';
            case 3:return '上传异常';
        }
        return '';
    }
    public function getCreatedAtShortAttribute(){
        return $this['created_at']?$this['created_at_short']=$this['created_at']->format('m-d H:i:s'):'';
    }
    public function getGoodsAmountAttribute(){
        $amount=0;
        $this->items()->get()->each(function (RejectedBillItem $item)use(&$amount){
            $amount+=$item['amount'];
        });
        return $amount;
    }
    public function getOperatorNameAttribute(){
        if(!$this['id_operator']){return '';}
        $user=User::find($this['id_operator']);
        return $user['name'];
    }
    public function getIsLoadedNullAttribute(){
        if($this['is_loaded']===null) return 'null';
        return $this['is_loaded'];
    }
    public function changeIsLoaded_ifItemsAllLoaded(){
        $allItemsAreLoaded=true;
        $this->items->each(function (RejectedBillItem $item)use(&$allItemsAreLoaded){
            if($item['is_loaded']=='未入库'){
                $allItemsAreLoaded=false;
                return false;
            }
        });
        if($allItemsAreLoaded){
            $this['is_loaded']=1;
        }else{
            $this['is_loaded']=0;
        }
        $this->update();
        return $this['is_loaded'];
    }

    public function syncOrderIssue(){
        $orderIssue = $this->orderIssue()->first();
        if(isset($orderIssue)){
           $this-> judgeRejectingStatus($orderIssue);
           OrderIssue::where('id',$orderIssue['id'])->update(['is_new_rejecting'=>'有']);
        }
    }

    private function judgeRejectingStatus(OrderIssue $orderIssue)
    {
        $orderPackageCommoditiesService = new OrderPackageCommoditiesService();
        $rejectedItems = [];
        $orderItems = [];
        if ($orderIssue->rejected_bill_id) {
            $rejectedBill = RejectedBill::find($orderIssue->rejected_bill_id)->first();
            $rejectedBillItems = RejectedBillItem::where('id_rejected_bill', $rejectedBill->id)->get();
            if ($rejectedBillItems) {
                foreach ($rejectedBillItems as $item) {
                    if(!isset($rejectedItems[$item->barcode_goods])){
                        $rejectedItems[$item->barcode_goods]  =0;
                    }
                    $rejectedItems[$item->barcode_goods] = $item->amount + $rejectedItems[$item->barcode_goods] ?? 0;
                }
            }
        } else {
            $orderIssue->update(['rejecting' => '无']);
            $orderIssue->save();
            return;
        }
        if ($orderIssue->order_id) {
            $orderPackageCommodities = $orderPackageCommoditiesService->getOrderPackageCommoditiesByOrderId($orderIssue->order_id);
            if ($orderPackageCommodities) {
                foreach ($orderPackageCommodities as $key => $item) {
                    if (!isset($orderItems[$item->commodity->sku])) {
                        Arr::add($orderItems,$item->commodity->sku,0);
                    }
                    $orderItems[$item->commodity->sku] = $orderItems[$item->commodity->sku] ?? 0 + $item->amount;
                }
            } else {
                $orderIssue->update(['rejecting_status' => '未退回']);
                $orderIssue->save();
                return;
            }
        }

        $rejectedExcess = 0;    // 退回差异
        $rejectedReview = 0;    // 退回复核  $rejectedItems == $orderItems
        foreach ($rejectedItems as $key => $items) {
            if (!isset($orderItems[$key])) {
                $rejectedExcess++;
            } else {
                if ($rejectedItems[$key] == $orderItems[$key]) {
                    $rejectedReview++;
                }
            }
        }
        if ($rejectedExcess > 0) {
            $orderIssue->update(['rejecting_status' => '差异退回']);
            $orderIssue->save();
            return;
        }
        $isExcess = 0; // 超量 $orderItems < $rejectedItems
        $isDiff = 0;   // 部分 $orderItems > $rejectedItems
        $isAccord = 0; // 相同 $orderItems == $rejectedItems
        $isLack = 0;   // 缺少 $orderItems != $rejectedItems
        foreach ($orderItems as $key => $item) {
            if (isset($rejectedItems[$key])) {
                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) {
            $orderIssue->update(['rejecting_status' => '全部退回']);
            $orderIssue->save();
            return;
        } else if ($isDiff > 0 and $isLack >= 0) {
            $orderIssue->update(['rejecting_status' => '部分退回']);
            $orderIssue->save();
            return;
        } else if ($isExcess > 0 and $isDiff == 0) {
            $orderIssue->update(['rejecting_status' => '超量退回']);
            $orderIssue->save();
            return;
        }
    }
}
