<?php

namespace App;

use App\Traits\ModelTimeFormat;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;

use App\Traits\ModelLogChanging;

class InventoryAccount extends Model
{
    use ModelLogChanging;

    use ModelTimeFormat;
    use SoftDeletes;
    protected $fillable=[
        'id','owner_id','type', 'start_at', 'end_at','total','processed','difference','returned','deleted_at','created_at','status','remark','auditor','ignored'
    ];
    protected $appends = [
            'surplus','check_surplus'
    ];
    public function creator(){
        return $this->hasOne('App\Sign','signable_id','id')
            ->where('signable_type','inventory_accounts')->where('field','创建人');
    }
    public function owner(){
        return $this->belongsTo('App\Owner','owner_id','id');
    }
    public function userAuditor(){
        return $this->belongsTo('App\User','auditor','id');
    }
    public function inventoryMissions(){
        return $this->belongsTo('App\InventoryAccountMission','id','inventory_account_id');
    }

    public function getSurplusAttribute()
    {
        return $this['total'] ? $this['total']-($this['processed']+$this['ignored']):0;
    }
    public function getProcessedAmount(){
        return $this->inventoryMissions()->whereIn('checked',['是','确认差异','已复核'])->where('inventory_account_id',$this['id'])->count();
    }
    public function getIgnoredAmount(){
        return $this->inventoryMissions()->where('checked','跳过')->where('inventory_account_id',$this['id'])->count();
    }
    //复盘剩余数
    public function getCheckSurplusAttribute()
    {
        $re_checked_amount=$this->inventoryMissions()->where('inventory_account_id',$this['id'])->whereNotNull('re_checked_amount')->count();
        return $this['total'] ? $this['total']-$re_checked_amount:null;
    }
    public function getDifferenceAmount(){
        return $this->inventoryMissions()->where('inventory_account_id',$this['id'])->where('difference_amount','!=',0)->count();
    }
    //复盘归位
    public function getReturnedAmount(){
        return $this->inventoryMissions()->where('inventory_account_id',$this['id'])->where('returned','是')->count();

    }
    public function createSignCreator(){
        return Sign::query()->create([
            'signable_type'=>'inventory_accounts',
            'signable_id'=>$this['id'],
            'field'=>'创建人',
            'mark'=>Auth::user()['name'],
        ]);
    }
}
