<?php

namespace App;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

/**
 * @method static orderBy(string $string, string $string1)
 */
use App\Traits\ModelTimeFormat;

use App\Traits\ModelLogChanging;
use Illuminate\Support\Facades\DB;

class Owner extends Model
{
    use ModelLogChanging;

    use ModelTimeFormat;
    public $fillable = [
        'name',                 //名称
        'code',                 //代码
        'checking_count',       //审核数量
        'deleted_at',           //删除时间
        "customer_id",          //客户ID
        "tax_rate_id",          //税率
        "linkman",              //联系人
        "phone_number",         //联系电话
        "user_owner_group_id",  //项目组ID
        "waring_line_on",       //月单量预警
        "description",          //描述
        "warehouse_id",         //仓库ID
        "user_workgroup_id",    //仓库小组(工作组)
        "relevance",            //关联模型的JSON数组
        'subjection',           //主体公司
        'is_tax_exist'          //是否必填税率
    ];
    //relevance说明 0：仓储 1：作业 2：快递 3：物流 4：直发 5:系统 存储示例：["0","1"]存在仓储与作业计费
    protected $casts = [
        "relevance" => "array"
    ];
    const subjection=[
        0=>'',
        1 => "宝时物流",
        2 => "宝时供应链",
    ];

    public static function filterAuthorities(){
        $user=Auth::user();
        $query = (new static)->newQuery();
        if(!$user){
            return $query->where('id','0');
        }
        $ownerIds=app('UserService')->getPermittingOwnerIds($user);
        if(empty($ownerIds))return $query;
        return $query->whereIn('id',$ownerIds);
    }

    /**
     * 退货管理里，客户审核的代码，是拼音+日期+计数，计数的后缀就是checking_count
     * @return int|mixed
     */
    public function getIncreasedCheckingCount(){
        $this['checking_count']=$this['checking_count']+1;
        $this->update();
        return $this['checking_count'];
    }

    public function paperBoxes()
    {
        return $this->belongsToMany('\App\PaperBox', 'owner_paper_box', 'owner_id', 'paper_box_id');
    }

    public function orderTrackingOwner(){
        return $this->belongsTo(OrderTrackingOwner::class,'id','owner_id');
    }

    public function contracts()
    {   //合同
        return $this->hasMany(OwnerContract::class,"owner_id","id");
    }

