<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

use App\Traits\ModelLogChanging;

class OwnerPriceLogistic extends Model
{
    use ModelLogChanging;

    protected $fillable = [
        "name",             //名称
        "unit_range",       //单价一区间
        "unit_id",          //单位一ID
        "other_unit_range", //单位二区间
        "other_unit_id",    //单位二ID
        "pick_up_price",    //提货费
        "fuel_price",       //燃油附加费
        "service_price",    //信息服务费
        "operation",        //操作
        "target_id",        //目标ID
        "tax_rate_id",      //税率
    ];

    public function getUnitRangeJsonAttribute()
    {
        return json_encode(explode(",",$this->unit_range));
    }
    public function getOtherUnitRangeJsonAttribute()
    {
        return json_encode(explode(",",$this->other_unit_range));
    }

    public function details()
    {
        return $this->hasMany(OwnerPriceLogisticDetail::class,"owner_price_logistic_id","id");
    }
    public function unit()
    {   //单位一
        return $this->hasOne(Unit::class,"id","unit_id");
    }
    public function otherUnit()
    {   //单位二
        return $this->hasOne(Unit::class,"id","other_unit_id");
    }
    public function owners()
    {   //货主
        return $this->belongsToMany(Owner::class,"owner_price_logistic_owner","owner_price_logistic_id","owner_id");
    }
    public function logistics()
    {   //物流
        return $this->belongsToMany(Logistic::class,"owner_price_logistic_logistic","owner_price_logistic_id","logistic_id");
    }
    public function taxRate()
    {   //税率
        return $this->belongsTo(TaxRate::class);
    }

    public function getOwnerIdAttribute()
    {   //获取货主ID数组
        return array_column(DB::select(DB::raw("SELECT * FROM owner_price_logistic_owner WHERE owner_price_logistic_id = ?"),[$this->id]),"owner_id");
    }

    public function getLogisticIdAttribute()
    {   //获取快递ID数组
        return array_column(DB::select(DB::raw("SELECT * FROM owner_price_logistic_logistic WHERE owner_price_logistic_id = ?"),[$this->id]),"logistic_id");
    }
}
