<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;
use think\Db;
use think\Cache;
use Redis;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','onLogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'login')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {

            $ret = $this->auth->register($mobile, Random::alnum(), $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'login');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }


    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 运营商一键登录
     */
    public function onLogin() {
        $token = $this->request->param('token');// 易盾返回的token
        // 判断登录token是否有效
        if (!$token) {
            //如果token为空就返回
            $this->error('token不能为空,请重试');
        } else {
            //调用getPhone方法并且将token传给getPhone
            $res = $this->getPhone($token);
            //如果返回的状态为1说明是注册过的用户
            if ($res['state'] == 1) {
                $phone = $res['phone'];
                // 用户登录逻辑 === 开始
                $userModel = new \app\common\model\User();
                $auth = \app\common\library\Auth::instance();

                $userInfo = $userModel->where(["mobile"=>$phone])->find();

                // 判断用户是否已经存在
                if($userInfo) { // 登录
                    $user = \app\common\model\User::get($userInfo["id"]);
                    if (!$user) {
                        $this->error("网络错误!请稍后重试");
                    }
                    $user->save(["logintime"=>time()]);
                    $res_login = $auth->direct($user->id);
                } else { // 注册
                    // 先随机一个用户名,随后再变更为u+数字id
                    $username = Random::alnum(20);
                    $password = Random::alnum(6);

                    // 获取默认头像和昵称
                    $nickname = array_column(\app\admin\model\website\Nickname::select(),'content');
                    $avatar = array_column(\app\admin\model\website\Avatar::select(),'content');
                    $extend = [
                        'nickname'=>$nickname[rand(0,count($nickname)-1)],
                        'avatar'=>$avatar[rand(0,count($avatar)-1)],
                        "mobile"=>$phone
                    ];

                    Db::startTrans();
                    try {
                        // 默认注册一个会员
                        $result = $auth->register($username, $password, "", $extend);

                        if (!$result) {
                            return false;
                        }
                        $user = $auth->getUser();
                        $fields = ['username' => 'u' . $user->id];

                        // 更新会员资料
                        $user = \app\common\model\User::get($user->id);
                        $user->save($fields);

                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $auth->logout();
                        return false;
                    }

                    // 写入登录Cookies和Token
                    $res_login = $auth->direct($user->id);
                }
                $userInfo = $auth->getUserinfo();
                if($res_login) {
                    $this->success("登录成功!",['userinfo' => $userInfo]);
                } else {
                    $this->error("登录失败!");
                }
                // 用户登录逻辑 === 结束
            } else {
                //如果没有注册过就返回注册状态
                $this->error($res['msg']);
            }
        }
    }


    /*
     * 根据token换取手机号码
     */
    public function getPhone($token) {
        $config = config('onLogin');
        AlibabaCloud::accessKeyClient($config['phone_access_key'], $config['phone_access_secret'])
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dypnsapi')
                ->scheme('https')// https | http
                ->version('2017-05-25')
                ->action('GetMobile')
                ->method('POST')
                ->host('dypnsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'AccessToken' => $token
                    ],
                ])
                ->request();

            // 将返回的结果转化为数组
            $result = $result->toArray();
            //判断当前数组不为空
            if (isset($result['GetMobileResultDTO']['Mobile'])) {
                // token不为空返回手机号码
                $phone = $result['GetMobileResultDTO']['Mobile'];
                $res = [
                    'state' => 1,
                    'phone' => $phone
                ];
                return $res;
            } else {
                //如果token为空
                $res = [
                    'state' => 0,
                    'msg' => 'token无效'
                ];
                return $res;
            }

        } catch (ClientException $e) {//有异常就抛出异常
            // 客户端错误
            $res = [
                'state' => 101,
                'msg' => '注册失败'
            ];
            return $res;
        } catch (ServerException $e) {
            // 服务端错误
            $res = [
                'state' => 101,
                'msg' => '注册失败'
            ];
            return $res;
        }
    }


    /**
     * 修改会员个人信息
     * 头像,昵称,性别,
     */
    public function userAvatar()
    {
        $user = $this->auth->getUser();
        $gender = $this->request->request('gender'); // 性别:1=男,-1=女
        $nickname_auth = $this->request->request('nickname');
        $avatar_auth = $this->request->request('avatar');
        if (!$gender && !$nickname_auth && !$avatar_auth) $this->error('参数为空!');
        // 随机获取昵称和头像
        if(!$user->nickname && !$nickname_auth) {
            $nicknameList = \app\admin\model\website\Nickname::select();//得到总条数
            $nicknameArr = [];
            if($nicknameList) foreach($nicknameList as $k => $v) {
                $nicknameArr[] = $v['content'];
            }
            $user->nickname = $nicknameArr[array_rand($nicknameArr,1)];
        }

        if(!$user->avatar && !$avatar_auth) {
            $avatarList = \app\admin\model\website\Avatar::select();//得到总条数
            $avatarArr = [];
            if($avatarList) foreach($avatarList as $k => $v) {
                $avatarArr[] = $v['content'];
            }
            $user->avatar = $avatarArr[array_rand($avatarArr,1)];
        }

        Db::startTrans();
        try {
            $res1 = true;
            if ($nickname_auth) {
                if($nickname_auth == $user->nickname) {
                    $this->error(__('与原昵称相同无需修改!'));
                }
                $user->nickname_auth = $nickname_auth;
                // 添加昵称修改申请表
                if(\app\common\model\NicknameAuth::where(["status"=>0,"user_id"=>$this->auth->id])->find()) $this->error("昵称已在审核中!请勿重复申请");
                $data = [];
                $data['user_id'] = $this->auth->id;
                $data['nickname'] = $nickname_auth;
                $data['old_nickname'] = $user->nickname;
                $data['createtime'] = time();
                $res1 = \app\common\model\NicknameAuth::insert($data);
            }
            if($avatar_auth) {
                $user->avatar_auth = $avatar_auth;
                // 添加头像修改申请表
                if(\app\common\model\AvatarAuth::where(["status"=>0,"user_id"=>$this->auth->id])->find()) $this->error("头像已在审核中!请勿重复申请");
                $data = [];
                $data['user_id'] = $this->auth->id;
                $data['avatar'] = $avatar_auth;
                $data['old_avatar'] = $user->avatar;
                $data['createtime'] = time();
                $res1 = \app\common\model\AvatarAuth::insert($data);
            }
            $gender && $user->gender = $gender;
            $res2 = $user->save();
            if($res1 && $res2 !== false) {
                Db::commit();
                delUserInfo($this->auth->id);
                $this->success("修改成功!昵称审核中");
            }

        } catch (PDOException $e) {
            Db::rollback();
            $this->error("修改失败!");
        }

    }

    /**
     * 修改会员个人信息
     * 城市,年龄,收入
     */
    public function userCity() {
        $user = $this->auth->getUser();
        $province = $this->request->request('province'); // 省
        $city = $this->request->request('city'); // 市
        $district = $this->request->request('district'); // 区
        $birthday = $this->request->request('birthday');
        $age = $this->request->request('age');
        $constellation = $this->request->request('constellation'); // 星座
        $income = $this->request->request('income');

        if ((!$province || !$city || !$district) && $age < 3 && !$income) $this->error('年龄太小了哦!');

        $province && $user->province = $province;
        $city && $user->city = $city;
        $district && $user->district = $district;
        $province && $user->province_name = \app\common\model\Area::getNameFromId($province);
        $city && $user->city_name = \app\common\model\Area::getNameFromId($city);
        $district && $user->district_name = \app\common\model\Area::getNameFromId($district);
        $age >= 3 && $user->age = $age;
        $constellation && $user->constellation = $constellation;
        $birthday && $user->birthday = $birthday;
        $income && $user->income = $income;
        $user->save();
        delUserInfo($this->auth->id);
        $this->success("修改成功!");
    }

    /**
     * 修改会员个人信息
     * 期望对象
     */
    public function userExpect() {
        $user = $this->auth->getUser();
        $expect = $this->request->request('expect'); // 期望对象,格式:1,2,3
        if (!$expect) $this->error('参数为空!');

        $user->expect_ids = $expect;
        $user->save();
        delUserInfo($user->id);
        $this->success("修改成功!");
    }

    /**
     * 修改会员个人信息
     * 最后登录的经纬度
     */
    public function userLnglat() {
        $user = $this->auth->getUser();
        $lng = $this->request->request('lng'); // 经度
        $lat = $this->request->request('lat'); // 纬度
        if (!$lng || !$lat) $this->error('参数缺失!');

        $user->lng = $lng;
        $user->lat = $lat;
        $user->save();
        $this->success("修改成功!");
    }

    /**
     * 修改会员个人信息
     * 环信注册id
     */
    public function userEmcid() {
        $user = $this->auth->getUser();
        $emcid = $this->request->request('emcid'); // 环信注册ID

        $user->emcid = $emcid;
        $user->save();
        $this->success("修改成功!");
    }



    /**
     * 修改会员个人信息
     * 爱好,职业,微信,交友宣言
     */
    public function userhoppy() {
        $user = $this->auth->getUser();
        $hobby_ids = $this->request->request('hobby_ids'); // 爱好
        $profession = $this->request->request('profession'); // 职业(传汉字即可)
        $wechat = $this->request->request('wechat'); // 微信号
        $declaration = $this->request->request('declaration'); // 交友宣言
        if (!$hobby_ids && !$profession && !$wechat && !$declaration) $this->error('参数为空!');

        Db::startTrans();
        try {
            $hobby_ids && $user->hobby_ids = $hobby_ids;
            $profession && $user->profession = $profession;
            if($wechat) {
                if($user->wechat_time + 30*86400 > time()) {
                    $this->error('微信号每月最多修改一次哦!');
                }
                $user->wechat_auth = $wechat;
                // 添加微信号修改申请表
                if(\app\common\model\WechatAuth::where(["status"=>0,"user_id"=>$this->auth->id])->find()) $this->error("微信号已在审核中!请勿重复申请");
                $data = [];
                $data['user_id'] = $this->auth->id;
                $data['wechat'] = $wechat;
                $data['old_wechat'] = $user->wechat;
                $data['createtime'] = time();
                $res1 = \app\common\model\WechatAuth::insert($data);

                $user->wechat_time = time();
            } else {
                $res1 = true;
            }
            if($declaration) {
                if (iconv_strlen($declaration, 'utf-8') > 64) {
                    $this->error('交友宣言最多64位哦!');
                }
                $user->declaration_auth = $declaration;
                // 添加交友宣言修改申请表
                if(\app\common\model\DeclarationAuth::where(["status"=>0,"user_id"=>$this->auth->id])->find()) $this->error("交友宣言已在审核中!请勿重复申请");
                $data = [];
                $data['user_id'] = $this->auth->id;
                $data['declaration'] = $declaration;
                $data['old_declaration'] = $user->declaration;
                $data['createtime'] = time();
                $res3 = \app\common\model\DeclarationAuth::insert($data);
            } else {
                $res3 = true;
            }
//            $declaration && $user->declaration = $declaration;
            $res2 = $user->save();
            if($res1 && $res2 && $res3) {
                Db::commit();
                delUserInfo($this->auth->id);
                if($wechat) {
                    $this->success("微信号修改申请已提交,请耐心等待审核!");
                } elseif ($declaration) {
                    $this->success("交友宣言修改申请已提交,请耐心等待审核!");
                } else {
                    $this->success("修改成功!");
                }
            }
        } catch (PDOException $e) {
            Db::rollback();
            $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 (!$zimage || !$fimage) {
            $this->error(__('Invalid parameters'));
        }
        $userauthModel = new \app\common\model\UserAuth();
        $data = [];
        $data["user_id"] = $this->auth->id;
        if($userauthModel->where($data)->where(['status'=>['in',[0,1]]])->find()) $this->error('您已经申请过了,请勿重复操作!');
        $data["idcard"] = $idcard;
        $data["realname"] = $realname;
        $zimage && $data["zimage"] = $zimage;
        $fimage && $data["fimage"] = $fimage;
        $data["status"] = 0;
        $data["updatetime"] = time();
        $data["createtime"] = time();
        $res = $userauthModel->insertGetId($data);
        \app\common\model\User::update(['is_auth'=>1],["id"=>$this->auth->id]);
        if($res) {
            $this->success("实名认证申请提交成功,请耐心等待审核");
        } else {
            $this->error("网络错误,请稍后重试");
        }
    }


    /**
     * 加入黑名单
     */
    public function addBlacklist() {
        $black_user_id = $this->request->request('black_user_id'); // 黑名单用户ID
        if (!$black_user_id) {
            $this->error(__('Invalid parameters'));
        }
        $user_id = $this->auth->id;
        if($user_id == $black_user_id) {
            $this->error(__('为何拉黑自己呢?'));
        }
        $userblacklistModel = new \app\common\model\UserBlacklist();
        $data = [];
        $data["user_id"] = $user_id;
        $data["black_user_id"] = $black_user_id;
        if($userblacklistModel->where($data)->find()) $this->error(__('已在黑名单!'));
        $data["createtime"] = time();
        $res = $userblacklistModel->insertGetId($data);
        if($res) {
            $this->success("加入成功!");
        } else {
            $this->error("网络错误,请稍后重试");
        }
    }

    /**
     * 获取黑名单用户
     */
    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.age,u.gender,u.constellation,u.hobby_ids,u.profession")
            ->join("hx_user u","u.id = a.black_user_id")
            ->where($where)
            ->limit($pageStart,$pageNum)
            ->select();
        if($list) {
            foreach($list as $k => $v) {
                $list[$k]['hobby_ids'] = \app\common\model\Hobby::getHobbyNames($v['hobby_ids']);
            }
            $this->success("获取成功!",$list);
        } else {
            $this->success("数据为空",[]);
        }
    }

    /**
     * 移除用户黑名单
     */
    public function removeUserBlack() {
        $id = $this->request->request('id'); // 黑名单ID
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }

        $userblacklistModel = new \app\common\model\UserBlacklist();
        $where = [];
        $where["id"] = $id;
        $info = $userblacklistModel->where($where)->find();
        if($info['user_id'] != $this->auth->id) $this->error("无权限!");
        $res = $userblacklistModel->where($where)->delete();
        if($res) {
            $this->success("移除成功!",$res);
        } else {
            $this->error("网络错误,请稍后重试!");
        }
    }

    /**
     * 举报用户
     */
    public function addReport() {
        $ruser_id = $this->request->request('ruser_id'); // 被举报用户ID
        $content = $this->request->request('content'); // 举报内容
        $type_id = $this->request->request('type_id'); // 举报类型
        $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["ruser_id"] = $ruser_id;
        $data["type_id"] = $type_id;
        $data["content"] = $content;
        $data["image"] = $image;
        $data["createtime"] = time();
        $res = $userreportModel->insertGetId($data);
        if($res) {
            $this->success("举报成功!");
        } else {
            $this->error("网络错误,请稍后重试");
        }
    }

    /**
     * 剩余特权次数
     * @return int|mixed
     */
    public function getFateCount() {
        $fate_count = \app\common\model\User::getViewCount($this->auth->id);
        $this->success("获取成功!",$fate_count);
    }

    /**
     * 添加有眼缘
     */
    public function addFate() {
        $fate_user_id = $this->request->request('fate_user_id'); // 被眼缘用户ID
        if (!$fate_user_id) {
            $this->error(__('Invalid parameters'));
        }
        $user_id = $this->auth->id;

        if($fate_user_id == $user_id) {
            $this->error("不需要添加自己为有眼缘哦!");
        }
        $user = \app\common\model\User::get($user_id);
        // 查看当前用户剩余次数
        $view_count = \app\common\model\User::getViewCount($user_id);
        if($view_count <= 0) {
            $this->error(__('可查看次数不够了哦!',[],100));
        } else {
            Db::startTrans();
            try {
                $user->view_count = $user->view_count - 1;
                $res1 = $user->save();
                // 添加眼缘记录
                $data = [];
                $data['user_id'] = $user_id;
                $data['fate_user_id'] = $fate_user_id;
                if(\app\common\model\UserFate::where($data)->find()) {
                    $this->error("已经添加眼缘啦!");
                }
                $data['createtime'] = time();
                $res2 = \app\common\model\UserFate::insert($data);

                // 添加返利
                if($user->is_goddess == 1) {
                    $memo = '被查看有眼缘获得收益!';
                    $profit = config('site.fate') * config('site.goddessProfitRate') * 0.01;
                } else {
                    $memo = '被查看有眼缘获得收益!';
                    $profit = config('site.fate') * config('site.userProfitRate') * 0.01;
                }
                if($profit >= 0.01 && $fate_user_id > 0) {
                    $res3 = \app\common\model\User::profit($profit,$fate_user_id,$memo);
                } else {
                    $res3 = true;
                }

                if($res1 && $res2 && $res3) {
                    Db::commit();

                    $fate_user_info = \app\common\model\User::where(['id'=>$fate_user_id])->find();
                    $title = '眼缘提醒!';
                    $content = $fate_user_info->nickname.': 等你很久了,终于来了。希望你可以眼缘这里找到有趣的灵魂。无论白天还是深夜,无论快乐还是寂寞,始终有人陪你~';
                    \app\common\model\SysMsg::sendSysMsg($fate_user_id,6,$title,$content);

                    $this->success("眼缘添加成功!");
                }

            } catch (PDOException $e) {
                Db::rollback();
                $this->error("添加失败!");
            }
        }
    }

    /**
     * 获取有眼缘列表
     */
    public function getFate() {
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;

        $user_id = $this->auth->id;
        $where = [];
        $where['a.user_id'] = $user_id;
        $res = \app\common\model\UserFate::alias("a")
            ->field("a.id,u.id as user_id,u.avatar,u.nickname,u.age,u.constellation,u.hobby_ids,u.profession,u.wechat")
            ->join("hx_user u","u.id = a.fate_user_id")
            ->where($where)
            ->order("a.createtime",'desc')
            ->limit($pageStart,$pageNum)
            ->select();
        if($res) foreach($res as $k => $v) {
            $res[$k]['hobby_ids'] = \app\common\model\Hobby::getHobbyNames($v['hobby_ids']);
        }
        $this->success("获取成功!",$res);
    }

    /**
     * 获取用户个人信息
     */
    public function getUserInfo() {
        $user_id = $this->request->request('user_id',0); // 用户ID
        if(!$user_id) {
            $this->error('参数缺失!');
        }
//        // redis
//        $redis = new Redis();
//        $redisconfig = config("redis");
//        $redis->connect($redisconfig["host"], $redisconfig["port"]);
//        $userInfo = decodeArray($redis->hGetAll('userInfo_'.$user_id));
//
//        if(!$userInfo){
            // 获取用户信息
            $field = 'id,avatar,nickname,is_goddess,is_auth,recharge_auth,vipStatus(vip_duetime) as is_vip,age,lng,lat,city_name,district_name,constellation,hobby_ids,profession,declaration,wechat,income';
            $userInfo = \app\common\model\User::field($field)->where(['id'=>$user_id])->find();
            $userInfo['hobby_ids'] = \app\common\model\Hobby::getHobbyNames($userInfo['hobby_ids']);
            // 获取是否有眼缘
            $userInfo['is_fate'] = \app\common\model\User::getIsView($user_id,$this->auth->id);
            // 获取地区
            $userInfo['address'] = \app\common\model\Eyemargin::getDistanceTxt($userInfo['lng'],$userInfo['lat'],$this->auth->lng,$this->auth->lat,$userInfo['city_name'],$userInfo['district_name']);

            // 微信号
            if(!$userInfo['wechat']) {
                $userInfo['wechat'] = '暂未设置微信号!';
            } elseif(!$userInfo['is_fate']) {
                $userInfo['wechat'] = '******';
            }

            // 获取已有标签以及数量
            $userInfo['tagUser'] = \app\common\model\TagUser::alias('a')
                ->field('a.id,t.name,a.number')
                ->join('hx_tag t','t.id = a.tag_id','left')
                ->where(['a.user_id'=>$user_id])
                ->select();

//            $userInfo = $userInfo->toArray();
//            $redis->hMSet('userInfo_'.$user_id,encodeArray($userInfo));
//        }

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

    /**
     * 获取我的个人信息
     */
    public function getMyInfo() {
        $user_id = $this->auth->id;
        // redis
//        $redis = new Redis();
//        $redisconfig = config("redis");
//        $redis->connect($redisconfig["host"], $redisconfig["port"]);
//        $userInfo = decodeArray($redis->hGetAll('userInfo_'.$user_id));
//
//        if(!$userInfo){
            // 获取用户信息
            $field = 'id,avatar,avatar_auth,gender,nickname,nickname_auth,is_goddess,is_auth,vipStatus(vip_duetime) as is_vip,vip_duetime,age,city_name,district_name,constellation,hobby_ids,expect_ids,profession,declaration,money,wechat,wechat_auth,pre_user_id';
            $userInfo = \app\common\model\User::field($field)->where(['id'=>$user_id])->find();
            $userInfo['vip_duetime'] = $userInfo['vip_duetime']?date('Y-m-d',$userInfo['vip_duetime']):"";
            if($userInfo['pre_user_id']>0) {
                $userInfo['pre_invite_no'] = \app\common\model\User::where(['id'=>$userInfo['pre_user_id']])->value("invite_no");
            } else {
                $userInfo['pre_invite_no'] = "";
            }
            // 获取我喜欢的统计
            $userInfo['ilike_count'] = \app\common\model\UserLike::where(['fans_id'=>$user_id])->count();
            $userInfo['likeme_count'] = \app\common\model\UserLike::where(['user_id'=>$user_id])->count();
            $userInfo['fate_count'] = \app\common\model\UserFate::where(['user_id'=>$user_id])->count();
            $userInfo['money_count'] = $userInfo['money'];
            $userInfo['hobby_ids'] = \app\common\model\Hobby::getHobbyNames($userInfo['hobby_ids']);
            $userInfo['expect_ids'] = $userInfo['expect_ids']?explode(",",$userInfo['expect_ids']):[];

        $userInfo['nickname_auth_stauts'] = \app\common\model\NicknameAuth::getAuthStatus($userInfo['id'],$userInfo['nickname_auth']);
        $userInfo['avatar_auth_stauts'] = \app\common\model\AvatarAuth::getAuthStatus($userInfo['id'],$userInfo['avatar_auth']);
        $userInfo['wechat_auth_stauts'] = \app\common\model\WechatAuth::getAuthStatus($userInfo['id'],$userInfo['wechat_auth']);
        $userInfo['declaration_auth_stauts'] = \app\common\model\DeclarationAuth::getAuthStatus($userInfo['id'],$userInfo['declaration_auth']);


//            $userInfo = $userInfo->toArray();
//            $redis->hMSet('userInfo_'.$user_id,encodeArray($userInfo));
//        }
        $this->success("获取成功!",$userInfo);
    }

    /**
     * 获取动态/我的动态
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserEyemagin() {
        $user_id = $this->request->request('user_id',0); // 用户ID
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;

        $where = [];
        if($user_id > 0) {
            $where['a.user_id'] = $user_id;
            $where['a.status'] = 1;
        } else {
            $user_id = $this->auth->id;
            $where['a.user_id'] = $user_id;
            $where['a.status'] = ['in',[0,1]];

        }
        $field = "a.*,u.avatar,u.city_name,u.district_name,u.nickname,u.is_goddess,u.is_auth,vipStatus(u.vip_duetime) as is_vip, 
                u.age,u.constellation,u.hobby_ids,u.profession,u.declaration,u.lng,u.lat";
        $list = \app\common\model\Eyemargin::alias("a")
            ->field($field)
            ->join("user u","a.user_id = u.id")
            ->where($where)
            ->limit($pageStart,$pageNum)
            ->order("a.createtime desc")
            ->select();
        if($list) foreach($list as $k => $v) {
            // 计算距离
            $list[$k]['distance'] = \app\common\model\Eyemargin::getDistance($v['lng'],$v['lat'],$this->auth->lng,$this->auth->lat);
            $list[$k]['distance_txt'] = \app\common\model\Eyemargin::getDistanceTxt($v['lng'],$v['lat'],$this->auth->lng,$this->auth->lat,$v['city_name'],$v['district_name']);
            $list[$k]['right_info'] = \app\common\model\Eyemargin::getIsView($v['user_id'],$user_id);
            $v['cover'] || $list[$k]['cover'] = $_SERVER["REQUEST_SCHEME"]."://".$_SERVER["HTTP_HOST"].'/assets/img/video_cover.jpeg';
            $v['hobby_ids'] || $list[$k]['hobby_ids'] = [];
            $v['profession'] || $list[$k]['profession'] = '';
            $v['music'] || $list[$k]['music'] = '';
            $v['video'] || $list[$k]['video'] = '';
        }


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

    /**
     * 获取我的个人基本信息
     */
    public function getMyBaseInfo() {
        $user_id = $this->auth->id;
        // redis
//        $redis = new Redis();
//        $redisconfig = config("redis");
//        $redis->connect($redisconfig["host"], $redisconfig["port"]);
//        $userInfo = decodeArray($redis->hGetAll('userInfo_'.$user_id));

//        if(!$userInfo){
            // 获取用户信息
            $field = 'id,avatar,nickname,gender,age,city_name,district_name,constellation,hobby_ids,profession,declaration,wechat,income';
            $userInfo = \app\common\model\User::field($field)->where(['id'=>$user_id])->find();
            $userInfo['hobby_ids'] = \app\common\model\Hobby::getHobbyNames($userInfo['hobby_ids']);
            // 获取已有标签以及数量
            $userInfo['tagUser'] = \app\common\model\TagUser::alias('a')
                ->field('a.id,t.name,a.number')
                ->join('hx_tag t','t.id = a.tag_id','left')
                ->where(['a.user_id'=>$user_id])
                ->select();

            $userInfo = $userInfo->toArray();
//            $redis->hMSet('userInfo_'.$user_id,encodeArray($userInfo));
//        }
        $this->success("获取成功!",$userInfo);
    }

    /**
     * 为用户添加标签
     */
    public function setUserTag() {
        $tag_id = $this->request->request('tag_id',0); // 标签ID
        $fate_user_id = $this->request->request('fate_user_id',0); // 有眼缘用户ID
        if(!$tag_id || !$fate_user_id) {
            $this->error('参数缺失!');
        }
        if(!\app\common\model\Tag::where(['id'=>$tag_id])->find()) {
            $this->error('标签不存在!');
        }

        $user_id = $this->auth->id;
        $is_fate = \app\common\model\User::getIsView($fate_user_id,$user_id);
        if(!$is_fate) $this->error('您需要先获取微信号才能添加标签');
        $tag_user_log = \app\common\model\TagUserLog::where(['user_id'=>$user_id,'fate_user_id'=>$fate_user_id,'tag_id'=>$tag_id])->find();
        if($tag_user_log) {
            $this->error('您已经为ta添加过此标签了');
        }
        Db::startTrans();
        try {
            // 添加记录
            $data = [];
            $data['user_id'] = $user_id;
            $data['fate_user_id'] = $fate_user_id;
            $data['tag_id'] = $tag_id;
            $data['createtime'] = time();
            $res1 = \app\common\model\TagUserLog::insert($data);
            // 修改标签数量
            $where = [];
            $where['user_id'] = $fate_user_id;
            $where['tag_id'] = $tag_id;
            $tag_user = \app\common\model\TagUser::where($where)->find();
            if($tag_user) {
                $tag_user->number = $tag_user->number + 1;
                $res2 = $tag_user->save();
            } else {
                $data = [];
                $data['user_id'] = $fate_user_id;
                $data['tag_id'] = $tag_id;
                $data['number'] = 1;
                $data['createtime'] = time();
                $res2 = \app\common\model\TagUser::insert($data);
            }

            if($res1 && $res2) {
                Db::commit();
                delUserInfo($fate_user_id);
                $this->success("标签添加成功!");
            }

        } catch (PDOException $e) {
            Db::rollback();
            $this->error("修改失败!");
        }
    }


    /**
     * 绑定用户
     */
    public function bindUser() {
        $invite_no = $this->request->request('invite_no'); // 邀请码
        if(!$invite_no) {
            $this->error("请输入邀请码!");
        }
        $user_id = $this->auth->id;

        // 查询邀请码用户信息
        $inviteUserInfo = \app\common\model\User::where(["invite_no"=>$invite_no])->find();
        if(!$inviteUserInfo) $this->error("查询不到该邀请码用户信息!");

        // 判断是否已经绑定过
        $my_pre_user_id = \app\common\model\User::where(["id"=>$user_id])->value("pre_user_id");
        if($my_pre_user_id > 0) {
            $this->error(__('您已绑定过,不可重复绑定!'));
        }

        if($user_id == $inviteUserInfo->id) {
            $this->error(__('不能绑定自己哦?'));
        }

        // 判断当前用户是否实名认证
        $userAuthInfo = \app\common\model\UserAuth::userIsAuth($this->auth->id);
        if($userAuthInfo['status'] == 0) $this->error($userAuthInfo['msg']);

        $res = \app\common\model\User::update(["pre_user_id"=>$inviteUserInfo->id,'invite_time'=>time()],["id"=>$user_id]);
        if($res) {
            $this->success("恭喜,绑定成功!");
        } else {
            $this->error("网络繁忙,请稍后重试!");
        }
    }



    /**
     * 添加银行卡
     */
    public function addBank() {
        $user_name = $this->request->request('user_name'); //真实姓名
        $bank_name= $this->request->request('bank_name'); //银行名称
        $bank_no = $this->request->request('bank_no'); //银行卡号
        if (!$user_name || !$bank_name || !$bank_no) {
            $this->error(__('Invalid parameters'));
        }
        $bankModel = new \app\common\model\UserBank();
        $where = [];
        $where["user_id"] = $this->auth->id;
        $where["bank_no"] = $bank_no;
        $bankInfo = $bankModel->where($where)->find();
        if($bankInfo) {
            $this->error('该银行卡已经添加过了!');
        }
        $data = [];
        $data["user_id"] = $this->auth->id;
        $data["user_name"] = $user_name;
        $data["bank_name"] = $bank_name;
        $data["bank_no"] = $bank_no;
        $data["createtime"] = time();
        $id = $bankModel->insertGetId($data);
        if($id > 0) {
            $this->success('添加成功!');
        } else {
            $this->error('添加失败!');
        }
    }

    /**
     * 获取银行卡信息
     */
    public function bankInfo() {
        $bankModel = new \app\common\model\UserBank();
        $where = [];
        $where["user_id"] = $this->auth->id;
        $bankInfo = $bankModel->where($where)->find();
        $bankInfo['bank_no'] && $bankInfo['bank_no'] = substr_replace($bankInfo['bank_no'],'********','0','8');
        $this->success('获取成功!',$bankInfo);
    }

    /**
     * 删除银行卡
     */
    public function bankDel() {
        $bankModel = new \app\common\model\UserBank();
        $where = [];
        $where["user_id"] = $this->auth->id;
        $bankInfo = $bankModel->where($where)->delete();
        if($bankInfo) {
            $this->success('删除成功!');
        } else {
            $this->error('删除失败!');
        }
    }


    /**
     * 获取会员开通配置信息
     */
    public function getVipConfig() {
        $res = [];
        $res['user_info'] = \app\common\model\User::field('id,nickname,avatar,vipStatus(vip_duetime) as is_vip,vip_duetime')->where(['id'=>$this->auth->id])->find();
        $res['user_info']['vip_duetime'] = $res['user_info']['vip_duetime']?date('Y-m-d',$res['user_info']['vip_duetime']):"";
        $res['vip_config'] = \app\admin\model\vip\Config::order("weight","desc")->select();
        $this->success("获取成功!",$res);
    }


    /**
     * 设置首页推荐
     */
    public function setEyemaginToMain() {
        $fate_id = $this->request->request('fate_id'); //动态ID
        if (!$fate_id) {
            $this->error(__('Invalid parameters'));
        }
        $user_id = $this->auth->id;
        $fateInfo = \app\common\model\Eyemargin::get($fate_id);
        if($fateInfo->user_id != $user_id) $this->error('抱歉,您无权限操作!');
        // 判断动态是否在审核中
        if($fateInfo->status != 1) $this->error('当前动态状态不允许设置为推荐!');

        Db::startTrans();
        try {
            // 先取消掉所有的推荐
            $res1 = \app\common\model\Eyemargin::update(['is_main'=>0],['user_id'=>$user_id]);
            $res2 = \app\common\model\Eyemargin::update(['is_main'=>1],['id'=>$fate_id]);
            if($res1 && $res2) {
                Db::commit();
                $this->success("设置成功!");
            }

        } catch (PDOException $e) {
            Db::rollback();
            $this->error("设置失败!");
        }
    }

    /**
     * 删除动态
     */
    public function delEyemagin() {
        $fate_id = $this->request->request('fate_id'); //动态ID
        if (!$fate_id) {
            $this->error(__('Invalid parameters'));
        }
        $user_id = $this->auth->id;
        $fateInfo = \app\common\model\Eyemargin::get($fate_id);
        if($fateInfo->user_id != $user_id) $this->error('抱歉,您无权限操作!');
        $res = \app\common\model\Eyemargin::where(['id'=>$fate_id])->delete();
        if($res) {
            $this->success("删除成功!");
        } else {
            $this->error("删除失败!");
        }
    }

    /**
     * 获取第一条系统消息
     */
    public function getFirstSysMsg() {
        $user_id = $this->auth->id;
        $res = [];
        $res['msg_content'] = \app\common\model\SysMsg::where(['user_id'=>$user_id])->order('createtime','desc')->value('title');
        $res['msg_count'] = \app\common\model\SysMsg::where(['user_id'=>$user_id,'is_read'=>0])->count();
        $this->success("获取成功!",$res);
    }

    /**
     * 获取系统消息列表
     */
    public function getSysMsg() {
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;

        $user_id = $this->auth->id;
        $sysMsgList = \app\common\model\SysMsg::where(['user_id'=>$user_id])->order('createtime','desc')->limit($pageStart,$pageNum)->select();
        if($sysMsgList) {
            // 标记所有消息已读1
            \app\common\model\SysMsg::update(['is_read'=>1],['user_id'=>$user_id]);
        }
        $this->success("获取成功!",$sysMsgList);
    }

    /**
     * 获取实名认证信息
     */
    public function getAuthInfo() {
        $user_id = $this->auth->id;
        // 判断当前用户是否实名认证
        $userAuthInfo = \app\common\model\UserAuth::where(["user_id"=>$user_id])->find();
        $res = [];
        $res['status'] = 2;
        $res['msg'] = "已实名!";
        $res['data'] = $userAuthInfo;
        if($userAuthInfo) {
            if($userAuthInfo->status == 0) {
                $res['status'] = 1;
                $res['msg'] = "审核中!";
            } elseif($userAuthInfo->status == 2) {
                $res['status'] = -1;
                $res['msg'] = "审核未通过!";
            }
        } else {
            $res['status'] = 0;
            $res['msg'] = "请先申请实名认证!";
            $res['data'] = [];
        }
        $res['recharge_auth'] = \app\common\model\User::where(['id'=>$user_id])->value("recharge_auth");
        $this->success("获取成功!",$res);
    }
}