<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

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

    // 开启自动写入时间戳字段
    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;
    }

    /**
     * 增加佣金和流水
     * @param $commission 佣金
     * @param int $user_id 用户ID
     * @return bool
     */
    public function userAddMoney($commission,int $user_id,$detail){
        //开启事务
        Db::startTrans();
        try {
            $user_info = self::where('id',$user_id)->find();

            $before = $user_info['money'];
            $money = bcadd((string)$before,(string)$commission,2);
            $upd = self::where('id',$user_id)->update(['money'=>$money]);
            if($upd){
                //填加佣金成功 增加余额流水记录
                $is_log = setUserMoneyLog($user_id,$before,$commission,$money,1,$detail);
                if($is_log == 1){
                    Db::commit();
                    return true;
                }else{
                    Db::rollback();
                    return false;
                }
            }else{
                Db::rollback();
                return false;
            }
        } catch (Exception $e){
            Db::rollback();
            return false;
        }
    }

    /**
     * 添加提现记录
     * @param int $user_id 用户ID
     * @param numeric $money  提现金额
     * @param $out_trade_no 交易凭证|暂定
     * @return void
     */
    public function add(int $user_id,$money,$out_trade_no){
        //开启事务
        Db::startTrans();
        try {

            $data['withdraw_sn'] = getOrderSn('T');
            $data['user_id'] = $user_id;
            $data['money'] = $money;
            $data['out_trade_no'] = $out_trade_no;
            $data['remark'] = "用户申请提现";
            $data['createtime'] = time();

            $add = Db::name("unishop_withdraw")->insert($data);
            if($add){

                //减少用户余额
                $user_money = self::where("id",$user_id)->value("money");
                $upd_money = bcsub((string)$user_money,(string)$money,2);
                $upd = self::where("id",$user_id)->update(['money'=>$upd_money]);
                if($upd){
                    $points_log = setUserMoneyLog($user_id,$user_money,$money,$upd_money,2,"用户申请提现");
                    if($points_log == 1){
                        Db::commit();
                        return true;
                    }else{
                        Db::rollback();
                        return false;
                    }
                }else{
                    Db::rollback();
//                    Logs('批发商品ID为:'.$value['id'].'减少用户余额失败','User_withdraw');
                    return false;
                }

            }else{

                Db::rollback();
                return false;
            }


        } catch (Exception $e){

            Db::rollback();
            return false;
        }

    }
}
