<?php

namespace app\common\model;

use app\admin\controller\general\Profile;
use app\admin\model\TtCode;
use think\Db;
use think\Model;
/**
 * 会员模型
 */
class User extends Model
{

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

    const NEW_REWARD = 500; //拉新奖励

    const STATUS_TRUE = 'normal';//用户状态正常
    const STATUS_FALSE = 'hidden'; //用户状态禁用

    const TYPE_TT = 2;//陶特分销
    const TYPE_YNS = 1;//陶特易农社

    /**
     * 获取个人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)
    {
        $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 $money 金额
     * @param $user_id 用户ID
     * @param $memo 注释
     * @throws \think\exception\DbException
     */
    public static function subMoney($money,$user_id,$memo)
    {
        $user = self::get($user_id);
        if ($user && $money != 0) {
            $before = $user->money;
            $after = function_exists('bcsub') ? bcsub($user->money, $money, 2) : $user->user - $money;
            if($after < 0) return false;
            //更新会员信息
            $user->save(['money' => $after]);
            //写入日志
            MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            return true;
        }
    }

    /**
     * 变更冻结金额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function frozen($money, $user_id,$type)
    {
        $user = self::get($user_id);
        if ($user && $money != 0) {
            if($type == 1){
                //增加冻结金额
                $after = function_exists('bcadd') ? bcadd($user->frozen, $money, 2) : $user->frozen + $money;
                $user->save(['frozen' => $after]);
                return True;
            }else{
                //减少冻结金额
                $after = function_exists('bcsub') ? bcsub($user->frozen, $money, 2) : $user->frozen - $money;
                if($after < 0)return false;
                $user->save(['frozen' => $after]);
                return true;
            }

        }
    }


    /**
     * 检测用户名是否存在
     * @param $username
     */
    public static function getByUsername($username)
    {
        return self::where('username',$username)->where('status',self::STATUS_TRUE)->find();
    }

    /**
     * 检测昵称是否存在
     * @param $nickname
     */
    public static function getByNickname($nickname)
    {
        return self::where('nickname',$nickname)->where('status',self::STATUS_TRUE)->find();
    }

    /**
     * 检测邮箱是否存在
     * @param $nickname
     */
    public static function getByEmail($email)
    {
        return self::where('email',$email)->where('status',self::STATUS_TRUE)->find();
    }

    /**
     * 检测手机号是否存在
     * @param $mobile
     */
    public static function getByMobile($mobile)
    {
        return self::where('mobile',$mobile)->where('status',self::STATUS_TRUE)->find();
    }

