<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\api\controller\user;

use app\api\controller\Base;
use think\Db;
use think\Validate;
use think\Session;


class User extends Base
{
    protected $noNeedLogin = ['password/s','getPhoneNumber','login','info','register','wxappLogin','gzhLogin','getWxappOpenid','mobileAuthLogin'];
    protected $noNeedRight = ['*'];
    
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\User;
    }

    public function logout()
    {
        if(Session::has('uToken')){
            Session::delete('uToken');  
        }
        $this->auth->logout();
        __success('退出成功');
    }

    public function huifubafangAuth(){
        $huifubafang = new \app\common\model\bbfxshop\Huifubafang();
        $result = $huifubafang->getOauthConfig($this->user['id']);
        __result($result);
    }
    
    public function addShareLog(){
        $type = $this->param("type/d");
        $result = $this->model->addShareLog($this->user['id'],$type);
        __result($result);
    }

    public function password(){
        $params = $this->param([
            'mobile/s',
            'password/s',
            'repassword/s',
            'code/s'
        ]);

        if(empty($params['mobile'])){
            __error("请输入手机号");
        }
        if(empty($params['password'])){
            __error("请输入新密码");
        }
        if(empty($params['repassword'])){
            __error("请确认新密码");
        }
        if($params['password'] != $params['repassword']){
            __error("两次密码不一致");
        }
        if(mb_strlen($params['password'], 'UTF-8') < 6){
            __error("登录密码长度不足");
        }
        if(empty($params['code'])){
            __error("请输入验证码");
        }

        $user = $this->user;
        if(!empty($user)){
            if(empty($user['mobile'])){
                __error("请先绑定手机号");
            }
            if($user['mobile'] != $params['mobile']){
                __error("当前账号绑定手机号与输入手机号不匹配");
            }
        }
        else{
            $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$params['mobile']])->find();
            if(empty($user)){
                __error("手机号未注册");
            }
        } 

        $result = \app\common\model\bbfxshop\Sms::checkVerifcode($params['mobile'],$params['code'],"password");
        if($result['code'] !== 1){
            __error($result['message']);
        }

        $password = $params['password'];
        $salt = random(8);
        $password = md5(md5($password).$salt);
        $data = [];
        $data['salt'] = $salt;
        $data['password'] = $password;
        $data['loginfailure'] = 0;
        
        Db::name("bbfx_user")->where(['id'=>$user['id']])->update($data);

        __success("密码重置成功");
    }

    public function update(){
        global $_W;
        $params = $this->param([
            'type/d',
            'nickname/s',
            'avatar/s',
            'skqrcode/s',
            'bank_realname/s',
            'bankname/s',
            'bankcard/s',
            'bankopen/s',
            'zfb_realname/s',
            'zfb/s',
            'pay_password/s',
            'old_password/s',
            'password/s',
            'repassword/s',
            'mobile/s',
            'code/s',
            'weixin/s'
        ]);
        $platform = $this->paramGet('platform/s');
        $data = [];
        if($params['type'] == 1){
            if(empty($params['nickname'])){
                __error("请输入昵称");
            }
            $data['nickname'] = $params['nickname'];
        }
        else if($params['type'] == 2){
            if(empty($params['avatar'])){
                __error("请上传头像");
            }
            $data['avatar'] = replaceSiteroot($params['avatar']);
        }
        else if($params['type'] == 3){
            if(empty($params['skqrcode'])){
                __error("请上传收款码");
            }
            $data['skqrcode'] = replaceSiteroot($params['skqrcode']);
        }
        else if($params['type'] == 5){
            
            $data = array(
                'zfb_realname'=>$params['zfb_realname'],
                'zfb'=>$params['zfb'],
                'bank_realname'=>$params['bank_realname'],
                'bankname'=>$params['bankname'],
                'bankcard'=>$params['bankcard'],
                'bankopen'=>$params['bankopen'],
                'skqrcode'=>replaceSiteroot($params['skqrcode']),
            );
            
        }
        else if($params['type'] == 6){
            $password = $params['pay_password'];
            $mobile = $this->user['mobile'];
            $code = $params['code'];
            if(empty($password)){
                __error("请输入支付密码");
            }
            if(mb_strlen($password, 'UTF-8') != 6){
                __error("请输入6位数字支付密码");
            }
            if(empty($mobile)){
                __error("请先绑定手机号");
            }
            
            $result = \app\common\model\bbfxshop\Sms::checkVerifcode($mobile,$code,"pay_password");
            if($result['code'] !== 1){
                __error($result['message']);
            }
            
            $data['pay_password'] = md5($password);
            if($data['pay_password'] == $this->user['pay_password']){
                __error("旧支付密码与新支付密码不可相同");
            }
        }
        else if($params['type'] == 7){
            $password = $params['password'];
            $repassword = $params['repassword'];
            $mobile = $this->user['mobile'];
            $code = $params['code'];
            if(empty($password)){
                __error("请输入登录密码");
            }
            if($password != $repassword){
                __error("两次输入的密码不一致");
            }
            if(mb_strlen($password, 'UTF-8') < 6){
                __error("登录密码长度不足");
            }
            
            // if($_W['base']['login_password_update_type'] != 1){
            //     if(empty($mobile)){
            //         __error("请输入手机号");
            //     }
            //     $result = \app\common\model\bbfxshop\Sms::checkVerifcode($mobile,$code,"password");
            //     if($result['code'] !== 1){
            //         __error($result['message']);
            //     } 
            // }
            // else{
                $old_password = $params['old_password'];
                if(empty($password)){
                    __error("请输入旧登录密码");
                }
                if($old_password == $password){
                    __error("新密码与旧登录密码不能一样");
                }

                $user_password = Db::name("bbfx_user")->where(['id'=>$this->user['id']])->value('password');
                $user_salt = Db::name("bbfx_user")->where(['id'=>$this->user['id']])->value('salt');
                $old_password = md5(md5($old_password).$user_salt);

                if($old_password != $user_password){
                    __error("旧登录密码错误");
                }
            // }
            
            $salt = random(8);
            $password = md5(md5($password).$salt);
            
            $data['salt'] = $salt;
            $data['password'] = $password;
        }
        else if($params['type'] == 8){
            $mobile = $params['mobile'];
            $code = $params['code'];
            if(empty($mobile)){
                __error("请输入手机号");
            }
            $mobile_user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$mobile])->find();
            if(!empty($mobile_user) && $mobile_user['id'] != $this->user['id']){
                __error("该手机号已被使用");
            }
            
            $result = \app\common\model\bbfxshop\Sms::checkVerifcode($mobile,$code,"bind");
            if($result['code'] !== 1){
                __error($result['message']);
            }
            
            $data['mobile'] = $mobile;
            
            if($this->user['platform'] == 'H5' || $this->user['platform'] == 'APP'){
                $openid = $this->user['platform']."_".$mobile."_".random(8);
                $data['openid'] = $openid;
            }
        }
        else if($params['type'] == 21){
            if(empty($params['weixin'])){
                __error("请填写微信号");
            }
            $data['weixin'] = $params['weixin'];
        }
        else{
            __error("修改失败");
        }
        $res = Db::name("bbfx_user")->where('id',$this->user['id'])->update($data);
        if($res){
            /*
            if($params['type'] == 8){
                $uudata = ['username'=>$data['mobile'],'mobile'=>$data['mobile']];
                if(!empty($data['openid']) && $this->user['platform'] != 'WXAPP' && $platform != 'wxapp'){
                    $uudata['openid'] = $data['openid'];
                }
                Db::name("user")->where("id",$this->user['uid'])->update($uudata);
            }
            */
            __success("修改成功");
        }
        else{
            __error("修改失败");
        }
    }
    
    public function scoreLog(){
        global $_W;
        $params = $this->param(['page/d','current/d']);
        
        $user = $this->user;
        
        $page = max(1,intval($params['page']));
        $psize = 20;
        $where = ['uniacid'=>UNIACID,'user_id'=>$user['id'],'type'=>2];
        if($params['current'] == 1){
            $where['money'] = ['>',0];
        }
        else if($params['current'] == 2){
            $where['money'] = ['<',0];
        }
        
        $list = Db::name("bbfx_money_log")->where($where)->order(['createtime desc','id desc'])->limit(($page-1)*$psize,$psize)->select();
        
        if(empty($list)){
            __error($page==1?'暂无数据~':'没有更多了~');
        }
        else{
            foreach ($list as $key => &$val){
                $val['money'] = bd_number($val['money']);
                $val['befores'] = bd_number($val['befores']);
                $val['afters'] = bd_number($val['afters']);
                if($val['money'] > 0){
                    $val['moneyText'] = "+".$val['money'];
                }
                else{
                    $val['moneyText'] = $val['money'];
                }
                
                $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
                $info = iunserializer($val['info']);
                if(!empty($info) && $val['item_type'] == 26){
                    $val['surplus'] = round($info['surplus'],2);
                }
                $val['info'] = $info;
                if($val['item_type'] == 3){
                    $val['title'] = $info['notes'];
                }
                if($val['item_type'] == 26){
                    $val['remarks'] = $_W['fenxiao']['texts']['cumulative_total_fanhuan'];
                }
                $val['mobile'] = '';
                if(in_array($val['item_type'],[52,53,54])){
                    if(!empty($info['mobile'])){
                        $val['mobile'] = $info['mobile'];
                    }
                }
            }
            unset($val);
            
            $income = "0.00";
            $pay = "0.00";
            if($page == 1){
                $income = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'type'=>2,'money'=>['>',0]])->sum("money");
                $pay = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'type'=>2,'money'=>['<',0]])->sum("money");
            }
            
            __success("success",['list'=>$list,'income'=>round($income,2),'pay'=>round($pay,2)]);
        }
        
        
    }
    
    public function moneyLog(){
        global $_W;
        $params = $this->param(['page/d','current/d']);
        
        $user = $this->user;
        
        $page = max(1,intval($params['page']));
        $psize = 20;
        $where = ['uniacid'=>UNIACID,'user_id'=>$user['id'],'type'=>1];
        if($params['current'] == 1){
            $where['money'] = ['>',0];
        }
        else if($params['current'] == 2){
            $where['money'] = ['<',0];
        }
        
        $list = Db::name("bbfx_money_log")->where($where)->order(['createtime desc','id desc'])->limit(($page-1)*$psize,$psize)->select();
        
        if(empty($list)){
            __error($page==1?'暂无数据~':'没有更多了~');
        }
        else{
            $commission_status = ['1'=>'一级佣金','2'=>'二级佣金','3'=>'三级佣金', '4'=>'级差奖','5'=>'见单奖','6'=>'平级奖','7'=>'加权分红','8'=>'总分红','9'=>'总分红(规则)','10'=>'加权分红'];
            foreach ($list as $key => &$val){
                $val['money'] = bd_number($val['money']);
                $val['befores'] = bd_number($val['befores']);
                $val['afters'] = bd_number($val['afters']);
                if($val['money'] > 0){
                    $val['moneyText'] = "+".$val['money'];
                }
                else{
                    $val['moneyText'] = $val['money'];
                }
                
                
                $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
                $info = iunserializer($val['info']);
                if(!empty($info) && $val['item_type'] == 26){
                    $val['surplus'] = round($info['surplus'],2);
                }
                $val['info'] = $info;
                if($val['item_type'] == 3){
                    $val['title'] = $info['notes'];
                }
                else if($val['item_type'] == 11){
                    $val['title'] = $commission_status[$info['type']];
                }
                
                if(!empty($info['user_id']) && $val['item_type'] == 11 && $info['itype'] == 3){
                    
                    // $val['order_no'] = $info['info']['order_no'];
                    // $val['order_id'] = $info['info']['id'];
                    
                    // // echo "<pre>";
                    // // print_r($info);die;
                    
                    // $xia_user = pdo_get("duoduo_activity_user",['id'=>$info['info']['user_id']],['id','avatar','nickname']);
                    // if(!empty($xia_user)){
                    //     $xia_user['avatar'] = tomedia($xia_user['avatar']);
                    //     $val['xia_user'] = $xia_user;
                    // }
                }
                
                if($val['item_type'] == 26){
                    $val['remarks'] = $_W['fenxiao']['texts']['cumulative_total_fanhuan'];
                }

                $val['mobile'] = '';
                if(in_array($val['item_type'],[52,53,54])){
                    if(!empty($info['mobile'])){
                        $val['mobile'] = $info['mobile'];
                    }
                }
            }
            unset($val);
            
            $income = "0.00";
            $pay = "0.00";
            if($page == 1){
                $income = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'type'=>1,'money'=>['>',0]])->sum("money");
                $pay = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'type'=>1,'money'=>['<',0]])->sum("money");
            }
            
            __success("success",['list'=>$list,'income'=>round($income,2),'pay'=>round($pay,2)]);
        }
        
        
    }
    
    public function addUpdateNotice(){
        $params = $this->param();
        
        $user = $this->user;
        
        Db::name("bbfx_user")->where(['id'=>$user['id']])->setInc("update_notice",1);
        
        __success("操作成功");
    }
    
    public function bindMobile(){
        $params = $this->param();
        
        $code = trim($params['code']);
        
        $result = \app\common\model\bbfxshop\Weixin::getPhoneNumber($code);
        
        if(empty($result) || $result['code'] != 1){
            __error($result['message']);
        }
        else{
            
            Db::name("bbfx_user")->where("id",$this->user['id'])->update(['mobile'=>$result['data']]);
            
            __success("操作成功",['mobile'=>$result['data']]);
        }
    }
    
    public function getPhoneNumber(){
        $params = $this->param();
        
        $code = trim($params['code']);
        
        $result = \app\common\model\bbfxshop\Weixin::getPhoneNumber($code);
        
        if(empty($result) || $result['code'] != 1){
            __result($result);
        }
        else{
            __success("操作成功",['mobile'=>$result['data']]);
        }
    }

    
    public function login(){
        global $_W;
        $params = $this->param(['type/d','mobile/s','code/s','password/s','sup_uid/d','platform/s']);
        $code = $params['code'];
        $mobile = $params['mobile'];
        $platform = $params['platform'];
        $sup_uid = intval($params['sup_uid']);
        $password = trim($params['password']);
        
        if(empty($mobile)){
            __error("请输入手机号或账号登录");
        }
        
        $type = intval($params['type']);
        $uid_login = false;
        $is_mobile_login = false;
        if($type == 0){
            $type = 1;
            if(Validate::regex($mobile, "^1\d{10}$")){
                $is_mobile_login = true;
                $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$mobile])->find();
            }
            else{
                $uid = intval($mobile);
                $uid = (string)$uid;
                if(mb_strlen($uid, "utf8") == 9){
                    $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'id'=>intval($uid)])->find();
                    if(!empty($user)){
                        $type = 2;
                        $uid_login = true;
                    }
                }
            }
            if(empty($user)){
                $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'username'=>$mobile])->find();
                if(!empty($user)){
                    if($is_mobile_login){
                        Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'id'=>$user['id']])->update(['mobile'=>$mobile]);
                    }
                    else{
                        $type = 2;
                    }
                }
            }
            if(empty($user)){
                __error("ID、手机号或账号不存在");
            }
            
            
            if($type == 1 && !empty($password) && empty($code)){
                $type = 2;
            }
        }
        else{
            if($type == 1){
                $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$mobile])->find();
                if(empty($user)){
                    __error("手机号未注册");
                }
            }
            else{
                if(Validate::regex($mobile, "^1\d{10}$")){
                    $is_mobile_login = true;
                    $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$mobile])->find();
                }
                else{
                    $uid = intval($mobile);
                    $uid = (string)$uid;
                    if(mb_strlen($uid, "utf8") == 9){
                        $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'id'=>intval($uid)])->find();
                        $uid_login = true;
                    }
                }
                if(empty($user)){
                    $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'username'=>$mobile])->find();
                }
                if(empty($user)){
                    __error("ID、手机号或账号不存在");
                }
            }
        }
        
        if($type == 2){
            if(empty($password)){
                __error("请输入登录密码！");
            }

            $time = strtotime(date('Y-m-d 00:00:00'));
            if($user['loginfailure'] >= 10 && $user['logintime'] > $time){
                __error("请于1天后尝试登录！");
            }

            if($is_mobile_login){
                $bind_list = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$user['mobile']])->field("id,mobile,password,salt,loginfailure,logintime")->select();
            }
            else{
                $bind_list = [];
            }

            $password = md5(md5($password).$user['salt']);

            if(count($bind_list) > 1){
                $mobile = $user['mobile'];
                $user = [];
                foreach($bind_list as $item){
                    $password_ok = false;
                    if($password === $item['password']){
                        $password_ok = true;
                    }
                    if(!$password_ok && $uid_login && empty($item['password']) && trim($params['password']) == '123456789'){
                        // $password_ok = true;
                    }

                    if($password_ok){
                        $user = $item;
                        break;
                    }

                }

                if(empty($user)){
                    if($user['logintime'] > $time){
                        $loginfailure = $user['loginfailure'] + 1;
                    }
                    else{
                        $loginfailure = 1;
                    }
                    
                    Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$mobile])->update(['loginfailure'=>$loginfailure,'logintime'=>time()]);
                    
                    if($type == 1){
                        __error("登录账号或密码错误");
                    }
                    else{
                        __error("登录账号或密码错误");
                    }
                }

                Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$mobile])->update(['loginfailure'=>0]);
                Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'id'=>$user['id']])->update(['logintime'=>time()]);
            }
            else{
                
                $password_ok = false;
                if($password === $user['password']){
                    $password_ok = true;
                }
                if(!$password_ok && $uid_login && empty($user['password']) && trim($params['password']) == '123456789'){
                    // $password_ok = true;
                }
                
                if(!$password_ok){
                    
                    if($user['logintime'] > $time){
                        $loginfailure = $user['loginfailure'] + 1;
                    }
                    else{
                        $loginfailure = 1;
                    }
                    
                    Db::name("bbfx_user")->where(['id'=>$user['id']])->update(['loginfailure'=>$loginfailure,'logintime'=>time()]);
                    
                    if($type == 1){
                        __error("登录账号或密码错误");
                    }
                    else{
                        __error("登录账号或密码错误");
                    }
                }
                else{
                    Db::name("bbfx_user")->where(['id'=>$user['id']])->update(['loginfailure'=>0,'logintime'=>time()]);
                }
            }
        }
        else{
            
            if(empty($code)){
                __error("请输入验证码");
            }
            
            $result = \app\common\model\bbfxshop\Sms::checkVerifcode($mobile,$code,"login");
            if($result['code'] !== 1){
                __error($result['message']);
            }
        }
        
        $ret = $this->auth->direct($user['id']);
        if(empty($ret)){
            __error($this->auth->getError());
        }
        $user = $this->auth->getUserinfo();
        if($sup_uid > 0){
            $this->model->bind($user,$sup_uid);
        }
        
        $user = filterData($user,"password,pay_password");
        $this->model->visitor($user['id'],$this->param("utk/s"),$this->param('platform/s'));
        __success("登录成功",$user);
    }

    protected function getLoginType(){
        global $_W;
        $base = $_W['base'];
        $platform = $this->param('platform/s');
        $wxapp_login = intval($base['wxapp_login']);
        $h5_login = intval($base['h5_login']);
        $app_login = intval($base['app_login']);

        $login_type = 0;
        if(($platform == 'wxapp' || $platform == 'WXAPP')){
            $login_type = $wxapp_login;
        }
        else if($platform == 'H5' || $platform == 'GZH'){
            $login_type = $h5_login;
            if($platform == 'GZH' && $base['is_gzh_login'] == 1){
                $login_type = 0;
            }
        }
        else if($platform == 'app' || $platform == 'APP'){
            $login_type = $app_login;
        }

        return $login_type;
    }
    
    public function register(){
        global $_W;
        $params = $this->param();
        $code = $params['code'];
        $mobile = $params['mobile'];
        $password = trim($params['password']);
        $repassword = trim($params['repassword']);
        $sup_code = $params['sup_code'];
        $platform = $params['platform'];
        $login_code = $params['login_code'];
        $type = intval($params['type']);
        
        $login_type = $this->getLoginType();
        if($login_type == 0 || $login_type == 4){
            // $this->wxappLogin();
            // __error("暂不支持该登录方式");
        }
        // if($login_type == 3){
        if($type == 2){
            if(empty($mobile)){
                __error("请输入用户名");
            }
            $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'username'=>$mobile])->find();
            if(!empty($user)){
                __error("用户名已存在");
            }
        }
        // else if($login_type == 1){
        else if($type == 1){
            if(empty($mobile)){
                __error("请输入手机号");
            }
            if(empty($code)){
                __error("请输入验证码");
            }

            $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$mobile])->find();
            if(!empty($user)){
                __error("手机号已注册");
            }
            if(empty($code)){
                __error("请输入验证码");
            }
        }
        else{
            __error("暂不支持该注册方式");
        }
        
        if(empty($password)){
            __error("请输入密码");
        }
        if($password !== $repassword){
            __error("两次输入的密码不一致");
        }
        
        if(mb_strlen($password, 'UTF-8') < 6){
            __error("密码长度不足，最低6位字符");
        }
        
        $openid = "";
        $unionid = "";
        $register_type = 0;// 0=注册，1=合并
        $platforms = ['wxapp','WXAPP','GZH','dyapp'];
        $openid_key = $this->model->getOpenidKey($platform);
        if(in_array($platform,$platforms)){

            if($platform == 'GZH'){
                $login_openid = Session::get('openid');
                $unionid = Session::get('unionid');
                if(empty($login_openid)) $login_openid = "";
                if(empty($unionid)) $unionid = "";
            }
            else{
                $result = $this->model->login($login_code,$platform);
                if($result['code'] != 1){
                    __result($result);
                }
                $login_openid = $result['data']['openid'];
                $unionid = $result['data']['unionid'];
            }
            $openid_user = [];
            if(!empty($login_openid)){
                // $openid_user = $this->model->getInfo($login_openid);
            }
            if(!empty($openid_user)){

                if(($type == 1 && empty($openid_user['mobile'])) || ($type == 2 && empty($openid_user['username']))){
                    $register_type = 1;
                    $openid = $login_openid;
                }
                else{
                    $openid = "";
                    $register_type = 2;
                }
                
            }
            else{
                $openid = $login_openid;
            }
        }
        
        
        if($type == 1){
            $result = \app\common\model\bbfxshop\Sms::checkVerifcode($mobile,$code,"register");
            if($result['code'] != 1){
                __result($result);
            }
        }

        try {

            $utk = $this->param("utk/d");
            if(intval($sup_code) <= 0){
                $sup_uid1 = intval(Session::get('sup_uid'));
                if($sup_uid1 > 0){
                    $sup_code = $sup_uid1;
                }
                if($sup_code <= 0 && $utk > 0){
                    $suplog = Db::name("bbfx_user_suplog")->where(['uniacid'=>UNIACID,'utk'=>$utk,'createtime'=>['>',strtotime(date('Y-m-d 00:00:00'))]])->order("id desc")->find();
                    if(!empty($suplog)){
                        $sup_code = $suplog['sup_uid'];
                    } 
                }
            }
            
            // file_put_contents("ud111.txt",request()->ip()."=>".$openid."：".$sup_uid."\n",FILE_APPEND);
        } catch (\Exception $e) { }
        
        $sup_uid = 0;
        $sup_path = "0";
        $o_sup_path = "0";
        if(!empty($sup_code)){
            $sup_user = $this->model->getSupUser(intval($sup_code));
            if(!empty($sup_user)){
                $sup_uid = $sup_user['id'];
                $sup_path = $sup_user['sup_path'];
                if(!empty($sup_user['o_sup_path'])){
                    $o_sup_path = $sup_user['o_sup_path'];
                }
            }
        }
        
        $avatar = $params['avatar'];
        $nickname = $params['nickname'];
        $sex = intval($params['sex']);
        $platform = $params['platform'];
        
        if(empty($nickname)){
            if($type == 2){
                $nickname = "用户".random(9,true);
            }
            else{
                $nickname = secret($mobile,true,3,4);
            }
        }
        if(empty($avatar)){
            $avatar = "/assets/images/avatar.jpg";
        }
        
        
        $salt = random(8);
        $password = md5(md5($password).$salt);
        
        $data = [
            "uniacid"=>UNIACID,
            "avatar"=>$avatar,
            "nickname"=>$nickname,
            "sex"=>$sex,
            "password"=>$password,
            "salt"=>$salt,
        ];

        if($type == 2){
            $data['username'] = $mobile;
        }
        else{
            $data['mobile'] = $mobile;
        }
        
        if($register_type == 1){
            $user_id = $openid_user['id'];
            if(in_array($platform,$platforms)){

                $data[$openid_key] = $openid;
                
                if(!empty($unionid) && $platform != 'dyapp'){
                    $unionid_user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'unionid'=>$unionid])->field("id,platform")->find();
                    if(empty($unionid_user)){
                        $data['unionid'] = $unionid;
                    }
                }
            }
            Db::name("bbfx_user")->where(['id'=>$user_id])->update($data);
        }
        else{
            $data['sup_uid'] = $sup_uid;
            if(!empty($openid_key)){
                $data[$openid_key] = $openid;
            }
            $data['createtime'] = time();
            $data['platform'] = $platform;
            if($sup_uid > 0){
                $data['bindtime'] = time();
            }
            else{
                if($_W['base']['register_required_sup_uid'] == 1){
                    __error("推荐码错误或不存在，无法注册");
                }
            }
            if(($platform == 'wxapp' || $platform == 'WXAPP') || $platform == 'GZH'){
                if($platform == 'GHZ'){
                    $data['gzh_openid'] = $openid;
                }
                else{
                    $data['wxapp_openid'] = $openid;
                }
                
                if(!empty($unionid)){
                    $unionid_user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'unionid'=>$unionid])->field("id,platform")->find();
                    if(empty($unionid_user)){
                        $data['unionid'] = $unionid;
                    }
                }
            }
            
            $data['code'] = random_int(100000,999999);
            $data['id'] = $this->model->uuid();
            $user_id = $data['id'];
            Db::name("bbfx_user")->insert($data);
            if(!empty($data['sup_uid'])){
                \app\common\model\bbfxshop\Contribution::jisuanShareContributionValue($user_id);
                \app\common\model\bbfxshop\Saward::setCommission($data['sup_uid']);
            }
        }
        
        
        if(empty($user_id)){
            __error("注册失败");
        }
        
        if($register_type != 1){
            $sup_path .= "-".$user_id;
            $data = ['sup_path'=>$sup_path];
            if($o_sup_path != ''){
                $data['o_sup_path'] = $o_sup_path."-".$user_id;
            }
            Db::name("bbfx_user")->where(['id'=>$user_id])->update($data);
        }
        
        \app\common\model\bbfxshop\FenxiaoUpgrade::upgrade($user_id);
        
        $ret = $this->auth->direct($user_id);
        if(empty($ret)){
            __error($this->auth->getError());
        }
        $user = $this->auth->getUserinfo();
        $user = filterData($user,"password,pay_password");
        $this->model->visitor($user['id'],$this->param("utk/s"),$this->param('platform/s'));
        __success("注册成功",$user);
    }
    
    public function gzhLogin(){
        global $_W;
        $params = $this->param(['source/s','sup_uid/s','ret_url/s','utk/d','scope/s','openid/s']);
        
        $source = $params['source'];
        $sup_uid = intval($params['sup_uid']);
        $utk = intval($params['utk']);
        $ret_url = $params['ret_url'];
        
        if(empty($ret_url)){
            $ret_url = "/pages/index/index";
        }
        
        if(empty($source)){
            $source = "mobile";
        }
        
        $platform = $_W['platform'];
        $is_gzh_login = Db::name("bbfx_base")->where(['uniacid'=>UNIACID])->value("is_gzh_login");
        if($source == 'mobile'){

            if(!empty($this->user)){
                // __error("已登录");
            }
            
            $ret_url = urldecode($ret_url);
            
            $redirect_uri = request()->domain()."/api/user/user/gzhLogin?source=wechat&utk={$utk}&ret_url={$ret_url}&i=".UNIACID;                 
            if(!empty($sup_uid)){
                $redirect_uri .= "&sup_uid={$sup_uid}";
            }
            $redirect_uri = urlencode($redirect_uri);
            $scope = "snsapi_userinfo";
            if($is_gzh_login != 1 || $scope == "snsapi_base"){
                $scope = "snsapi_base";
            }

            if($is_gzh_login == 1 && !$this->auth->isLogin()){
                $scope = "snsapi_userinfo";
            }
            
            try {
                // file_put_contents("ud222.txt",request()->ip()."：".$sup_uid."\n",FILE_APPEND);
            } catch (\Exception $e) {
            }
            
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$platform['AppId']}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state=STATE#wechat_redirect";
            
            $this->success("操作成",$url);
        }
        else if($source == 'wechat'){
            $code = $this->paramGet('code/s');
            
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$platform['AppId']}&secret={$platform['AppSecret']}&code={$code}&grant_type=authorization_code";
            
            $result = ihttp_get($url);
            $result = json_decode($result['content'],true);
            
            if(empty($result['access_token'])){
                __error($result['errmsg']);
            }
            
            $access_token = $result['access_token'];
            $openid = $result['openid'];
            $unionid = $result['unionid'];
            if(empty($unionid)){
                $unionid = "";
            }
            $is_snapshotuser = 0;
            if(!empty($result['is_snapshotuser'])){
                if($result['is_snapshotuser'] == 1){
                    $is_snapshotuser = 1;
                }
            }

            
            if($is_snapshotuser != 1){
                Session::set('openid',$openid);
                Session::set('unionid',$unionid);
            }
            
            if($is_snapshotuser != 1 && $is_gzh_login == 1){
                $result = ihttp_get("https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN");
            
                $result = json_decode($result['content'],true);
                $nickname = "";
                $avatar = "";
                if(empty($result['openid'])){
                    __error("登录失败");
                }

                if(empty($result['headimgurl']) && $is_gzh_login != 1){
                    addFileLog("gl111",$utk."：获取openid\n",FILE_APPEND);
                    addFileLog("gl222",json_encode($result));
                    $ret_url = urldecode($ret_url);
                    $url = request()->domain()."/mobile/#".$ret_url;
                    header("Location: ".$url);
                    exit();
                }

                /*
                $userinfo = Db::name("user")->where("openid",$openid)->find();
                if(empty($userinfo)){
                    $mobile = "";
                    $username = $mobile;
                    if(empty($username)){
                        $username = random(12,true);
                    }
                    $password = "123456789";
                    $extend = ['avatar'=>$result['headimgurl'],'nickname'=>$result['nickname'],'openid'=>$openid];
                    
                    $ret = $this->auth->register($username, $password, '', $mobile, $extend);
                    $userinfo = Db::name("user")->where("openid",$openid)->find();
                }
                else{
                    $ret = $this->auth->direct($userinfo['id']);
                }
                if(empty($ret)){
                    __error($this->auth->getError());
                }
                */
                
                $uid = $this->model->getUnionidUser($openid,$unionid,'GZH');
                $ret = $this->auth->direct($uid);
                
                $token = "";
                
                $data = ['avatar'=>$result['headimgurl'],'nickname'=>$result['nickname']];
                if(empty($data['avatar'])){
                    $data['avatar'] = "/assets/images/avatar.jpg";
                }
                if(empty($data['nickname'])){
                    $data['nickname'] = "用户".random(9,true);
                }
                
                if(empty($ret)){
                    // $data['uid'] = $userinfo['id'];
                	$data['createtime'] = time();
                    $data['openid'] = $openid;
                    $data['gzh_openid'] = $openid;
                    $data['uniacid'] = UNIACID;
                    $data['platform'] = "GZH";
                    if(!empty($unionid)){
                        $data['unionid'] = $unionid;
                    }
                    
                    
                    try {
                        
                        if(intval($sup_uid) <= 0){
                            $sup_uid1 = intval(Session::get('sup_uid'));
                            if($sup_uid1 > 0){
                                $sup_uid = $sup_uid1;
                            }
                            if($sup_uid <= 0 && $utk > 0){
                                $suplog = Db::name("bbfx_user_suplog")->where(['uniacid'=>UNIACID,'utk'=>$utk])->order("id desc")->find();
                                if(!empty($suplog)){
                                    $sup_uid = $suplog['sup_uid'];
                                } 
                            }
                        }
                        
                        // file_put_contents("ud111.txt",request()->ip()."=>".$openid."：".$sup_uid."\n",FILE_APPEND);
                    } catch (\Exception $e) {
                    }
                    
                    $sup_path = "0";
                    $o_sup_path = "0";
                    if($sup_uid > 0){
                        $sup_user = $this->model->getSupUser($sup_uid);
                        if(!empty($sup_user)){
                            $data['sup_uid'] = $sup_user['id'];
                            $sup_path = $sup_user['sup_path'];
                            if(!empty($sup_user['o_sup_path'])){
                                $o_sup_path = $sup_user['o_sup_path'];
                            }
                        }
                        else{
                            $data['sup_uid'] = 0;
                            if($_W['base']['register_required_sup_uid'] == 1){
                                __error("推荐码错误或不存在，无法注册");
                            }
                        }
                    }
                    $data['code'] = random_int(100000,999999);
                    $data['id'] = $this->model->uuid();
                    $user_id = $data['id'];
                    Db::name("bbfx_user")->insert($data);
                    if(empty($user_id)){
                        __error("登录失败");
                    }
                    if(!empty($data['sup_uid'])){
                        \app\common\model\bbfxshop\Contribution::jisuanShareContributionValue($user_id);
                        \app\common\model\bbfxshop\Saward::setCommission($data['sup_uid']);
                    }

                    $sup_path .= "-".$user_id;
                    $data = ['sup_path'=>$sup_path];
                    if($o_sup_path != ''){
                        $data['o_sup_path'] = $o_sup_path."-".$user_id;
                    }
                    Db::name("bbfx_user")->where(['id'=>$user_id])->update($data);

                    \app\common\model\bbfxshop\FenxiaoUpgrade::upgrade($user_id);
                    
                    $ret = $this->auth->direct($user_id);
                    if(empty($ret)){
                        __error($this->auth->getError());
                    }
                    $user = $this->auth->getUserinfo();
                }
                else{
                    $user = $this->auth->getUserinfo();
                    $data = [];
                    $data['gzh_openid'] = $openid;
                    if(!empty($unionid) && empty($user['unionid'])){
                        $data['unionid'] = $unionid;
                    }
                    Db::name("bbfx_user")->where(['id'=>$this->auth->id])->update($data);
                    if($sup_uid > 0){
                        $this->model->bind($user,$sup_uid);
                    }
                }
                
                Session::set('uToken',$user['token']);
            }
            
            $ret_url = urldecode($ret_url);
            
            $url = request()->domain()."/mobile/#".$ret_url;
            header("Location: ".$url);
            exit();
        }
    }
    
    public function getWxappOpenid(){
        $code = $this->param("code/s");
        $platform = $this->param("platform/s");
        if($platform == 'GZH' || $platform == 'H5'){
            $openid = Session::get('openid');
            if(empty($openid)){
                __error("未授权登录");
            }
        }
        else if($platform == 'APP'){
            __error("未授权登录"); 
        }
        else{
            $result = $this->model->login($code,$platform);
            if(empty($result) || $result['code'] != 1){
                __result($result);
            }
            $openid = $result['data']['openid'];
        }
        
        addFileLog("ooo111",$openid);
        __success("操作成功",$openid);
    }
    
    // 手机号授权登录
    public function mobileAuthLogin(){
        global $_W;
        $params = $this->param(['code/s','login_code/s','platform/s','sup_uid/d']);
        
        $code = trim($params['code']);
        $login_code = trim($params['login_code']);
        $platform = trim($params['platform']);

        $login_type = $this->getLoginType();
        if($login_type == 0 || $login_type == 4){
            // $this->wxappLogin();
            // __error("暂不支持该登录方式");
        }
        if($login_type != 2){
            // __error("暂不支持该登录方式");
        }
        
        $result = $this->model->getPhoneNumber($code,$platform);
        
        if($result['code'] != 1){
            __result($result);
        }
        
        $mobile = $result['data'];
        if(empty($mobile)){
            __error("手机号错误");
        }
        
        
        $result = $this->model->login($login_code,$platform);
        if($result['code'] != 1){
            __result($result);
        }

        $openid = $result['data']['openid'];
        
        $data = [];

        $openid_key = $this->model->getOpenidKey($platform);
        
        $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,"{$openid_key}"=>$openid,'mobile'=>$mobile])->find();

        if(empty($user)){
            $openid_user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,"{$openid_key}"=>$openid])->find();
            $mobile_user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$mobile])->find();

            if(!empty($openid_user) || !empty($mobile_user)){
                if(!empty($openid_user) && !empty($mobile_user)){
                    if($openid_user['id'] == $mobile_user['id']){
                        $user = $openid_user;
                    }
                    else{
                        $user = $mobile_user;
                    }
                }
                else if(empty($openid_user) && !empty($mobile_user)){
                    $user = $mobile_user;
                    if(empty($user[$openid_key])){
                        $data['platform'] = $platform;
                        $data[$openid_key] = $openid;
                    }
                    
                }
                else if(!empty($openid_user) && empty($mobile_user)){
                    if(empty($openid_user['mobile']) || $openid_user['mobile'] == $mobile){
                        $user = $openid_user;
                        $data['mobile'] = $mobile;
                    }
                }
            }
        }
        
        $avatar = "/assets/images/avatar.jpg";
        $nickname = secret($mobile,true,3,4);
        
        if(!empty($user)){

            if($user['platform'] == 'H5' || $user['platform'] == 'APP'){
                $data = [];
                $data[$openid_key] = $openid;
            }
            
            if(!empty($data)){
                Db::name("bbfx_user")->where(['id'=>$user['id']])->update($data);
            }
            
            $sup_uid = intval($params['sup_uid']);
            if($sup_uid > 0){
                $this->model->bind($user,$sup_uid);
            }
            $user_id = $user['id'];
        }
        else{
            
            $data['uniacid'] = UNIACID;
            $data[$openid_key] = $openid;
            if(empty($openid_user)){
                // $data['openid'] = $openid;
            }
            $data['avatar'] = $avatar;
            $data['nickname'] = $nickname;
            // $data['sex'] = 1;
            $data['mobile'] = $mobile;
            $data['createtime'] = time();

            $sup_uid = intval($params['sup_uid']);


            try {

                $utk = $this->param("utk/d");
                if(intval($sup_uid) <= 0){
                    if($utk > 0){
                        $suplog = Db::name("bbfx_user_suplog")->where(['uniacid'=>UNIACID,'utk'=>$utk,'createtime'=>['>',strtotime(date('Y-m-d 00:00:00'))]])->order("id desc")->find();
                        if(!empty($suplog)){
                            $sup_uid = $suplog['sup_uid'];
                        } 
                    }
                }
                
                // file_put_contents("ud111.txt",request()->ip()."=>".$openid."：".$sup_uid."\n",FILE_APPEND);
            } catch (\Exception $e) { }


            $sup_path = "0";
            $o_sup_path = "0";
            if($sup_uid > 0){
                $sup_user = $this->model->getSupUser($sup_uid);
                if(!empty($sup_user)){
                    $data['sup_uid'] = $sup_user['id'];
                    $data['bindtime'] = time();
                    $sup_path = $sup_user['sup_path'];
                    if(!empty($sup_user['o_sup_path'])){
                        $o_sup_path = $sup_user['o_sup_path'];
                    }
                }
                else{
                    if($_W['base']['register_required_sup_uid'] == 1){
                        __error("推荐码错误或不存在，无法注册");
                    }
                }
            }

            $data['code'] = random_int(100000,999999);
            $data['id'] = $this->model->uuid();
            $user_id = $data['id'];
            Db::name("bbfx_user")->insert($data);
            if(!empty($data['sup_uid'])){
                \app\common\model\bbfxshop\Contribution::jisuanShareContributionValue($user_id);
                \app\common\model\bbfxshop\Saward::setCommission($data['sup_uid']);
            }
            $is_new = 1;
            
        }
        
        $ret = $this->auth->direct($user_id);
        if(empty($ret)){
            __error($this->auth->getError());
        }
        $user = $this->auth->getUserinfo();
        
        if($is_new == 1){
            $sup_path .= "-".$user['id'];
            $data = ['sup_path'=>$sup_path];
            if($o_sup_path != ''){
                $data['o_sup_path'] = $o_sup_path."-".$user_id;
            }
            Db::name("bbfx_user")->where(['id'=>$user['id']])->update($data);
            \app\common\model\bbfxshop\FenxiaoUpgrade::upgrade($user['id']);
        }
        $user = filterData($user,"password,pay_password");
        $this->model->visitor($user['id'],$this->param("utk/s"),$this->param('platform/s'));
        __success("登录成功",$user);
    }
    
    public function wxappLogin(){
        global $_W;
        $params = $this->param();
        $platform = trim($params['platform']);
        $code = trim($params['code']);
        
        $login_type = $this->getLoginType();
        if($login_type != 0 && $login_type != 4){
            // __error("暂不支持该登录方式");
        }
        
        $result = $this->model->login($code,$platform);
        if($result['code'] != 1){
            __result($result);
        }
        
        $openid = $result['data']['openid'];
        $unionid = $result['data']['unionid'];
        
        if($platform == 'wxapp' || $platform == 'wxapp'){
            $uid = $this->model->getUnionidUser($openid,$unionid,'wxapp');
        }
        else{
            $uid = $this->model->getUserId($openid,$platform);
        }

        $openid_key = $this->model->getOpenidKey($platform);
        
        $ret = $this->auth->direct($uid);
        
        $data = [];
        $avatar = $params['avatar'];
        $nickname = $params['nickname'];
        $mobile = $params['mobile'];
        $sex = intval($params['sex']);
        
        if(empty($avatar)){
            $avatar = "/assets/images/avatar.jpg";
        }
        if(empty($nickname) && !empty($mobile)){
            $nickname = secret($mobile,true,3,4);
        }
        if(empty($nickname)){
            $nickname = "用户".random(8,true);
        }
        
        if(!empty($avatar) || !empty($nickname)){
            $data['avatar'] = $avatar;
        	$data['nickname'] = $nickname;
        }
        
        if(!empty($ret)){
            
            $data = [];
            $data[$openid_key] = $openid;
            if($platform == 'wxapp' && !empty($unionid) && empty($this->auth->unionid)){
                $data['unionid'] = $unionid;
            }
            Db::name("bbfx_user")->where(['id'=>$this->auth->id])->update($data);
            $user_id = $this->auth->id;
            
            $user = $this->auth->getUserinfo();
            $sup_uid = intval($params['sup_uid']);
            if($sup_uid > 0){
                $this->model->bind($user,$sup_uid);
            }
        }
        else{
            /*
            $userinfo = Db::name("user")->where("openid",$openid)->find();
            if(empty($userinfo)){
                $username = $mobile;
                if(empty($username)){
                    $username = random(12,true);
                }
                $password = "123456789";
                $extend = ['avatar'=>$avatar,'nickname'=>$nickname,'openid'=>$openid];
                
                $ret = $this->auth->register($username, $password, '', $mobile, $extend);
                
            }
            else{
                $ret = $this->auth->direct($userinfo['id']);
            }
            if(empty($ret)){
                __error($this->auth->getError());
            }
            $userinfo = $this->auth->getUserinfo();
            $data['uid'] = $userinfo['id'];
            */
            
            
        	$data['createtime'] = time();
            $data[$openid_key] = $openid;
            $data['openid'] = $openid;
            $data['sex'] = $sex;
            $data['mobile'] = $mobile;
            $data['uniacid'] = UNIACID;
            $data['platform'] = $platform;
            if($platform == 'wxapp' && !empty($unionid)){
                $data['unionid'] = $unionid;
            }
            $set = $_W['base'];
            
            if(in_array('4',$set['wxapp_login']) && empty($mobile)){
                __error("请授权手机号");
            }
            
            
            $is_merge_user = false;
            if(!empty($mobile)){
                $mobile_user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$mobile])->find();

                if(!empty($mobile_user)){
                    if($mobile_user['platform'] == 'wxapp' || $mobile_user['platform'] == 'WXAPP' || $mobile_user['platform'] == 'GZH'){
                        __error("该手机号已被其他用户绑定");
                    }

                    if(($mobile_user['platform'] == 'H5' || $mobile_user['platform'] == 'APP') && empty($mobile_user[$openid_key])){
                        $is_merge_user = true;
                    }
                }
            }

            if($is_merge_user){
                $data = [
                    'sex'=>$sex,
                ];

                $data[$openid_key] = $openid;

                if(!empty($params['nickname'])){
                    $data['nickname'] = $params['nickname'];
                }
                if(!empty($params['avatar'])){
                    $data['avatar'] = cdnurl($params['avatar']);
                }
                if($platform == 'wxapp' && !empty($unionid) && empty($mobile_user['unionid'])){
                    $data['unionid'] = $unionid;
                }
                Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'id'=>$mobile_user['id']])->update($data);
                $user_id = $mobile_user['id'];
                $is_new = 0;
            }
            else{
                $sup_uid = intval($params['sup_uid']);
                $sup_path = "0";
                $o_sup_path = "0";

                try {
                    $utk = $this->param("utk/d");
                    if(intval($sup_uid) <= 0){
                        if($utk > 0){
                            $suplog = Db::name("bbfx_user_suplog")->where(['uniacid'=>UNIACID,'utk'=>$utk,'createtime'=>['>',strtotime(date('Y-m-d 00:00:00'))]])->order("id desc")->find();
                            if(!empty($suplog)){
                                $sup_uid = $suplog['sup_uid'];
                            } 
                        }
                    }
                    
                    // file_put_contents("ud111.txt",request()->ip()."=>".$openid."：".$sup_uid."\n",FILE_APPEND);
                } catch (\Exception $e) { }


                if($sup_uid > 0){
                    $sup_user = $this->model->getSupUser($sup_uid);
                    if(!empty($sup_user)){
                        $data['sup_uid'] = $sup_user['id'];
                        $data['bindtime'] = time();
                        $sup_path = $sup_user['sup_path'];
                        if(!empty($sup_user['o_sup_path'])){
                            $o_sup_path = $sup_user['o_sup_path'];
                        }
                    }
                    else{
                        if($_W['base']['register_required_sup_uid'] == 1){
                            __error("推荐码错误或不存在，无法注册");
                        }
                    }
                }
                $data['code'] = random_int(100000,999999);
                $data['id'] = $this->model->uuid();
                $user_id = $data['id'];

                Db::name("bbfx_user")->insert($data);

                if(!empty($data['sup_uid'])){
                    \app\common\model\bbfxshop\Contribution::jisuanShareContributionValue($user_id);
                    \app\common\model\bbfxshop\Saward::setCommission($data['sup_uid']);
                }
                
                $is_new = 1;
            }
            
            
            $ret = $this->auth->direct($user_id);
            if(empty($ret)){
                __error($this->auth->getError());
            }
            $user = $this->auth->getUserinfo();
        }
        
        if($is_new == 1){
            $sup_path .= "-".$user['id'];
            $data = ['sup_path'=>$sup_path];
            if($o_sup_path != ''){
                $data['o_sup_path'] = $o_sup_path."-".$user_id;
            }
            Db::name("bbfx_user")->where(['id'=>$user['id']])->update($data);
            \app\common\model\bbfxshop\FenxiaoUpgrade::upgrade($user['id']);
        }
        $user = filterData($user,"password,pay_password");
        $this->model->visitor($user['id'],$this->param("utk/s"),$this->param('platform/s'));
        __success("登录成功",$user);
    }

    public function unbind(){
        $id = $this->param("id/d");
        $user = $this->user;

        $bind = Db::name("bbfx_user")->where(["id"=>$id,'mobile'=>$user['mobile']])->find();
        if(empty($bind)){
            __error("绑定账号用户不存在");
        }

        Db::name("bbfx_user")->where(["id"=>$id])->update(['mobile'=>'']);
        
        __success("操作成功");
    }

    public function addAccount(){
        $username = $this->param("username/s");
        $password = $this->param("password/s");
        $repassword = $this->param("repassword/s");
        $nickname = $this->param("nickname/s");
        $avatar = $this->param("avatar/s");
        $sup_uid = $this->param("sup_uid/d");
        
        if(empty($username)){
            __error("请输入账号");
        }
        if(empty($password)){
            __error("请输入密码");
        }
        if(empty($repassword)){
            __error("请确认密码");
        }
        if($password != $repassword){
            __error("两次密码不一致");
        }

        if(mb_strlen($password, 'UTF-8') < 6){
            __error("密码长度不足，最低6位字符");
        }

        if(empty($nickname)){
            $nickname = "用户".random(8,true);
        }
        if(empty($avatar)){
            $avatar = "/assets/images/avatar.png";
        }

        $sup_path = "0";
        $o_sup_path = "0";
        if(!empty($sup_uid)){
            $sup_user = $this->model->getSupUser(intval($sup_uid));
            if(!empty($sup_user)){
                $sup_uid = $sup_user['id'];
                $sup_path = $sup_user['sup_path'];
                if(!empty($sup_user['o_sup_path'])){
                    $o_sup_path = $sup_user['o_sup_path'];
                }
            }
        }
        else{
            $sup_uid = 0;
        }

        $salt = random(8);
        $password = md5(md5($password).$salt);

        $user = $this->user;
        $mobile = $user['mobile'];
        $id = $this->model->uuid();
        $data = [
            "id"=>$id,
            "uniacid"=>UNIACID,
            "sup_uid"=>$sup_uid,
            "sup_path"=>$sup_path."-".$id,
            "o_sup_path"=>$o_sup_path."-".$id,
            "username"=>$username,
            "mobile"=>$mobile,
            "avatar"=>replaceSiteroot($avatar),
            "nickname"=>$nickname,
            "password"=>$password,
            "salt"=>$salt,
            "code"=>random_int(100000,999999),
            "createtime"=>time()
        ];

        Db::name("bbfx_user")->insert($data);
        
        __success("操作成功",['id'=>$data['id']]);
    }

    public function getBindList(){
        $user = $this->user;
        if(empty($user['mobile'])){
            __error("请先绑定手机号");
        }

        $list = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$user['mobile']])->field("id,username,nickname,avatar")->select();
        if(empty($list)){
            __error("暂无绑定用户");
        }
        foreach($list as $key => &$val){
            $val['avatar'] = cdnurl($val['avatar']);
        }
        unset($val);
        __success("获取成功",['list'=>$list]);
    }

    public function switchAccount(){
        $id = $this->param("id/d");
        $user = $this->user;
        $bind = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'id'=>$id,'mobile'=>$user['mobile']])->find();
        if(empty($bind)){
            __error("切换用户不存在");
        }
        if($bind['id'] == $user['id']){
            __error("不能切换到当前用户");
        }

        // 退出登录
        if(Session::has('uToken')){
            Session::delete('uToken');  
        }
        $this->auth->logout();

        // 切换用户
        $this->auth->direct($bind['id']);
        $user = $this->auth->getUserinfo();
        $user = filterData($user,"password,pay_password");
        $this->model->visitor($user['id'],$this->param("utk/s"),$this->param('platform/s'));
        __success("切换成功",$user);
    }
    
    public function info(){
        
        $params = $this->param(['code/s','sup_uid/d','platform/s']);
        
        $user = $this->user;
        $code = $params['code'];
        $sup_uid = $params['sup_uid'];
        $platform = $params['platform'];
        if(empty($user) && !empty($code)){
            
            $result = $this->model->login($code,$platform);
            if(empty($result) || $result['code'] != 1){
                $this->model->visitor(0,$this->param("utk/s"),$this->param('platform/s'));
                __error($result['message']);
            }
            
            $openid = $result['data']['openid'];
            $unionid = $result['data']['unionid'];

            if($platform == 'WXAPP' || $platform == 'wxapp'){
                $uid = $this->model->getUnionidUser($openid,$unionid,'wxapp');
            }
            else{
                $uid = $this->model->getUserId($openid,$platform);
            }

            $openid_key = $this->model->getOpenidKey($platform);

            $ret = $this->auth->direct($uid);
            
            if(empty($ret)){
                $this->addSupLog();
                $this->model->visitor(0,$this->param("utk/s"),$this->param('platform/s'));
                __error("用户不存在");
            }
            
            
            $user = $this->auth->getUserinfo();
            $data = [];
            if(empty($user['unionid']) && $platform != 'dyapp'){
                $data['unionid'] = $unionid;
            }
            if(!empty($user[$openid_key])){
                $data[$openid_key] = $openid;
            }
            if(!empty($data)){
                Db::name("bbfx_user")->where(['id'=>$user['id']])->update($data);
            }
        }
        
        if(!empty($user)){
            if($sup_uid > 0){
                $this->model->bind($user,$sup_uid);
            }

            $user = filterData($user,"password,pay_password");
            $this->model->visitor($user['id'],$this->param("utk/s"),$this->param('platform/s'));
            __success("操作成功",$user);
        }
        else{
            $this->model->visitor(0,$this->param("utk/s"),$this->param('platform/s'));
            $this->addSupLog();
            __error("用户不存在");
        }
    }
    
    protected function addSupLog(){
        $sup_uid = $this->param("sup_uid/d");
        $utk = $this->param("utk/d");
        
        try {
            if($sup_uid > 0){
                Session::set('sup_uid',$sup_uid);
                $log = Db::name("bbfx_user_suplog")->where(['uniacid'=>UNIACID,'utk'=>$utk,'sup_uid'=>$sup_uid,'createtime'=>['>',strtotime(date('Y-m-d 00:00:00'))]])->find();
                if(empty($log)){
                    Db::name("bbfx_user_suplog")->insert(['uniacid'=>UNIACID,'ip'=>request()->ip(),'utk'=>$utk,'sup_uid'=>$sup_uid,'createtime'=>time()]);
                }
            }
        } 
        catch (\Exception $e) {
            // print_r($e->getMessage());die;
        }
        
    }
    
    public function subscribe(){
        global $_W;
        $params = $this->param();
        
        $user = $this->user;
        $base = $_W['base'];
        
        Db::name("bbfx_user")->where(["uniacid"=>UNIACID,"id"=>$user['id']])->setInc("subscribe_num",1);
        $user = Db::name("bbfx_user")->where(["uniacid"=>UNIACID,"id"=>$user['id']])->find();
        $user['isAdmin'] = 0;
        if($base['admin']){
             $admin = explode(",",$base['admin']);
             foreach ($admin as $key => $val){
                 if($val == $user['id']){
                     $user['isAdmin'] = 1;
                 }
             }
        }
        
        $user = filterData($user,"password,pay_password");
        
        __success("success",$user);
    }

    public function checkGuanzhu(){
        __error("不是小程序端");
        $openid = $this->param("openid/s");
        $platform = $this->param("platform/s");
        if($platform != 'wxapp' && $platform != 'WXAPP'){
            __error("不是小程序端");
        }
        if(empty($openid)){
            $openid = $this->user['gzh_openid'];
        }
        if(empty($openid)){
            __error("openid错误");
        }

        $result = \app\common\model\bbfxshop\Weixin::getWxAccessToken();
        if($result['code'] != 1){
            __result($result);
        }
        $access_token = $result['data'];

        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid=o6_bmjrPTlm6_2sgVt7hMZOPfL2M&lang=zh_CN";
        $result = ihttp_get($url);
        $result = toJsonde($result['content']);
        if(empty($result['openid'])){
            __error($result['errmsg']);
        }

        __success("操作成功",['subscribe'=>$result['subscribe']]);
    }
}