<?php

namespace app\admin\model;

use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use fast\Random;
use liuniu\BaseModel;
use think\Request;

class User extends BaseModel
{

    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'prevtime_text',
        'logintime_text',
        'jointime_text'
    ];

    public function getOriginData()
    {

        return $this->origin;
    }

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            //如果有修改密码
            if (isset($changed['password'])) {
                if ($changed['password']) {
                    $salt = \fast\Random::alnum();
                    $row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
                    $row->salt = $salt;
                } else {
                    unset($row->password);
                }
            }
        });


        self::beforeUpdate(function ($row) {
            $changedata = $row->getChangedData();
            $origin = $row->getOriginData();
            if (isset($changedata['money']) && (function_exists('bccomp') ? bccomp($changedata['money'], $origin['money'], 2) !== 0 : (double) $changedata['money'] !== (double) $origin['money'])) {
                MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
            }
            if (isset($changedata['score']) && (int) $changedata['score'] !== (int) $origin['score']) {
                ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
            }
        });
    }

    public function getGenderList()
    {
        return ['1' => __('Male'), '0' => __('Female')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }

    public function getPrevtimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['prevtime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['logintime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getJointimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['jointime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPrevtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setBirthdayAttr($value)
    {
        return $value ? $value : null;
    }

    public function group()
    {
        return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    /**
     * 更新用户信息
     * @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,
                'spread_uid' => 0,
                'spread_time' => 0,
            ];
            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(),
            'user_type' => $routineUser['user_type']
        ]);
        $res = $res1 && $res2;
        self::checkTrans($res);
        return $res2;
    }

    /**
     * 微信用户增加
     * @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',
        ]);
        $WechatUser['user_id'] = $res2['id'];
        $WechatUser['user_type'] = $WechatUser['login_type'];
        unset( $WechatUser['login_type']);
        UserRelation::create($WechatUser);
        $res = $res1 && $res2;
        self::checkTrans($res);
        return $res2;
    }



}
