<?php

namespace addons\webman\model;
use addons\webman\traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Class AdminUser
 * @property int id 主键
 * @property string username 用户账号
 * @property string password 密码
 * @property string nickname 姓名
 * @property string avatar 头像
 * @property string email 邮箱
 * @property string phone 手机号
 * @property int status 状态(0:禁用,1:启用)
 * @property int type 1 部门 2渠道
 * @property string remember_token 排序
 * @property int department_id 部门
 * @property int is_super 是否渠道超管
 * @property int post 岗位
 * @property string deleted_at 删除时间
 * @property string created_at 创建时间
 * @property string updated_at 最后一次修改时间
 *
 * @property AdminDepartment department 部门/渠道
 * @package addons\webman\model
 */
class AdminUser extends Model
{
    protected $casts = ['post'=>'array'];
    protected $fillable = ['username', 'password', 'nickname', 'avatar'];

    use SoftDeletes, HasDateTimeFormatter;

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->setTable(plugin()->webman->config('database.user_table'));
    }

    /**
     * 角色
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles(){
        return $this->belongsToMany(plugin()->webman->config('database.role_model'),plugin()->webman->config('database.role_user_model'), 'user_id', 'role_id');
    }

    /**
     * 部门
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function department(){
        return $this->belongsTo(plugin()->webman->config('database.department_model'), 'department_id');
    }

    /**
     * 功能
     * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
     */
    public function permission()
    {
        return $this->hasManyThrough(plugin()->webman->config('database.role_permission_model'), plugin()->webman->config('database.role_user_model'), 'user_id', 'role_id','id','role_id');
    }

    /**
     * 密码哈希加密
     * @param $value
     */
    public function setPasswordAttribute($value){
        $this->attributes['password'] = password_hash($value,PASSWORD_DEFAULT);
    }
}
