<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class TechnicalTitle extends Model
{

    /**
     * 关联到模型的数据表
     *
     * @var string
     */
    protected $table = 'wash_grade_professional';
    protected $primaryKey = 'grpr_id';
    protected $guarded = [];
    /**
     * 可以被批量赋值的属性.
     *
     * @var array
     */
//    protected $fillable = ['grpr_name', 'grpr_remark', 'grpr_state', 'grpr_delete', 'grpr_update_time'];
    public $attributeNames = [
        'grpr_id'=>'编号',
        'grpr_name'=>'级别名称',
        'grpr_remark'=>'备注',
        'grpr_state'=>'状态值',
        'status_name'=>'状态',
        'grpr_delete'=>'是否删除',
        'grpr_create_time'=>'创建时间',
        'grpr_update_time'=>'更新时间'
    ];
    /**
     * 表明模型是否应该被打上时间戳
     *
     * @var bool
     */
    public $timestamps = true;
    /**
     * 模型日期列的存储格式
     *
     * @var string
     */
    //protected $dateFormat = 'U';

    /**
     * The connection name for the models.
     *
     * @var integer $id
     * @var bool $includeSub
     *
     * @return mixed
     */
    //protected $connection = 'connection-name';
    const CREATED_AT = 'grpr_create_time';
    const UPDATED_AT = 'grpr_update_time';

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('grpr_delete',function (Builder $builder){
            $builder->where('grpr_delete','=',1);
        });
    }


    public function levels() {
        return $this->hasMany('App\Models\TechnicalLevel', 'grle_grpr_id', 'grpr_id')->state(1);
    }

    public function scopeName($query, $name) {
        return $query->where('grpr_name', 'like', '%' . $name . '%');
    }

    public function scopeDelete($query, $delete = 1) {
        return $query->where('grpr_delete', $delete);
    }

    public function getStatusNameAttribute()
    {
        if ($this->getAttribute('grpr_state') == 1) return '启用';
        if ($this->getAttribute('grpr_state') == 2) return '停用';

        return '未知';
    }

    public function getDeleteNameAttribute()
    {
        if ($this->getAttribute('grpr_delete') == 1) return '正常';
        if ($this->getAttribute('grpr_delete') == 2) return '已删除';

        return '未知';
    }

    public function getCreateTimeAttribute()
    {
        $create_time = $this->getAttribute('grpr_create_time');
        $dotExist = strpos($create_time, '.');
        if ($dotExist !== false)
        {
            $dateTime = explode('.', $create_time);

            return $dateTime[0];
        }

        return null;
    }

    public function getUpdateTimeAttribute()
    {
        $update_time = $this->getAttribute('grle_update_time');
        $dotExist = strpos($update_time, '.');
        if ($dotExist !== false)
        {
            $dateTime = explode('.', $update_time);

            return $dateTime[0];
        }

        return null;
    }

}
