<?php

namespace app\common\model;

use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
        'authlist_array',
        'is_ok_arr',
        'user_chirography_array',
        'user_label_array',
        'user_chirography_ids_array',
        'user_label_ids_array',
        'attention_num'
    ];

    protected $hidden = [
        'group_id','level','bio','money','score','successions',
        'maxsuccessions','prevtime','logintime','loginip','loginfailure',
        'joinip','jointime','password','salt','email','token','status','verification'
    ];


    /**
     * 获取可以显示隐藏的字段
     * @param   string $value
     * @param   array  $data
     * @return string
     */
    public function getIsOkArrAttr($value, $data)
    {
       return ['username','gender','birthday','guan','address','mobile','occupation'];
    }


    /**
     * 获取关注我的用户数量
     */
    public function getAttentionNumAttr($value,$data){
        return \model('user_attention')->where('in_user_id',$data['id'])->count();
    }



    public function getUserChirographyArrayAttr($value, $data){
        if (!$data['user_chirography_ids']){
            return [];
        }
        $data = explode(',',$data['user_chirography_ids']);
        $res = [];
        foreach ($data as $val){
            $user_chirography = \model('user_chirography')->where('id',$val)->find();
            if ($user_chirography){
                $res[] = $user_chirography['name'];
            }
        }
        return $res;
    }

    public function getUserLabelArrayAttr($value, $data){
        if (!$data['user_label_ids']){
            return [];
        }
        $data = explode(',',$data['user_label_ids']);
        $res = [];
        foreach ($data as $val){
            $user_label = \model('user_label')->where('id',$val)->find();
            if ($user_label){
                $res[] = $user_label['name'];
            }
        }
        return $res;
    }




    public function getUserChirographyIdsArrayAttr($value, $data){
        if (!$data['user_chirography_ids']){
            return [];
        }
        return explode(',',$data['user_chirography_ids']);
    }

    public function getUserLabelIdsArrayAttr($value, $data){
        if (!$data['user_label_ids']){
            return [];
        }
        return explode(',',$data['user_label_ids']);
    }

    /**
     * 获取个人URL
     * @param   string $value
     * @param   array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param   string $value
     * @param   array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像,请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        if ($data['avatar'] != '' && !in_array(substr($data['avatar'],-4),explode(',','jpg,png,bmp,jpeg,gif,zip,rar,xls,xlsx'))){
            $content = file_get_contents($data['avatar']);
            file_put_contents(ROOT_PATH.'/public/uploads/user_avatar/user_id_'.$data['id'].'.jpg', $content);
            model('user')->where('id',$data['id'])->update(['avatar'=>'/uploads/user_avatar/user_id_'.$data['id'].'.jpg']);
            $data['avatar'] = '/uploads/user_avatar/user_id_'.$data['id'].'.jpg';
        }
        if (file_exists(cdnurl($value,true))){
            return cdnurl($value,true);
        }
        if (file_exists(ROOT_PATH.$value)){
            return  this_url().$value;
        }
        return this_url()."/uploads/user_avatar/001.jpg";
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param   string $value
     * @param   array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user && $money != 0) {
            $before = $user->money;
            //$after = $user->money + $money;
            $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
            //更新会员信息
            $user->save(['money' => $after]);
            //写入日志
            MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user && $score != 0) {
            $before = $user->score;
            $after = $user->score + $score;
            $level = self::nextlevel($after);
            //更新会员信息
            $user->save(['score' => $after, 'level' => $level]);
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }


    /**
     * 查询用户身份
     * @param $value 当前数据
     * @param $data 所有数据
     * @return int
     */
    public static function getAuthlistArrayAttr($value,$data)
    {
        $data_arr = explode(',',$data['authlist']);
        $re = [];
        if ($data['is_expert'] == 1){
            $re[] = '专家';
        }
        if ($data_arr){
            if (in_array('1',$data_arr)){
                $re[] = '书友';
            }
            if (in_array('2',$data_arr)){
                $re[] = '书协';
            }
            if (in_array('3',$data_arr)){
                $re[] = '书协';
            }
            if (in_array('4',$data_arr)){
                $re[] = '企业';
            }
        }
        return $re;
    }
}