<?php

namespace app\common\model;

use app\admin\model\UserRelation;
use fast\Random;
use liuniu\BaseModel;
use think\Db;
use think\Model;
use think\Request;

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

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

    /**
     * 获取个人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']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    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)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($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]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($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]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @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;
    }

    /**
     * 关联用户关系
     * @return \think\model\relation\HasOne
     */
    public function userRelation()
    {
        return $this->hasOne("UserRelation","user_id","id");
    }
    /**
     * 更新用户信息
     * @param $wechatUser 用户信息
     * @param $uid 用户uid
     * @return bool|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function updateWechatUser($wechatUser, $uid)
    {
        $userInfo = self::where('id', $uid)->find();
        if (!$userInfo) return;
        if ($userInfo->spread_uid) {
            return self::where('id',$uid)->update([
                'nickname' => $wechatUser['nickname'] ?: '',
                'avatar' => $wechatUser['headimgurl'] ?: '',
                'login_type' => isset($wechatUser['login_type']) ? $wechatUser['login_type'] : $userInfo->login_type,
            ]);
        } else {
            $data = [
                'nickname' => $wechatUser['nickname'] ?: '',
                'avatar' => $wechatUser['headimgurl'] ?: '',
                'login_type' => isset($wechatUser['login_type']) ? $wechatUser['login_type'] : $userInfo->login_type,
            ];
            return self::where('id',$uid)->update($data);
        }
    }

    /**
     * 设置推广关系
     * @param $spread
     * @param $uid
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function setSpread($spread, $uid)
    {
        //当前用户信息
        $userInfo = self::where('id', $uid)->find();
        if (!$userInfo) return true;
        //当前用户有上级直接返回
        if ($userInfo->spread_uid) return true;
        //没有推广编号直接返回
        if (!$spread) return true;
        if ($spread >= $uid) return true;
        if ($uid == self::where('id', $spread)->value('spread_uid')) return true;

        $data['spread_uid'] = $spread;
        $data['spread_time'] = time();
        return self::where('id',$uid)->update($data);
    }

    /**
     * 小程序用户添加
     * @param $routineUser
     * @param int $spread_uid
     * @return object
     */
    public static function setRoutineUser($routineUser, $spread_uid = 0)
    {
        self::beginTrans();
        $res1 = true;
        if ($spread_uid) $res1 = self::where('id', $spread_uid)->inc('spread_count', 1)->update();
//        $storeBrokerageStatu = sys_config('store_brokerage_statu') ? : 1;//获取后台分销类型
        $salt   = Random::alnum();
        $res2 = self::create([
            'username' => 'rt' .Random::alpha(3).time(),
            'password' => md5(md5(12345678).$salt),
            'salt'     => $salt,
            'nickname' => $routineUser['nickname'] ?: '',
            'avatar' => $routineUser['headimgurl'] ?: '',
            'spread_uid' => $spread_uid,
            'spread_time' => $spread_uid ? time() : 0,
            'jointime' =>time(),
            'joinip' => Request::instance()->ip(),
            'logintime' => time(),
            'loginip' => Request::instance()->ip(),
            'login_type' => $routineUser['login_type'],
            'cid'    => $routineUser['cid'],
            'status' =>'normal',
        ]);
        $routineUser['user_id'] = $res2['id'];
        $routineUser['login_type'] = $routineUser['login_type'];
        UserRelation::create($routineUser);
        $res = $res1 && $res2;
        self::checkTrans($res);
        return $res2;
    }

    /**
     * 小程序创建用户后返回uid
     * @param $routineInfo
     * @return mixed
     */
    public static function routineOauth($routine)
    {
        $routineInfo['nickname'] = filter_emoji($routine['nickName']);//姓名
        $routineInfo['sex'] = $routine['gender'];//性别
        $routineInfo['language'] = $routine['language'];//语言
        $routineInfo['city'] = $routine['city'];//城市
        $routineInfo['province'] = $routine['province'];//省份
        $routineInfo['country'] = $routine['country'];//国家
        $routineInfo['headimgurl'] = $routine['avatarUrl'];//头像
        $routineInfo['routine_openid'] = $routine['openId'];//openid
        $routineInfo['session_key'] = $routine['session_key'];//会话密匙
        $routineInfo['unionid'] = $routine['unionId'];//用户在开放平台的唯一标识符
        $routineInfo['login_type'] = 2;//用户类型
        $routineInfo['cid'] = $routine['cid'];
        $spid = 0;//绑定关系uid
        $isCOde = false;
        //获取是否有扫码进小程序
        if ($routine['code']) {
            $spid = $routine['spid'];
        } else if ($routine['spid'])
            $spid = $routine['spid'];

        //  判断unionid  存在根据unionid判断
        if ($routineInfo['unionid'] != '' && ($uid = UserRelation::where(['unionid' => $routineInfo['unionid']])->where('login_type', '<>', '0')->value('user_id'))) {
            UserRelation::where('user_id',$uid)->update($routineInfo);
            $routineInfo['code'] = $spid;
            $routineInfo['isPromoter'] = $isCOde;
            if ($routine['login_type']) $routineInfo['login_type'] = 3;
            self::updateWechatUser($routineInfo,0);
        } else if ($uid = UserRelation::where(['routine_openid' => $routineInfo['routine_openid']])->where('login_type', '<>', 0)->value('user_id')) { //根据小程序openid判断
            UserRelation::where('user_id',$uid)->update($routineInfo);
            $routineInfo['code'] = $spid;
            $routineInfo['isPromoter'] = $isCOde;
            if ($routine['login_type']) $routineInfo['login_type'] = $routine['login_type'];
            self::updateWechatUser($routineInfo, 0);
        } else {
            $res = self::setRoutineUser($routineInfo, $spid);
            $uid = $res['id'];
        }
        return $uid;
    }

    /**
     * 微信用户增加
     * @param $WechatUser
     * @param int $spread_uid
     */
    public static function setWechatUser($WechatUser, $spread_uid = 0)
    {
        self::beginTrans();
        $res1 = true;
        if ($spread_uid) $res1 = self::where('id', $spread_uid)->inc('spread_count', 1)->update();
        $salt   = Random::alnum();
        $res2 = self::create([
            'username' => 'wx' . Random::alpha(3).time(),
            'password' => md5(md5(12345678).$salt),
            'salt'     => $salt,
            'nickname' => $WechatUser['nickname'] ?: '',
            'avatar' => $WechatUser['headimgurl'] ?: '',
            'spread_uid' => $spread_uid,
            'spread_time' => $spread_uid ? time() : 0,
            'jointime' => time(),
            'joinip' => Request::instance()->ip(),
            'logintime' => time(),
            'loginip' => Request::instance()->ip(),
            'login_type' => $WechatUser['login_type'],
            'status' => 'normal',
            'cid'    => $WechatUser['cid'],
        ]);
        $WechatUser['user_id'] = $res2['id'];
        $WechatUser['login_type'] = $WechatUser['login_type'];
        UserRelation::create($WechatUser);
        $res = $res1 && $res2;
        self::checkTrans($res);
        return $res2;
    }
    public static function getByUsername($cid,$value)
    {
        return self::where('username',$value)->where('cid',$cid)->find();
    }
    public static function getByEmail($cid,$value)
    {
        return self::where('email',$value)->where('cid',$cid)->find();
    }
    public static function getByMobile($cid,$value)
    {
        return self::where('mobile',$value)->where('cid',$cid)->find();
    }
    public static function getByNickname($cid,$value)
    {
        return self::where('nickname',$value)->where('cid',$cid)->find();
    }
    public static function setendtime($user_id,$level_id)
    {
        $level = UserGroup::find($level_id);
        $user = self::find($user_id);
        if($user['vip_forever']==0 && $user['vip_endtime']>time())
        {
            $data['vip_endtime'] = strtotime("+{$level['validity_month']} month",$user['vip_endtime']);
        }
        else
        {
            $data['vip_endtime'] = strtotime("+{$level['validity_month']} month");
        }
        $data['group_id'] = $level_id;
        $data['level'] = $level_id;
        $data['user_type'] = $level['user_type'];
        self::where('id',$user_id)->update($data);
        return true;
    }
}
