<?php
/**
 * +------------------------------------------------------------
 * | 用户 模型
 * +------------------------------------------------------------
 * | @author: bsh (844783437@qq.com)
 * | @create_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @copyright: CIM信息聚合系统 (https://cimxx.com)
 * +------------------------------------------------------------
 * | @last_modified_by: bsh
 * | @last_modified_time: 2018-04-28 19:14:25
 * +------------------------------------------------------------
 * | @todo:
 * +------------------------------------------------------------
 */

namespace app\user\model;

use think\Model;
use app\user\model\Group;
use app\user\model\Log;

class User extends Model
{
    private static $group = [];

    protected $pk = 'id';

    protected $name = 'user';

    // 设置json类型字段
    protected $json = ['fields'];

    // 设置JSON数据返回数组
    protected $jsonAssoc = true;

    protected $append = ['avatar', 'group_name', 'show_email', 'show_phone'];

    protected static function init()
    {
        self::$group = action('user/api/group');
    }

    public function getAvatarAttr($value, $data)
    {
        return action('user/api/avatar', ['id' => $data['id']]);
    }

    public function register()
    {
        return $this->hasOne('app\user\model\Log', 'user_id', 'id')->where('action', '=', 'register')->field('user_id,ip,os,browser,event,memo,create_time');
    }

    function getLoginAttr($value, $data)
    {
        return model('app\user\model\Log')->where('user_id', '=', $data['id'])->where('action', '=', 'login')->order('id desc')->find();
    }

    public function getShowPhoneAttr($value, $data)
    {
        return empty($data['phone']) ? '' : substr_replace($data['phone'], '****', 3, 4);
    }

    public function getShowEmailAttr($value, $data)
    {
        return empty($data['email']) ? '' : substr_replace($data['email'], '****', 3, 4);
    }

    function getGroupNameAttr($value, $data)
    {
        if (!isset($data['group_id'])) return;
        return self::$group[$data['group_id']]['name'];
    }

}