    public function order(){
        return $this->hasOne(Order::class,'owner_id','id');
    }
    public function customer()
    {   //客户
        return $this->hasOne(Customer::class,"id","customer_id");
    }
    public function userOwnerGroup()
    {   //项目组
        return $this->hasOne(UserOwnerGroup::class,"id","user_owner_group_id");
    }
    public function userWorkGroup()
    {   //工作组
        return $this->belongsTo(UserWorkgroup::class,"user_workgroup_id","id");
    }
    public function ownerAreaReport()
    {   //面积报表
        return $this->hasOne(OwnerAreaReport::class,"owner_id","id");
    }
    public function ownerStoragePriceModels()
    {   //仓储计费
        $query = OwnerStoragePriceModel::query()->select("target_id")
            ->whereNotNull("operation")->where("operation","!=","")
            ->whereNotNull("target_id")->where("target_id","!=","");
        return $this->belongsToMany(OwnerStoragePriceModel::class,"owner_storage_price_model_owner","owner_id","owner_storage_price_model_id")
            ->whereNotIn("id",$query)->where(function(Builder $query){
                $query->where("operation","!=","D")->orWhereNull("operation");
            });
    }
    public function ownerPriceOperations()
    {   //作业计费
        $query = OwnerPriceOperation::query()->select("target_id")
            ->whereNotNull("operation")->where("operation","!=","")
            ->whereNotNull("target_id")->where("target_id","!=","");
        return $this->belongsToMany(OwnerPriceOperation::class,"owner_price_operation_owner","owner_id","owner_price_operation_id")
            ->whereNotIn("id",$query)->where(function(Builder $query){
                $query->where("operation","!=","D")->orWhereNull("operation");
            });
    }
    public function ownerPriceExpresses()
    {   //快递计费
        $query = OwnerPriceExpress::query()->select("target_id")
            ->whereNotNull("operation")->where("operation","!=","")
            ->whereNotNull("target_id")->where("target_id","!=","");
        return $this->belongsToMany(OwnerPriceExpress::class,"owner_price_express_owner","owner_id","owner_price_express_id")
            ->whereNotIn("id",$query)->where(function(Builder $query){
                $query->where("operation","!=","D")->orWhereNull("operation");
            });
    }
    public function ownerPriceLogistics()
    {   //物流计费
        $query = OwnerPriceLogistic::query()->select("target_id")
            ->whereNotNull("operation")->where("operation","!=","")
            ->whereNotNull("target_id")->where("target_id","!=","");
        return $this->belongsToMany(OwnerPriceLogistic::class,"owner_price_logistic_owner","owner_id","owner_price_logistic_id")
            ->whereNotIn("id",$query)->where(function(Builder $query){
                $query->where("operation","!=","D")->orWhereNull("operation");
            });
    }
    public function ownerPriceDirectLogistics()
    {   //直发车计费
        $query = OwnerPriceDirectLogistic::query()->select("target_id")
            ->whereNotNull("operation")->where("operation","!=","")
            ->whereNotNull("target_id")->where("target_id","!=","");
        return $this->belongsToMany(OwnerPriceDirectLogistic::class,"owner_price_direct_logistic_owner","owner_id","owner_price_direct_logistic_id")
            ->whereNotIn("id",$query)->where(function(Builder $query){
                $query->where("operation","!=","D")->orWhereNull("operation");
            });
    }
    public function ownerPriceSystem()
    {   //系统计费
        $query = OwnerPriceSystem::query()->select("target_id")
            ->whereNotNull("operation")->where("operation","!=","")
            ->whereNotNull("target_id")->where("target_id","!=","");
        return $this->hasOne(OwnerPriceSystem::class,"owner_id","id")
            ->whereNotIn("id",$query)->where(function(Builder $query){
                $query->where("operation","!=","D")->orWhereNull("operation");
            });
    }
    public function warehouse()
    {   //仓库
        return $this->belongsTo(Warehouse::class,"warehouse_id","id");
    }
    public function ownerMaterials()
    {   //耗材
        return $this->hasMany(OwnerMaterial::class,"owner_id","id");
    }
    public function taxRate()
    {   //税率
        return $this->belongsTo(TaxRate::class);
    }
    public function storageAudit()
    {   //审核的仓储模型
        return $this->belongsToMany(OwnerStoragePriceModel::class,"owner_storage_price_model_owner")
            ->select(DB::raw(1))->whereNotNull("operation")
            ->where("operation","!=","")->groupBy("owner_id");
    }
    public function operationAudit()
    {   //审核的作业模型
        return $this->belongsToMany(OwnerPriceOperation::class,"owner_price_operation_owner")
            ->select(DB::raw(1))->whereNotNull("operation")
            ->where("operation","!=","")->groupBy("owner_id");
    }
    public function expressAudit()
    {   //审核的快递模型
        return $this->belongsToMany(OwnerPriceExpress::class,"owner_price_express_owner")
            ->select(DB::raw(1))->whereNotNull("operation")
            ->where("operation","!=","")->groupBy("owner_id");
    }
    public function logisticAudit()
    {   //审核的物流模型
        return $this->belongsToMany(OwnerPriceLogistic::class,"owner_price_logistic_owner")
            ->select(DB::raw(1))->whereNotNull("operation")
            ->where("operation","!=","")->groupBy("owner_id");
    }
    public function directLogisticAudit()
    {   //审核的直发模型
        return $this->belongsToMany(OwnerPriceDirectLogistic::class,"owner_price_direct_logistic_owner")
            ->select(DB::raw(1))->whereNotNull("operation")
            ->where("operation","!=","")->groupBy("owner_id");
    }
    public function systemAudit()
    {   //审核的直发模型
        return $this->hasOne(OwnerPriceSystem::class,"owner_id","id")
            ->select(DB::raw(1))->whereNotNull("operation")
            ->where("operation","!=","");
    }
}
