<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\api\controller\Common;
use app\api\validate\user\Report;
use app\common\model\UserPower;
use app\common\service\TenimService;
use outh\outh;
use think\Db;
use app\common\controller\RedisLeaderboard;
use Redis;
use GatewayClient\Gateway;
use think\Exception;

/**
 * 会员中心接口
 */
class UserCenter extends Common
{
    protected $noNeedLogin = ['shujuhuifu','getAnchorType','getRecharConfig','getExchangeConfig','getLevelExplain'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->userModel = new \app\common\model\User();
    }

    /**
     * 获取当前用户信息
     */
    public function getMyUserInfo() {
        $this->success("获取成功!",$this->auth->getUserinfo());
    }

    /**
     * 获取个人信息
     */
    public function getUserInfo() {
        $user_id = $this->request->request("user_id");
        if (!$user_id) {
            $this->error(__('Invalid parameters'));
        }
        // 获取基本信息
        $where = [];
        $where["id"] = $user_id;
        $userInfo = $this->userModel->field("id,nickname,pre_nickname,image,mobile,avatar,pre_avatar,gender,money,age,u_id,level,jewel,
        age_id,constellation_id,province_id,city_id,desc,ipaddress,is_cool,is_manager,is_stealth")->where($where)->find();
        $userInfo['nickname_status'] = $userInfo['avatar_status'] = 0;
        if (!empty($userInfo['pre_nickname']) && $userInfo['pre_nickname'] != $userInfo['nickname']) {
            $userInfo['nickname_status'] = 1;
        }
        if (!empty($userInfo['pre_avatar']) && $userInfo['pre_avatar'] != $userInfo['avatar']) {
            $userInfo['avatar_status'] = 1;
        }
        // 获取技能信息
        $skillList = Model("ViewUserSkill")->getSkillInfo($user_id);
        $userInfo["skill"] = implode("/",$skillList);
        // 获取关注粉丝信息
        $followModel = new \app\common\model\ViewFollows();
        $fansModel = new \app\common\model\ViewFans();
        // 获取关注信息
        $where = [];
        $where["user_id"] = $user_id;
        $userCount = $followModel->where($where)->value("follows"); //该用户关注了几个人
        $userInfo["follows_count"] = $userCount?$userCount:0;
        $userInfo["follows"] = $userInfo["follows_count"];//前端字段使用不一致添加
        // 获取粉丝数
        $where = [];
        $where["user_id"] = $user_id;
        $fansCount = $fansModel->where($where)->value("fans"); //该用户的粉丝数
        $userInfo["fans_count"] = $fansCount?$fansCount:0;
        $userInfo["fans"] = $userInfo["fans_count"];//前端字段使用不一致添加
        // 获取贵族信息
        $nobleInfo = $this->userModel->getUserNobleInfo($user_id);
        // 查看者是否已关注
        $followid = \app\common\model\UserFansFollow::where(["fans_id"=>$this->auth->id,"user_id"=>$user_id])->value("id");
        $userInfo["is_follow"] = $followid>0?1:0;

        $userInfo = json_decode(json_encode($userInfo),true);
        $userInfo = array_merge($userInfo,$nobleInfo);

        // 获取用户在派对直播间情况信息
        $redis = new Redis();
        $redisconfig = config("redis");
        $redis->connect($redisconfig["host"], $redisconfig["port"]);
        if ($redisconfig['redis_pwd']) {
            $redis->auth($redisconfig['redis_pwd']);
        }
        if($redisconfig['redis_selectdb'] > 0){
            $redis->select($redisconfig['redis_selectdb']);
        }
        $livingUserPartyId = $redis->hGet("livingUser", $user_id);

        $userInfo['party_info'] = json([]);
        if ($livingUserPartyId) {
            $party = \app\common\model\Party::where('id',$livingUserPartyId)->field('id,room_type')->find();
            $userInfo['party_info'] = ['party_id' => $party['id'], 'room_type' => $party['room_type']];
        }
        $blackWhere['user_id'] = $this->auth->id;
        $blackList = model('UserBlacklist')->where($blackWhere)->select();
        $blackIds = !empty($blackList) ? array_column($blackList,'black_user_id') : [];
        $userInfo['is_black'] = in_array($user_id,$blackIds) ? 1 : 0;

        $memberinfo = Db::name('guild_member')->alias('m')->field('m.id as `member_id`,m.user_id,guild.name,guild.image,guild.member,guild.desc')->join('guild','m.guild_id = guild.id','LEFT')->where(['m.user_id'=>$user_id,'m.status'=>1])->find();
        if ($memberinfo) {
            $userInfo['memberinfo'] = $memberinfo;
        }
        //家族信息
        $guildField = 'g.id,g.g_id,g.user_id,g.party_id,g.name,g.image,g.desc,g.member,g.status';
        $guildWhere['gm.user_id'] = $user_id;
        $guildWhere['g.status'] = 1;
        $guildInfo = model('Guild')->alias('g')->field($guildField)
            ->join('guild_member gm','gm.guild_id = g.id','LEFT')
            ->where($guildWhere)->order('id desc')->find();
        $userInfo['guild_info'] = !empty($guildInfo) ? $guildInfo : [];
        $guildStatus = -2;
        if (!empty($guildInfo)) {
            $guildStatus = (int)$guildInfo['status'];
        }
        $userInfo['guild_status'] = $guildStatus;//家族状态:公会状态:0=待审核,1=正常,-1=已解散,-2无公会
        //动态
        //技能
        //礼物
        $power = UserPower::where(['user_id'=>$user_id])->find();
        $userInfo['user_power'] = $power;
        //访客记录
        if ($this->auth->id != $user_id) {
            $visit_data = [
                'user_id' => $this->auth->id,
                'visit_user_id' => $user_id,
            ];
            $visit_check = Db::name('user_visitlist')->where($visit_data)->find();
            if(empty($visit_check)){
                $visit_data['updatetime'] = time();
                Db::name('user_visitlist')->insertGetId($visit_data);
            }else{
                Db::name('user_visitlist')->where('id',$visit_check['id'])->update(['updatetime'=>time()]);
            }
        }

        $this->success("获取成功!",$userInfo);
    }

    /**
     * 添加关注
     */
    public function addFollows() {
        $user_id = $this->request->request("user_id",0,"intval");// 被关注者ID
        $type = $this->request->request("type",1);// 类型:1=关注,2=取消关注
        if (!$user_id || $user_id<=0) {
            $this->error(__('Invalid parameters'));
        }
        if($type == 1) {
            if($user_id == $this->auth->id) {
                $this->error("不需要关注自己哦!");
            }
            $fansfollowModel = new \app\common\model\UserFansFollow();
            $data = [];
            $data["user_id"] = $user_id;
            $data["fans_id"] = $this->auth->id;
            if($fansfollowModel->where($data)->find()) {
                $this->error("你已经关注过ta啦!");
            }
            $data["createtime"] = time();
            $id = $fansfollowModel->insertGetId($data);

            //关注通知
            $msgdata = [
                'user_id'=>$user_id,
                'title'  => '有人刚刚关注了你',
                'content'=> '打开[消息][最新关注]即可查看',
                'createtime' => time(),
            ];
            Db::name('message')->insertGetId($msgdata);

            if($id > 0) {
                // 增加任务进度 +exp
                \app\common\model\TaskLog::tofinish($this->auth->id,"ebxLwnXj3L",1);
                // 增加任务进度 +exp
                \app\common\model\TaskLog::tofinish($this->auth->id,"iA1QgRhL",1);
                // 增加任务进度 +exp
                \app\common\model\TaskLog::tofinish($this->auth->id,"ghopE4Ou",1);
                // 增加任务进度 +exp
                \app\common\model\TaskLog::tofinish($this->auth->id,"TryNGc1x",1);

                $this->success("关注成功!");
            } else {
                $this->error("网络错误,请稍后重试!");
            }
        } else {
            $fansfollowModel = new \app\common\model\UserFansFollow();
            $where = [];
            $where["user_id"] = $user_id;
            $where["fans_id"] = $this->auth->id;
            $fansfollowInfo = $fansfollowModel->where($where)->find();
            if(!$fansfollowInfo) {
                $this->error("关注信息获取失败!");
            }

            $res = $fansfollowModel->where($where)->delete();
            if($res > 0) {
                $this->success("取消成功!");
            } else {
                $this->error("网络错误,请稍后重试!");
            }
        }

    }

    /**
     * 是否关注
     */
    public function isFollows() {
        $user_id = $this->request->request("user_id",0,"intval");// 关注者ID

        if (!$user_id || $user_id<=0) {
            $this->error(__('Invalid parameters'));
        }

        $fansfollowModel = new \app\common\model\UserFansFollow();
        $where = [];
        $where["user_id"] = $user_id;
        $where["fans_id"] = $this->auth->id;
        $fansfollowInfo = $fansfollowModel->where($where)->find();
        $data = [];
        if($fansfollowInfo) {
            $data["is_show_follow"] = 0;
        } else {
            $data["is_show_follow"] = 1;
        }
        $this->success("获取成功!",$data);

    }

    /**
     * 获取关注人列表.派对信息
     */
    public function getFollowsLive() {
        $is_online = $this->request->request("is_online");// 是否在线:1=直播中,0=未开播
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;

        $is_online == 1 || $is_online = 0;

        $fanfollowModel = new \app\common\model\UserFansFollow();
        $where = [];
        $where["a.fans_id"] = $this->auth->id;
        $where["p.room_type"] = 2;
        $where["p.is_online"] = $is_online;
        if($is_online == 1) {
            $field = "p.id as party_id,u.u_id,u.nickname,p.party_name,p.party_hot,p.party_logo,u.avatar,t.id as party_type";
        } else {
            $field = "p.id as party_id,a.user_id,u.avatar,u.gender,u.level,u.nickname,p.party_name,p.party_logo,t.id as party_type";
        }
        $list = $fanfollowModel->alias("a")
            ->field($field)
            ->join("hx_user u","u.id = a.user_id")
            ->join("hx_party p","p.user_id = a.user_id")
            ->join("hx_party_type t","t.id = p.party_type","left")
            ->limit($pageStart,$pageNum)
            ->where($where)->select();
        if($list) {
            foreach($list as $k => $v) {
                $mod = isset($v["party_type"])?intval($v["party_type"])%5:1;
                if(isset($v["type_name"]) && $v["type_name"]) {
                    $type_name = $v["type_name"];
                } else {
                    $type_name = "普通房";
                }
                $list[$k]["party_type"] = $type_name;
                $list[$k]["party_type_color"] = $mod == 0?5:$mod;
            }

            $this->success("获取成功!",$list);
        } else {
            $this->success("数据为空!",[]);
        }

    }

    /**
     * 获取关注列表
     * (个人中心模块)(消息-最新关注)
     */
    public function getFollowsUser() {
        $type = $this->request->request('type',1); // 1=关注,2=粉丝,3=好友
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;
        $pageEnd = $pageStart + $pageNum;

        $fanfollowModel = new \app\common\model\UserFansFollow();

        // 获取关注列表
        $where = [];
        $where["a.fans_id"] = $this->auth->id;
        $followlist = $fanfollowModel->alias("a")
            ->field("a.id,a.user_id,a.createtime,u.avatar,u.nickname,u.level,u.gender,u.desc")
            ->join("hx_user u","u.id = a.user_id")
//            ->limit($pageStart,$pageNum)
            ->where($where)->order('a.id desc')->select();
        $followlist = list_domain_image($followlist,['avatar']);

        // 获取粉丝列表
        $where = [];
        $where["a.user_id"] = $this->auth->id;
        $fanslist = $fanfollowModel->alias("a")
            ->field("a.id,a.fans_id,a.createtime,u.avatar,u.nickname,u.level,u.gender,u.desc")
            ->join("hx_user u","u.id = a.fans_id")
//            ->limit($pageStart,$pageNum)
            ->where($where)->order('a.id desc')->select();
        $fanslist = list_domain_image($fanslist,['avatar']);

//        print_r(json_encode($followlist));exit;
        if($type == 1) {
            $ids = [];
            if($fanslist) {
                foreach($fanslist as $k => $v) {
                    $ids[] = $v["fans_id"];
                }
            }
            if($followlist) {
                foreach($followlist as $k => $v) {
                    $followlist[$k]['createtime_text'] = get_last_time($v['createtime']);
                    $followlist[$k]["is_follow"] = 1;
                    if(in_array($v["user_id"],$ids)) {
                        $followlist[$k]["is_hu"] = 1;
                    } else {
                        $followlist[$k]["is_hu"] = 0;
                    }
                }
            }
            $fansfollow = $followlist;
        } elseif($type == 2) {
            $ids = [];
            if($followlist) {
                foreach($followlist as $k => $v) {
                    $ids[] = $v["user_id"];
                }
            }
            if($fanslist) {
                foreach($fanslist as $k => $v) {
                    $fanslist[$k]['createtime_text'] = get_last_time($v['createtime']);
                    if(in_array($v["fans_id"],$ids)) {
                        $fanslist[$k]["is_hu"] = 1;
                        $fanslist[$k]["is_follow"] = 1;
                    } else {
                        $fanslist[$k]["is_hu"] = 0;
                    }
                }
            }
            $fansfollow = $fanslist;
        }else {
            $ids = [];
            if($followlist) {
                foreach($followlist as $k => $v) {
                    $ids[] = $v["user_id"];
                }
            }
            if($fanslist) {
                foreach($fanslist as $k => $v) {
                    $fanslist[$k]['createtime_text'] = get_last_time($v['createtime']);
                    $fanslist[$k]["is_follow"] = 1;
                    if(in_array($v["fans_id"],$ids)) {
                        $fanslist[$k]["is_hu"] = 1;
                    } else {
                        unset($fanslist[$k]); //不是好友的 直接unset掉
                    }
                }
            }
            $fansfollow = $fanslist;
        }

        if($fansfollow) {
            $data = [];
            foreach($fansfollow as $k => $v) {
                if($k >= $pageStart && $k < $pageEnd) {
                    $data[] = $v;
                }
            }
            $this->success("获取成功!",$data);
        } else {
            $this->success("数据为空!",[]);
        }
    }

    /**
     * 获取最近访客
     * (消息)
     */
    public function getMyVisitList(){
        $list = Db::name('user_visitlist')->alias('uv')
            ->field('uv.user_id,uv.updatetime,user.id,user.nickname,user.avatar,user.gender,user.desc')
            ->join('user','uv.user_id = user.id','LEFT')
            ->where('uv.visit_user_id',$this->auth->id) //被访问者
            ->order('uv.id desc')->autopage()->select();
        $list = list_domain_image($list,['avatar']);

        if(!empty($list)){
            foreach($list as $key => &$val){
                //关注
                $val['is_follow'] = $this->is_follow($val['user_id'],$this->auth->id);
            }
        }

        $this->success(1,$list);
    }

    /**
     * 获取附近的人
     * (消息-同城)
     */
    public function getSamecityList(){

        if(!$this->auth->city_id){
            $this->success(1,[]);
        }

        $where = [
            'status' => 'normal',
            'city_id'=> $this->auth->city_id,
        ];

        //排除黑名单的
        $black_ids = Db::name('user_blacklist')->where('user_id',$this->auth->id)->column('black_user_id');
        if(!empty($black_ids)){
            $where['id'] = ['NOTIN',$black_ids];
        }

        $list = Db::name('user')->where($where)->where('id','neq',$this->auth->id)->field('id,nickname,avatar,gender,desc')->order('id desc')->autopage()->select();
        $list = list_domain_image($list,['avatar']);

        if(!empty($list)){
            foreach($list as $key => &$val){
                //关注
                $val['is_follow'] = $this->is_follow($val['id'],$this->auth->id);
            }
        }

        $this->success(1,$list);
    }

    //是否关注
    private function is_follow($user_id,$fans_id){
        $where = [
            'user_id' => $user_id,
            'fans_id' => $fans_id,
        ];
        $check = Db::name('user_fans_follow')->where($where)->find();
        if($check){
            return 1;
        }else{
            return 0;
        }
    }


    /**
     * 获取个人技能列表
     */
    public function getMySkillList() {
        $user_id = $this->request->request('user_id',0); // 用户ID
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        if ($user_id == -1) {
            $user_id = $this->auth->id;
        } elseif($user_id>0) {
            $user_id = intval($user_id);
        } else {
            $this->error(__('Invalid parameters'));
        }
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;
        $authModel = new \app\common\model\DispatchAuth();
        $where = [];
        $where["a.user_id"] = $user_id;
        $where["a.status"] = 1;
        $authskillList = $authModel->alias("a")
            ->field("a.id,ds.image,ds.name,a.voice,a.voice_time,a.price,a.is_main,ds.unit")
            ->join("hx_dispatch_skill ds","ds.id = a.skill_id")
            ->where($where)
            ->limit($pageStart,$pageNum)
            ->select();
        $this->success("获取成功!",$authskillList);
    }

    /**
     * 删除个人技能信息
     */
    public function delMySkillInfo() {
        $id = $this->request->request('id'); // 认证ID
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        $authModel = new \app\common\model\DispatchAuth();
        $where = [];
        $where["id"] = $id;
        $where["user_id"] = $this->auth->id;
        $authInfo = $authModel->where($where)->find();
        if(!$authInfo) $this->error("技能认证未找到");
//        if($authInfo->is_main == 1) $this->error("请先取消主技能,再删除!");

        Db::startTrans();
        try{
            $res1 = $authInfo->delete();
            $res2 = \app\common\model\UserSkill::where(["user_id"=>$this->auth->id,"skill_id"=>$authInfo->skill_id])->delete();
            if($res1 && $res2) {
                Db::commit();
                $this->success("删除成功!");
            } else {
                $this->error("网络错误,请稍后重试!");
            }
        }catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 修改个人技能信息
     */
    public function editMySkillInfo() {
        $price = $this->request->request('price'); // 价格
        $id = $this->request->request('id'); // 认证ID
        $is_main = $this->request->request('is_main'); // 是否设置为主技能
        if (!$id && !$price) {
            $this->error(__('Invalid parameters'));
        }
        $authModel = new \app\common\model\DispatchAuth();
        $where = [];
        $where["id"] = $id;
        if(!$authModel->where($where)->find()) $this->error("技能认证未找到");

        Db::startTrans();
        try{
            if($is_main == 1) {
                $where = [];
                $where["user_id"] = $this->auth->id;
                $authModel->update(["is_main"=>0],$where);
            }
            $where = [];
            $where["id"] = $id;
            $data = [];
            $data["price"] = $price;
            $data["is_main"] = $is_main;
            $res = $authModel->update($data,$where);

            $myAuthList = $authModel->where(["user_id"=>$this->auth->id,"is_main"=>1])->find();
            if(!$myAuthList) {
                $this->error("必须至少设置一个主技能");
                Db::rollback();
            }

            if($res) {
                Db::commit();
                $this->success("修改成功!",$data);
            } else {
                    $this->error("网络错误,请稍后重试!");
            }
        }catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 编辑个人信息(完善资料)
     */
    public function editUserInfo() {
        $avatar = $this->request->request('avatar'); // 头像
        $nickname = $this->request->request('nickname'); // 昵称
        $age = $this->request->request('age'); // 年龄
        $ageId = $this->request->request('age_id'); // 年龄段
        $gender = $this->request->request('gender'); // 性别 0=女,1=男
        $image = $this->request->request('image'); // 个人形象照
        $constellationId = $this->request->request('star_id'); //星座ID
        $provinceId = $this->request->request('province_id'); //省ID
        $cityId = $this->request->request('city_id'); //城市ID
        $desc = $this->request->request('desc'); //个性签名
        /*if (!$avatar && !$nickname && !$age && !$image && !in_array($gender,[0,1])) {
            $this->error(__('请输入要修改的信息'));
        }*/

        $where = [];
        $where["id"] = $this->auth->id;
        $data = [];
        $avatar && $data["avatar"] = $avatar;

        if($nickname){
            if (mb_strlen($nickname) > 30) {
                $this->error('用户昵称最多支持30个汉字或组合');
            }
            $data["nickname"] = $nickname;
        }
        $gender && $data["gender"] = $gender;
        $age && $data["age"] = $age;
        $image && $data["image"] = $image;
        $ageId && $data['age_id'] = $ageId;
        $constellationId && $data['constellation_id'] = $constellationId;
        $provinceId && $data['province_id'] = $provinceId;
        $cityId && $data['city_id'] = $cityId;
        $desc && $data['desc'] = $desc;
        $res = $this->userModel->update($data,$where);
        if($res) {
            $user = $this->userModel->where($where)->find();
            if (!empty($user['nickname']) && !empty($user['avatar']) && !empty($user['age_id']) && $user['has_info']==0) {
                $data['has_info'] = 1;
                $this->userModel->update($data,$where);
            }
            $this->success("修改成功!");
        } else {
            $this->error("网络错误,请稍后重试!");
        }
    }
    /**
     * 编辑个人信息(修改昵称和头像需要后台审核)
     */
    public function editUser() {
        $avatar = $this->request->request('avatar'); // 头像
        $nickname = $this->request->request('nickname'); // 昵称
        if (!$avatar && !$nickname) {
            $this->error(__('请输入要修改的信息'));
        }

        $data = [];
        if ($avatar && $avatar != $this->auth->avatar) {
            $data["pre_avatar"] = $avatar;
        }
        if($nickname && $nickname != $this->auth->nickname){
            if (mb_strlen($nickname) > 8) {
                $this->error('用户昵称最多支持8个汉字或组合');
            }
            $data["pre_nickname"] = $nickname;
        }
        if (!empty($data)) {
            $where["id"] = $this->auth->id;
            $res = $this->userModel->update($data,$where);
            if(!$res) {
                $this->error("网络错误,请稍后重试!");
            }
        }
        $this->success("修改成功!");
    }
    /**
     * 主播申请
     */
    public function anchorApply() {
        $type_id = $this->request->request('type_id',0); // 技能分类ID
        $party_type_id = $this->request->request('party_type_id'); //分类ID
        $desc = $this->request->request('desc'); // 申请备注
        if (!$party_type_id && !$desc) {
            $this->error(__('Invalid parameters'));
        }
        $useranchorModel = new \app\common\model\UserAnchor();
        $data = [];
        $data["user_id"] = $this->auth->id;
        $data["type_id"] = $type_id;
        $data["party_type_id"] = $party_type_id;
        if($useranchorModel->where($data)->find()) $this->error(__('您已申请过该类型的主播,请勿重复申请!'));
        $data["desc"] = $desc;
        $data["createtime"] = time();
        $res = $useranchorModel->insertGetId($data);
        if($res) {
            \app\common\model\User::update(["is_anchor"=>1],["id"=>$this->auth->id]);
            $this->success("申请发送成功!");
        } else {
            $this->error("网络错误,请稍后重试");
        }
    }

    /**
     * 实名认证
     */
    public function authApply() {
        $realname = $this->request->request('realname'); // 真实姓名
        $idcard = $this->request->request('idcard'); // 身份证号
        $zimage = $this->request->request('zimage'); // 身份证正面照
        $fimage = $this->request->request('fimage'); // 身份证反面照
        if (!$realname && !$idcard && !$zimage && !$fimage) {
            $this->error(__('Invalid parameters'));
        }
        $userauthModel = new \app\common\model\UserAuth();
        $data = [];
        $data["user_id"] = $this->auth->id;
        //$data["idcard"] = $idcard;
        $userAuth = $userauthModel->where($data)->find();
        if (!empty($userAuth)) {
            if(in_array($userAuth['status'],[0,1])) $this->error('您已经申请过了,请勿重复操作!');
        }
        
        // 测试需要 开始
        $data["realname"] = $realname;
        $zimage && $data["zimage"] = $zimage;
        $fimage && $data["fimage"] = $fimage;
        $data["status"] = 1;
        if (!empty($userAuth)) {
            $data["updatetime"] = time();
            $authWhere['user_id'] = $this->auth->id;
            $res = $userauthModel->where($authWhere)->update($data);
        } else {
            $data["createtime"] = time();
            $res = $userauthModel->insertGetId($data);
        }
        if($res) {
            \app\common\model\User::update(["is_auth"=>2],["id"=>$this->auth->id]);
            $this->success("恭喜,实名认证成功!");
        } else {
            $this->error("网络错误,请稍后重试");
        }
        // 测试需要 结束

        // 实名认证验证
        $configInfo = config("auth");
        $outh = new outh($configInfo["api_url"],$configInfo["customer_code"],$configInfo["private_key"],$configInfo["key"]);

        $out_trade_no = date("YmdHis").rand(1000,9999);
        $ret = $outh->toVerify($out_trade_no,$realname,$idcard);

        if(isset($ret["code"])) {
           if($ret["code"] == "1008") {
               $this->error(__('身份证格式错误'));
           }
            if($ret["code"] == "1009") {
                $this->error(__('身份证格式错误'));
            }
            if($ret["code"] == "0001") {
                $this->error(__('姓名和身份证号不匹配!'));
            }
            if($ret["code"] == "0000") {
                $data["realname"] = $realname;
                $zimage && $data["zimage"] = $zimage;
                $fimage && $data["fimage"] = $fimage;
                $data["status"] = 1;
                $data["createtime"] = time();
                $res = $userauthModel->insertGetId($data);
                if($res) {
                    \app\common\model\User::update(["is_auth"=>2],["id"=>$this->auth->id]);
                    $this->success("恭喜,实名认证成功!");
                } else {
                    $this->error("网络错误,请稍后重试");
                }
            }
        } else {
            $this->error("网络错误,请稍后重试");
        }

    }

    /**
     * 获取主播分类
     */
    public function getAnchorType() {
        $this->success("获取成功!",\app\common\model\UserAnchorType::select());
    }

    /**
     * 加入黑名单
     */
    public function addBlacklist() {
        Db::startTrans();
        try {
            $black_user_id = $this->request->request('black_user_id'); // 黑名单用户ID
            if (!$black_user_id) {
                throw new Exception(__('Invalid parameters'));
            }
            $userblacklistModel = new \app\common\model\UserBlacklist();
            $data = [];
            $data["user_id"] = $this->auth->id;
            $data["black_user_id"] = $black_user_id;
            if($userblacklistModel->where($data)->find()) $this->error(__('已在黑名单!'));
            $data["createtime"] = time();
            $res = $userblacklistModel->insertGetId($data);
            if(!$res) {
                throw new Exception("网络错误,请稍后重试");
            }
            //im加入黑名单
            $tenimService = new TenimService();
            $params = [
                'user_id' => $this->auth->id,
                'black_user_ids' => [(string)$black_user_id],
            ];
            $imResult = $tenimService->addBlack($params);
            if (!$imResult['status']) {
                throw new Exception($imResult['msg']);
            }
            Db::commit();
            $this->success("加入成功!");
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取黑名单用户
     */
    public function getBlacklist() {
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;
        $userblacklistModel = new \app\common\model\UserBlacklist();// ->limit($pageStart,$pageNum)
        $where = [];
        $where["a.user_id"] = $this->auth->id;
        $list = $userblacklistModel->alias("a")
            ->field("a.id,a.black_user_id,u.avatar,u.nickname,u.level,u.gender")
            ->join("hx_user u","u.id = a.black_user_id")
            ->where($where)
            ->limit($pageStart,$pageNum)
            ->select();
        if($list) {
            $this->success("获取成功!",$list);
        } else {
            $this->success("数据为空",[]);
        }
    }

    /**
     * 移除用户黑名单
     */
    public function removeUserBlack() {
        Db::startTrans();
        try {
            $id = $this->request->request('id'); // 黑名单ID
            $userId = $this->request->request('user_id'); // 用户ID
            if (!$id && !$userId) {
                throw new Exception(__('Invalid parameters'));
            }

            $userblacklistModel = new \app\common\model\UserBlacklist();
            $where = [];
            $id && $where["id"] = $id;
            if ($userId) {
                $where['user_id'] = $this->auth->id;
                $where['black_user_id'] = $userId;
            }
            $userBlack = $userblacklistModel->where($where)->find();
            if (empty($userBlack)) {
                throw new Exception('未找到黑名单信息');
            }
            $blackUserId = isset($userBlack['black_user_id']) ? $userBlack['black_user_id'] : 0;
            $res = false;
            if (!empty($userBlack)) {
                $res = $userblacklistModel->where($where)->delete();
            }
            if(!$res) {
                $this->error("网络错误,请稍后重试!");
            }
            //im加入黑名单
            if (!empty($blackUserId)) {
                $tenimService = new TenimService();
                $params = [
                    'user_id' => $this->auth->id,
                    'black_user_ids' => [(string)$blackUserId],
                ];
                $imResult = $tenimService->delBlack($params);
                if (!$imResult['status']) {
                    throw new Exception($imResult['msg']);
                }
            }
            Db::commit();
            $this->success("移除成功!",$res);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 举报用户
     */
    /*public function addReport() {
        $ruser_id = $this->request->request('ruser_id'); // 被举报用户ID
        $content = $this->request->request('content'); // 举报内容
        $image = $this->request->request('image'); // 图片描述(多个用半角逗号隔开)
        if (!$ruser_id) {
            $this->error(__('Invalid parameters'));
        }

        $userreportModel = new \app\common\model\UserReport();
        $data = [];
        $data["user_id"] = $this->auth->id;
        $data["reportable_id"] = $ruser_id;
        $data['reportable_type'] = $this->getModelName('user');
        $data["content"] = $content;
        $data["image"] = $image;
        $data["createtime"] = time();
        $res = $userreportModel->insertGetId($data);
        if($res) {
            $this->success("举报成功!");
        } else {
            $this->error("网络错误,请稍后重试");
        }
    }*/

    /**
     * 举报
     */
    /*public function addReportNew() {
        $params = $this->request->param();
        $validate = new Report();
        $result = $validate->check($params);
        if (!$result) {
            $this->error($validate->getError());
        }

        $userreportModel = new \app\common\model\UserReport();
        $data = [];
        $data["user_id"] = $this->auth->id;
        $data["reportable_id"] = $params['reportable_id'];

        $data['reportable_type'] = $this->getModelName($params['reportable_type']);
        $data["content"] = $params['content'];
        $data["image"] = $params['image'];
        $data["createtime"] = time();
        $res = $userreportModel->insertGetId($data);
        if($res) {
            $this->success("举报成功!");
        } else {
            $this->error("网络错误,请稍后重试");
        }
    }*/

    /**
     * redis 数据恢复---非redis数据丢失请勿使用!!!!
     */
    public function shujuhuifu() {
        $key = $this->request->request("key");// 操作验证 123456
        if($key != 123456) {
            $this->error(__('Invalid parameters'));
        }
        $giftuserpartyModel = new \app\common\model\GiftUserParty();
        $redis = new Redis();
        $redisconfig = config("redis");
        $redis->connect($redisconfig["host"], $redisconfig["port"]);
        if ($redisconfig['redis_pwd']) {
            $redis->auth($redisconfig['redis_pwd']);
        }
        if($redisconfig['redis_selectdb'] > 0){
            $redis->select($redisconfig['redis_selectdb']);
        }

        // 获取本周第一天
        $weekday = $this->firstOfWeek(date("Y-m-d H:i:s"));
        // 获取本月第一天
        $monthday = date("Ym01");
        $where = [];
        $where["createtime"] = ["gt",strtotime($weekday)];
        $list1 = $giftuserpartyModel->where($where)->select();

        foreach($list1 as $k => $v) {
            // 添加redis记录做财富排行榜周榜用
            $redis->zIncrBy("jewel_get_".$v["party_id"].":".$weekday,$v["value"],$v["user_to_id"]);
            // 添加redis记录做贡献排行榜周榜用
            $redis->zIncrBy("jewel_to_".$v["party_id"].":".$weekday,$v["value"],$v["user_id"]);
        }

        $where = [];
        $where["createtime"] = ["gt",strtotime(date("Y-m-01"))];
        $list2 = $giftuserpartyModel->where($where)->select();

        foreach($list2 as $k => $v) {
            // 添加redis记录做财富排行榜月榜用
            $redis->zIncrBy("jewel_get_".$v["party_id"].":".$monthday,$v["value"],$v["user_to_id"]);
            // 添加redis记录做贡献排行榜月榜用
            $redis->zIncrBy("jewel_to_".$v["party_id"].":".$monthday,$v["value"],$v["user_id"]);
        }
        $this->success("执行成功!");
    }

    /**
     * 获取用户钻石余额
     */
    public function getUserJewel() {
        $data = \app\common\model\User::field("Jewel,money")->where(["id"=>$this->auth->id])->find();
        return $this->success("获取成功!",$data);
    }

    /**
     * 获取用户等级说明
     */
    public function getLevelExplain() {
        $data = \app\common\model\UserLevelExplain::field("title,content")->select();
        return $this->success("获取成功!",$data);
    }

    /**
     * 获取用户等级信息
     */
    public function getUserLevelInfo() {
        $res = [];$exstart = 0;$exend = 0;
        $userModel = new \app\common\model\User();
        $userInfo = $userModel->field("id,nickname,avatar,level,empirical")->where(["id"=>$this->auth->id])->find();
        if(!$userInfo) {
            $this->error("用户信息获取失败!");
        }
        $res["avatar"] = $userInfo['avatar'];
        $res["nickname"] = $userInfo['nickname'];

        // 获取用户当前经验值对应等级
        $userconfigModel = new \app\common\model\UserLevelConfig();
        $where = [];
        $where["empirical"] = ["elt",$userInfo["empirical"]];
        $userexplainstart = $userconfigModel->where($where)->order("empirical","desc")->limit(1)->select();
        $where = [];
        $where["empirical"] = ["gt",$userInfo["empirical"]];
        $userexplainend = $userconfigModel->where($where)->order("empirical","asc")->limit(1)->select();
        if(!$userexplainstart && !$userexplainend) {
            $this->error("经验等级信息获取失败!");
        } elseif(!$userexplainstart && $userexplainend) {
            $res["level_start"] = 0;
            $res["level_end"] = $userexplainend[0]["level"];
        } elseif($userexplainstart && !$userexplainend) {
            $res["level_start"] = $userexplainstart[0]["level"];
            $res["level_end"] = $userexplainstart[0]["level"];
        } elseif($userexplainstart && $userexplainend) {
            $res["level_start"] = $userexplainstart[0]["level"];
            $res["level_end"] = $userexplainend[0]["level"];
        }
        $userexplainstart && $exstart = $userexplainstart[0]["empirical"];
        $userexplainend && $exend = $userexplainend[0]["empirical"];
        $r1 = $exend-$exstart; // 等级经验值差
        $r2 = $userInfo["empirical"]-$exstart; // 当前等级与最低等级经验值差
        $r3 = $exend-$userInfo["empirical"]; // 还需多少经验值升级
        if($r1 == 0) {
            $res["level_rate"] = 1;
        } elseif($r2 == 0) {
            $res["level_rate"] = 0;
            if($res["level_start"] == $res["level_end"]) {
                $res["level_rate"] = 1;
            }
        } else {
            $res["level_rate"] = intval(($r2/$r1)*100)/100;
        }
        $res["to_up_need"] = $r3>0?$r3:0;

//        // 满级
//        if($r3 == 0 && !$userexplainend) {
//            $res["level_rate"] = 1;
//        }

        $this->success("获取成功!",$res);
    }

    /**
     * 邀请
     * @return void
     */
    public function addInvite()
    {
        try {
            $inviteNo = $this->request->param('invite_no','');
            $userId = $this->auth->id;
            if (empty($inviteNo)) {
                throw new Exception('参数错误');
            }
            $where['invite_no'] = $inviteNo;
            $userField = 'id,invite_no,pre_userid';
            $user = model('User')->field($userField)->where($where)->find();
            if (empty($user)) {
                throw new Exception('无效的邀请码');
            }
            //判断邀请码用户不能是自己的下级
            if ($user['pre_userid'] == $userId) {
                throw new Exception('对方已被您邀请过');
            }
            $userInviteWhere['invite_user_id'] = $userId;
            $userInvite = model('UserInvite')->where($userInviteWhere)->find();
            if (!empty($userInvite)) {
                throw new Exception('您已经被邀请过');
            }
            $userInviteData = [
                'user_id' => $user['id'],
                'invite_user_id' => $userId,
                'createtime' => time(),
            ];
            $userInviteRes = model('UserInvite')->insertGetId($userInviteData);
            if (!$userInviteRes) {
                throw new Exception('邀请失败');
            }
            $userUpWhere['id'] = $userId;
            $userUpdate = ['pre_userid'=>$user['id']];
            $userUpdateRes = model('User')->where($userUpWhere)->update($userUpdate);
            if (!$userUpdateRes) {
                throw new Exception('更新邀请人失败');
            }
            $this->success('邀请成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
    
    /**
     * 邀请详情
     * @return void
     */
    public function inviteInfo()
    {
        try {
            $userId = $this->auth->id;
            $field = 'id,invite_no';
            $where['id'] = $userId;
            $user = model('User')->field($field)->where($where)->find();
            $inviteNo = isset($user['invite_no']) ? $user['invite_no'] : '';
            $todayNow = day_now();
            $todayStart = $todayNow[0];
            $todayEnd = $todayNow[1]+1;
            $userMoneyLogWhere['user_id'] = $userId;
            $userMoneyLogWhere['type'] = 103;
            $appendWhere['createtime'] = [['egt', $todayStart],['lt', $todayEnd],'and'];
            $todayMoney = model('UserMoneyLog')->where($userMoneyLogWhere)->where($appendWhere)->sum('value');
            $totalMoney = model('UserMoneyLog')->where($userMoneyLogWhere)->sum('value');
            //本周
            $weekNow = week_now();
            $userInviteWhere['user_id'] = $userId;
            $userInviteAppendWhere['createtime'] = [['egt', $weekNow[0]],['lt', $weekNow[1]+1],'and'];
            $userInviteModel = model('UserInvite');
            $weekNowNum = $userInviteModel->where($userInviteWhere)->where($userInviteAppendWhere)->count();
            //上周
            $lastWeek = last_week();
            $appendLastWhere['createtime'] = [['egt', $lastWeek[0]],['lt', $lastWeek[1]+1],'and'];
            $lastWeekNum = $userInviteModel->where($userInviteWhere)->where($appendLastWhere)->count();
            //全部
            $totalNum = $userInviteModel->where($userInviteWhere)->count();
            $inviteMoney = config('site.invite_money');
            $inviteRule = config('site.invite_rule');
            $result = [
                'invite_money' => (int)$inviteMoney,
                'invite_no' => $inviteNo,//邀请码
                'today_money' => $todayMoney,//今日收益
                'total_money' => $totalMoney,//总收益
                'week_now_num' => $weekNowNum,//本周邀请数
                'last_week_num' => $lastWeekNum,//上周邀请数
                'total_num' => $totalNum,//总邀请数
                'invite_rule' => $inviteRule,//规则说明
            ];
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 邀请列表
     * @return void
     */
    public function inviteList()
    {
        try {
            $userId = $this->auth->id;
            $where['user_id'] = $userId;
            $userInvite = model('UserInvite')->where($where)->with(['user'=>function($uQuery){
                $uQuery->field('id,avatar,u_id,nickname');
            }])->autopage()->order('createtime desc')->select();
            $result = [];
            if (!empty($userInvite)) {
                foreach ($userInvite as $key => $value) {
                    $user = isset($value['user']) ? $value['user'] : [];
                    $temp = [
                        'user_id'          => isset($user['id']) ? $user['id'] : 0,
                        'u_id'             => isset($user['u_id']) ? $user['u_id'] : 0,
                        'avatar'           => isset($user['avatar']) ? $user['avatar'] : 0,
                        'nickname'         => isset($user['nickname']) ? $user['nickname'] : 0,
                        'create_time_text' => !empty($value['createtime']) ? date('Y-m-d', $value['createtime']) : '',
                    ];
                    $result[] = $temp;
                }
            }

            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
    
    /**
     * 钻石兑换记录
     * @return void
     */
    public function exchangeList()
    {
        try {
            $field = 'id,sound_coin,createtime';
            $where['user_id'] = $this->auth->id;
            $result = model('UserExchangeLog')->field($field)->where($where)->autopage()->order('createtime desc')->select();
            if (!empty($result)) {
                foreach ($result as $key => &$value) {
                    $value['jewel'] = '+'.$value['sound_coin'];
                    $value['createtime'] = !empty($value['createtime']) ? date('Y-m-d H:i',$value['createtime']) : '';
                    unset($value['sound_coin']);
                }
            }
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 钻石充值记录
     * @return void
     */
    public function rechargeList()
    {
        try {
            $field = 'id,detail,mode,value,createtime';
            $where['user_id'] = $this->auth->id;
            $result = model('UserJewelLog')->field($field)->where($where)->autopage()->order('createtime desc')->select();
            if (!empty($result)) {
                foreach ($result as $key => &$value) {
                    $value['value'] = $value['mode'].$value['value'];
                    $value['createtime'] = !empty($value['createtime']) ? date('Y-m-d H:i',$value['createtime']) : '';
                }
            }
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 提现配置列表
     * @return void
     */
    public function withdrawalConfigList()
    {
        try {
            $field = 'id,money,real_money';
            $result = model('WithdrawalConfig')->field($field)->autopage()->order('weigh asc')->select();
            if (!empty($result)) {
                //设置是否使用自定义
                $withdrawDefine = config('site.withdraw_define');
                if ($withdrawDefine == 1) {
                    $fieldArr = [[
                        'id' => -1,
                        'money' => 0,
                        'real_money' => 0.00,
                    ],];
                    $result = array_merge($result,$fieldArr);
                }
            }
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 提现
     * @return void
     */
    public function withdrawal()
    {
        Db::startTrans();
        try {
            $withdrawConfigId = $this->request->param('id',0);
            $money = $this->request->param('money',0.00);
            $type = $this->request->param('type',0);
            $userId = $this->auth->id;
            $isAnchor = $this->auth->is_anchor;
            $userMoney = $this->auth->money;
            if (empty($withdrawConfigId) && empty($money)) {
                throw new Exception('参数错误');
            }
            //只有主播可以提现
            if ($isAnchor != 2) {
                throw new Exception('您不是主播不允许提现');
            }
            if ($this->auth->power->withdraw == 1) {
                throw new Exception('您已被禁止提现');
            }
            //验证提现类型
            $withdrawTypeConfig = config('wallet.withdraw_type');
            $typeIds = array_keys($withdrawTypeConfig);
            if (!in_array($type,$typeIds)) {
                throw new Exception('未知的提现类型');
            }
            $typeStr = isset($withdrawTypeConfig[$type]) ? $withdrawTypeConfig[$type] : '';
            $withdrawRateConfig = config('site.withdrawRate');//用户获取的金额比例(需要/100)
            $withdrawRate = bcdiv($withdrawRateConfig,100,2);
            if (!empty($money)) {//自定义金额
                if ($money <= 0) {
                    throw new Exception('金额有误');
                }
                $inputMoney = $money;
                $moneys = bcmul($money,$withdrawRate,2);
                $platformMoney = bcsub($money,$moneys,2);
            } else {//提现配置
                $where['id'] = $withdrawConfigId;
                $withdrawalConfig = model('WithdrawalConfig')->where($where)->find();
                if (empty($withdrawalConfig)) {
                    throw new Exception('未知的配置信息');
                }
                $inputMoney = $withdrawalConfig['money'];
                $moneys = $withdrawalConfig['money'];
                $platformMoney = bcsub($moneys,$withdrawalConfig['real_money'],2);;
            }
            if ($moneys <= 0) {
                throw new Exception('申请金额异常');
            }
            //扣减余额 记录余额日志
            $walletRes = model('wallet')->lockChangeAccountRemain($userId, $inputMoney, '-', $userMoney, '申请提现', 104,'money');
            if (!$walletRes['status']) {
                throw new Exception($walletRes['msg']);
            }
            $account = $name = '';
            if ($type == 1) {//微信
                $account = '';
                $name = '';
            } elseif ($type == 2) {//支付宝
                $userAlipayWhere['user_id'] = $userId;
                $userAlipay = model('UserAlipay')->where($userAlipayWhere)->find();
                if (empty($userAlipay)) {
                    throw new Exception('请绑定支付宝');
                }
                $account = $userAlipay['pay_no'];
                $name = $userAlipay['realname'];
            } elseif ($type == 3) {//银行
                $userBankWhere['user_id'] = $userId;
                $userBank = model('UserBank')->where($userBankWhere)->find();
                if (empty($userBank)) {
                    throw new Exception('请绑定银行卡');
                }
                $account = $userBank['bank_no'];
                $name = $userBank['realname'];
            }
            $data = [
                'user_id'       => $userId,//用户ID
                'money'         => $inputMoney,//金额
                'handingfee'    => $platformMoney,//手续费
                'real_money'    => bcsub($inputMoney,$platformMoney,2),//金额
                'taxes'         => 0.00,//税费
                'type'          => $typeStr,//类型
                'account'       => $account,//提现账户
                'name'          => $name,//真实姓名
                //'memo'          => '',//备注
                //'orderid'       => '',//订单号
                //'transactionid' => '',//流水号
                'status'        => 'created',//状态:created=申请中,successed=成功,rejected=已拒绝
                //'transfertime'  => '',//转账时间
                'createtime'    => time(),//添加时间
            ];
            $withdrawRes = model('Withdraw')->insertGetId($data);
            if (!$withdrawRes) {
                throw new Exception('提现失败');
            }
            Db::commit();
            $this->success('操作成功待审核');
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 提现列表
     * @return void
     */
    public function withdrawalList()
    {
        try {
            $field = 'id,money,type,status,createtime,transfertime';
            $where=[];
            $where['user_id'] = $this->auth->id;
            //$where['status'] = 'successed';//状态:created=申请中,successed=成功,rejected=已拒绝
            $result = model('Withdraw')->field($field)->where($where)->autopage()->order('createtime desc')->select();
            if (!empty($result)) {
                foreach ($result as $key => &$value) {
                    $value['money'] = '-'.$value['money'];
                    $value['createtime'] = !empty($value['createtime']) ? date('Y-m-d H:i', $value['createtime']) : '';
                    $value['transfertime'] = !empty($value['transfertime']) ? date('Y-m-d H:i', $value['transfertime']) : '';
                }
            }
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}