    /**
     * 扣除金额，解除上级冻结金额
     * @throws \think\exception\DbException
     */
    public static function depositChange($user_id)
    {
        $info = self::get($user_id);
        Db::startTrans();
        //获取创建30天后的时间戳
        try{
            $nextMonth = $info->createtime + 86400 * 30;
            //判断是否交了押金
            if($info->is_deposit == 1) ['code'=>1];
            if($info->money >= self::NEW_REWARD){
                //扣除用户余额
                self::subMoney(self::NEW_REWARD,$user_id,'扣除服务费');
                //解除上级冻结金额
                self::frozen(self::NEW_REWARD,$info->parent_id,2);
                //返还上级冻结金额
                self::money(self::NEW_REWARD,$info->parent_id,'返回冻结金额');
                //记录已交押金
                self::where('id',$user_id)->update(['is_deposit'=>1]);
                Db::commit();
                return ['code'=>1];
            }else if($nextMonth < time()){
                //禁用账户
                self::where('id',$user_id)->update(['status'=>self::STATUS_FALSE]);
                //恢复站长码
                TtCode::where('user_id',$user_id)->update(['status'=>0,'user_id'=>self::STATUS_FALSE]);
                //将最后余额返还上级
                self::money($info->money,$info->parent_id,'返回冻结金额');
                //根据用户余额 解除上级冻结金额
                self::frozen($info->money,$info->parent_id,2);
                //清空用户余额
                self::where('id',$user_id)->update(['money'=>0]);
                Db::commit();
                return ['code'=>2];
            }else{
                return ['code'=>1];
            }

        }catch (\Exception $e){
            dump($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    /**
     * 检测账户是否可以晋升 (缺少条件 ：订单判断)
     * @param $user_id
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public static function testGroup($user_id)
    {
        $info = self::get($user_id);
        switch ($info['group_id']){
            case 3:
                $count = self::where('parent_id',$user_id)->where('status',self::STATUS_TRUE)->where('group_id',3)->count();
                if($count >= 5){
                    $group_id = 2;
                }
                break;
            case 2:
                $count = self::where('parent_id',$user_id)->where('status',self::STATUS_TRUE)->where('group_id',2)->count();
                if($count >= 5){
                    $group_id = 1;
                }
                break;
        }
    }


    /*
     * 三级分销
     * @param int    $money   金额
     * @param int    $user_id 用户
     */
    public static function distribution($money, $user_id)
    {   
        // 查询用户信息
        $user = self::get($user_id);
        if(!$user){
            return ['code'=>0];
        }
        // 查询三级分销比例
        $distribution = TtDistribution::where('id',1)->find();
        // 计算分销金额
        $distribution_money = $money * ($distribution['primary_distribution']/100 + $distribution['secondary_distribution']/100 +$distribution['third_distribution']/100);
        // 计算现有余额扣除分销金额
        $now_money = $user->money + ($money - $distribution_money);
        // 更新用户的余额
        $user_money = self::where('id',$user_id)->update(['money' => $now_money])
        // 一级分销开始
        if($user->parent_id != 0){
            // 查询我的直属上级
            $first_level = self::where('id',$user->parent_id)->find();
            // 计算直属上级的余额加上分销的金额
            $first_distribution = $money * ($distribution['primary_distribution']/100) + $first_level['money'];
            // 更新直属上级的余额
            $first_user_money = self::where('id',$first_level['id'])->update(['money' => $first_distribution]);
            // 写入余额变动日志
            if($first_user_money){
                MoneyLog::create(['user_id' => $first_level['id'], 'money' => $money * ($distribution['primary_distribution']/100), 'before' => $first_level['money'], 'after' => $first_user_money, 'memo' => '直属上级获得佣金']);
            }
            //二级分销开始
            if($first_level['parent_id'] != 0){
                // 查询我上级的上级
                $second_level = self::where('id',$first_level['parent_id'])->find();
                // 计算二级上级的余额加上分销的金额
                $second_distribution = $money * ($distribution['secondary_distribution']/100) + $second_level['money'];
                // 更新二级上级的余额
                $second_user_money = self::where('id',$second_level['id'])->update(['money' => $second_distribution]);
                // 写入余额变动日志
                if($second_user_money){
                    MoneyLog::create(['user_id' => $second_level['id'], 'money' => $money * ($distribution['secondary_distribution']/100), 'before' => $second_level['money'], 'after' => $second_user_money, 'memo' => '二级上级获得佣金']);
                }
                //三级分销开始
                if($second_level['parent_id'] != 0){
                    // 查询我上级的上级的上级
                    $third_level = self::where('id',$second_level['parent_id'])->find();
                    // 计算三级上级的余额加上分销的金额
                    $third_distribution = $money * ($distribution['third_distribution']/100) + $third_level['money'];
                    // 更新三级上级的余额
                    $third_user_money = self::where('id',$third_level['id'])->update(['money' => $third_distribution]);
                    // 写入余额变动日志
                    if($third_user_money){
                        MoneyLog::create(['user_id' => $third_level['id'], 'money' => $money * ($distribution['third_distribution']/100), 'before' => $third_level['money'], 'after' => $third_user_money, 'memo' => '三级上级获得佣金']);
                    }
                }
                //三级分销技术
            }
            //二级分销结束
        }
        //一级分销结束
        if($user_money){
            // 写入余额变动日志
            MoneyLog::create(['user_id' => $user_id, 'money' => $money - $distribution_money, 'before' => $user->money, 'after' => $now_money, 'memo' => '分销获得佣金']);
            return true;
        } else {
            return false;
        }
    }
}
