<?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\Config;
use think\Validate;

use app\common\library\Token;
use think\Db;
use app\common\model\UserDeviceInfo;
use onlogin\onlogin;

use addons\epay\library\Service;
use app\common\library\Wechat;

/**
 * 会员接口,登录,注册,修改资料等
 */
class User extends Api
{
    protected $noNeedLogin = ['emaillogin','emailregister','mobilelogin','resetpwd'];
    protected $noNeedRight = '*';

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


    /**
     * 邮箱登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function emaillogin()
    {
        $account = input('account');
        $password = input('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($account, 'email')) {
            $this->error(__('Email is incorrect'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $this->success(__('Logged in successful'), $this->auth->getUserinfo_simple());
        } else {
            $this->error($this->auth->getError());
        }
    }

    //邮箱注册
    public function emailregister()
    {
        $account = input('account');
        $captcha = input('captcha');
        $password = input('password');
        if (!$account || !$captcha || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($account, 'email')) {
            $this->error(__('Email is incorrect'));
        }
        $ret = Ems::check($account, $captcha, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        $extend = [
            'register_from' => input('register_from',''),
            'gender' => -1
        ];
        $ret = $this->auth->register('',$password,$account,'', $extend);
        if ($ret) {
            Ems::flush($account);
            $this->success('注册成功', $this->auth->getUserinfo_simple());
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录 + 注册
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {

        $mobile = input('mobile');
        $captcha = input('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, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status == -1) {
                $this->error('账户已注销');
            }
            if (!in_array($user->status,[1,2])) {
                $this->error(__('Account is locked'));
            }
            if ($user->frozentime > time()) {
                $this->error('您的账号已被封禁至' . date('Y-m-d H:i'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);


        } else {


            $extend = [
                'register_from' => input('register_from',''),
                'gender' => -1
            ];
            $ret = $this->auth->register('', '', '', $mobile, $extend);

        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $this->success(__('Logged in successful'), $this->auth->getUserinfo_simple());
        } else {
            $this->error($this->auth->getError());
        }
    }

    //注册设置性别
    public function setgender() {
        $user_id = $this->auth->id;

        $gender = input('gender', -1, 'intval'); //性别:1=男,0=女
        if (!in_array($gender, [1, 0])) {
            $this->error('性别错误');
        }

        $edit_data['gender'] = $gender;
        $edit_data['avatar'] = $gender == 1 ? config('avatar_boy') : config('avatar_girl'); //头像

        $rs = Db::name('user')->where(['id' => $user_id])->update($edit_data);
        if ($rs === false) {
            $this->error('您的网络开小差啦~');
        }

        //$data = $this->userInfo('return');
        $data['gender'] = $edit_data['gender'];
        $data['avatar'] = $edit_data['avatar'];

        $this->success('success', $data);

    }

    //刷新随机昵称
    public function get_rand_nick_name(){
        $nickname = $this->auth->get_rand_nick_name();
        $this->success('success', $nickname);
    }

    //注册完善资料
    public function perfect_info() {
        $avatar = input('avatar', '', 'trim'); //头像
        $nickname = input('nickname', '', 'trim'); //昵称
        $birthday = input('birthday', '', 'strtotime'); //生日
        $hometown_cityid = input('hometown_cityid', '', 'trim'); //城市id
        $bio = input('bio', '', 'trim'); //个性签名
        $hobby = input('hobby', '', 'trim'); //爱好
        $marital = input('marital', '', 'trim'); //婚姻
        $introcode = input('introcode', '', 'trim'); //邀请码

        $data = [];
        if ($avatar) {
            $data['avatar'] = $avatar;
        }
        if ($nickname !== '') {
            if (iconv_strlen($nickname, 'utf-8') > 10) {
                $this->error('昵称最多10个字~');
            }
            $data['nickname'] = $nickname;
        }
        if ($birthday) {
            $data['birthday'] = $birthday;
        }
        if ($hometown_cityid) {
            $count = Db::name('area')->where('id', $hometown_cityid)->count('id');
            if (!$count) {
                $this->error('城市不存在');
            }
            $data['hometown_cityid'] = $hometown_cityid;
        }
        if ($bio) {
            $data['bio'] = $bio;
        }
        if ($hobby) {
            $data['hobby'] = $hobby;
        }
        if ($marital) {
            $data['marital'] = $marital;
        }
        if ($introcode && !$this->auth->intro_uid) {
            $intro_user = Db::name('user')->field('id, intro_uid')->where('introcode', $introcode)->find();
            if ($intro_user && $intro_user['id'] != $this->auth->id && $intro_user['intro_uid'] != $this->auth->id) {
                $data['intro_uid'] = $intro_user['id'];
                $data['invite_time'] = time();
            }
        }

        //开启事务
        Db::startTrans();
        $update_rs = Db::name('user')->where('id',$this->auth->id)->update($data);
        if($update_rs === false){
            Db::rollback();
            $this->error('修改失败');
        }

        //给上级发放钻石
        if(isset($data['intro_uid'])){
            $intro_gold = config('site.new_user_intro_gold');
            if($intro_gold > 0){
                $rs_wallet = model('wallet')->lockChangeAccountRemain($data['intro_uid'], 0,'gold',$intro_gold,34,'邀请'.$this->auth->username.'注册奖励');
                if($rs_wallet['status'] === false){
                    Db::rollback();
                    $this->error('邀请新人奖励赠送失败');
                }
            }
        }

        //上传头像加5金币
        if(isset($data['avatar'])){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,19);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }
        if (isset($data['birthday'])) {
            //完成设置生日  +5金币
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,1);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }

        Db::commit();
        $this->success('修改成功');
    }

    //用户详细资料
    public function userInfo($type = 1){
        $info = $this->auth->getUserinfo();
        if($type == 'return'){
            return $info;
        }
        $this->success(__('success'),$info);
    }


    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $field_array = ['nickname','introcode',/*'gender',*/'birthday','height','weight','bio','audio_bio','avatar','photo_images','education','hobby','job','marital','tag','wages','hometown_cityid','hide_is_finishinfo',/*'wechat_account',*/'character','constellation','stature','is_appointment', 'greet_voice', 'greet_chat', 'is_cohabit', 'live', 'is_house', 'car', 'chest', 'waist'];

        $data = [];
        foreach($field_array as $key => $field){

            if(!input('?'.$field)){
                continue;
            }

            $newone = input($field);

            if($field == 'avatar'){
                // if ($this->auth->real_status == 1) {
                //$this->error('您已经真人认证不能修改头像~');
                // die;
                // }
                $newone = input('avatar', '', 'trim,strip_tags,htmlspecialchars');
            }
            if($field == 'photo_images'){
                $newone = input('photo_images', '', 'trim,strip_tags,htmlspecialchars');
            }

            $data[$field] = $newone;
        }

        if(isset($data['birthday'])){
            $data['birthday'] = strtotime($data['birthday']);
        }
        if(isset($data['avatar'])){
            //$data['real_status'] = -1;  //或许应该改成0。性别不能改所以不需要
        }

        if(isset($data['introcode'])){
            if ($this->auth->intro_uid != 0) {
                $this->error('邀请人不可修改~');
            }

            $intro_user = Db::name('user')->field('id, intro_uid')->where('introcode', $data['introcode'])->find();
            if(!$intro_user){
                $this->error('不存在的邀请人');
            }
            if ($intro_user['id'] == $this->auth->id) {
                $this->error('不能填写自己邀请码');
            }
            if ($intro_user['intro_uid'] == $this->auth->id) {
                $this->error('不能填写下级邀请码');
            }
            unset($data['introcode']);//别人的邀请码,不能改了自己的
            $data['intro_uid'] = $intro_user['id'];
            $data['invite_time'] = time();
        }
        //dump($data);
        if(empty($data)){
            $this->error('没有任何改变');
        }



        Db::startTrans();
        $userData = Db::name('user')->field('avatar,gender,status')->where('id',$this->auth->id)->find();
        if (isset($data['avatar']) && !empty($data['avatar']) && $userData['status'] == 2) {//隐藏
            $boyAvatar = config('avatar_boy');
            $girlAvatar = config('avatar_girl');
            if ($userData['gender'] == 1 && $data['avatar'] != $boyAvatar) {
                $data['status'] = 1;//更新为正常
            } elseif ($userData['gender'] == 0 && $data['avatar'] != $girlAvatar) {
                $data['status'] = 1;//更新为正常
            }
        }
        $update_rs = Db::name('user')->where('id',$this->auth->id)->update($data);
        if($update_rs === false){
            Db::rollback();
            $this->error('修改资料失败');
        }

        //给上级发放钻石
        if(isset($data['intro_uid'])){
            $intro_gold = config('site.new_user_intro_gold');
            if($intro_gold > 0){
                $rs_wallet = model('wallet')->lockChangeAccountRemain($data['intro_uid'], 0,'gold',$intro_gold,34,'邀请'.$this->auth->username.'注册奖励');
                if($rs_wallet['status'] === false){
                    Db::rollback();
                    $this->error('邀请新人奖励赠送失败');
                }
            }
        }

        //tag任务赠送金币
        //上传头像加5金币
        if(isset($data['avatar'])){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,19);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }
        //上传生日 +5金币
        if (isset($data['birthday'])) {
            //完成设置生日  +5金币
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,1);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }
        //上传个性签名 5金币
        if(isset($data['bio'])){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,2);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }
        //上传本人语音介绍 10金币
        if(isset($data['audio_bio'])){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,21);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }
        //上传本人五张照片 10金币
        if(isset($data['photo_images'])){
            $photo_images_num = count(explode(',',$data['photo_images'])) + count(explode(',',$this->auth->photo_images));
            if ($photo_images_num >= 5) {
                $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id, 5);
                if ($task_rs === false) {
                    Db::rollback();
                    $this->error('完成任务赠送奖励失败');
                }
            }
        }


        Db::commit();


        $this->success();
    }


    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        //退出im
        $tenIm = new Tenim();
        $tenIm->loginoutim($this->auth->id);

        //修改用户活跃0
        Db::name('user')->where('id',$this->auth->id)->update(['is_active' => 0]);

        $this->auth->logout();
        $this->success(__('Logout successful'));
    }


    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        //$type = input("type");
        $type = 'email';
        $mobile = input("mobile");
        $email = input("email");
        $newpassword = input("newpassword");
        $captcha = input("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());
        }
    }

    /**
     * 微信注册来的,绑定手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function bindmobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');

        if(!empty($this->auth->mobile)){
            $this->error('已经绑定了手机号');
        }
        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)->find()) {
            $this->error('该手机号已被其他用户绑定');
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }

        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');

        //手机号奖励
        $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,18);
        if($task_rs === false){
            Db::rollback();
            return false;
        }
        $this->success('success',$this->userInfo('return'));
    }


    //注销配置
    public function cancleconfig(){
        $rs = [
            'rule' => config('site.user_cancle_rules'),
            'reason' => [
                            '想换个新账号',
                            '没有聊得来的',
                            '不想玩了',
                            '其他原因',
                        ],
        ];
        $this->success(1,$rs);
    }

    //假注销
    public function cancleUser(){
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        //退出im
        $tenIm = new Tenim();
        $tenIm->loginoutim($this->auth->id);

        $data = [
            'status' => -1,
            'mobile' => 'close_'.$this->auth->mobile,
            'wechat_openid' => 'close_'.$this->auth->wechat_openid,
        ];
        Db::name('user')->where('id',$this->auth->id)->update($data);

        $this->auth->logout();
        $this->success('注销成功');
    }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 手机验证码验证
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    /*public function mobilecheck()
    {
        $mobile = input('mobile');
        $captcha = input('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, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }

        $this->success('验证通过');
    }*/

    /**
     * 手机验证码注册
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     * @param string $gender  性别:1=男,0=女
     */
    /*public function mobileregister()
    {
        $mobile = input('mobile');
        $captcha = input('captcha');
        $gender = input('gender', -1, 'intval'); //性别:1=男,0=女

        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        if (!in_array($gender, [1, 0])) {
            $this->error('性别错误');
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            $this->error('账号已经存在,请直接登录');

            if ($user->status == -1) {
                $this->error('账户已注销');
            }
            if (!in_array($user->status,[1,2])) {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);


        } else {
            $extend = [
                'register_from' => input('register_from',''),
                'gender' => $gender
            ];
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, $extend);

        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = $this->userInfo('return');
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }*/



    /**
     * 运营商一键登录
     */
    /*public function onLogin()
    {
        $accessToken = input('accessToken');// 运营商预取号获取到的token
        $token = input('tokenT');// 易盾返回的token
        if (!$accessToken || !$token) {
            $this->error("参数获取失败!");
        }

        $params = array(
            // 运营商预取号获取到的token
            "accessToken" => $accessToken,
            // 易盾返回的token
            "token"       => $token
        );

        // 获取密钥配置
        $configInfo = config("onLogin");
        $onlogin = new onlogin($configInfo["secretid"], $configInfo["secretkey"], $configInfo["businessid"]);

        $onret = $onlogin->check($params);

//        $ret = [];
//        $ret["code"] = 200;
//        $ret["msg"] = "ok";
//        $ret["data"] = [
//            "phone" => "17574504021",
//            "resultCode" => 0
//        ];

        if ($onret["code"] == 200) {
            $mobile = $onret["data"]["phone"];
            if (empty($mobile)) {
                // 取号失败,建议进行二次验证,例如短信验证码
                $this->error("取号登录失败,请用验证码方式登录!");
            } else {
                // 取号成功, 执行登录等流程
                // 用户登录逻辑 === 开始

                $user = \app\common\model\User::getByMobile($mobile);
                if ($user) {
                    if (!in_array($user->status,[1,2])) {
                        $this->error(__('Account is locked'));
                    }
                    if ($user->frozentime > time()) {
                        $this->error('您的账号已被封禁至' . date('Y-m-d H:i'));
                    }
                    //如果已经有账号则直接登录
                    $ret = $this->auth->direct($user->id);
                    $is_register = 0;


                } else {


                    $extend = [
                        'register_from' => input('register_from',''),
                        'gender' => -1
                    ];
                    $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, $extend);
                    $is_register = 1;

                }


                if ($ret) {
                    $this->success(__('Logged in successful'), $this->auth->getUserinfo());
                } else {
                    $this->error($this->auth->getError());
                }
                // 用户登录逻辑 === 结束
            }
        } else {
            $this->error("登录失败,请用验证码方式登录!");
        }
    }*/

    /**
     * 运营商一键登录注册
     */
    /*public function onregister()
    {
        $accessToken = input('accessToken');// 运营商预取号获取到的token
        $token = input('tokenT');// 易盾返回的token
        $gender = input('gender', -1, 'intval'); //性别:1=男,0=女

        if (!$accessToken || !$token) {
            $this->error("参数获取失败!");
        }
        if (!in_array($gender, [1, 0])) {
            $this->error('性别错误');
        }

        $params = array(
            // 运营商预取号获取到的token
            "accessToken" => $accessToken,
            // 易盾返回的token
            "token"       => $token
        );

        // 获取密钥配置
        $configInfo = config("onLogin");
        $onlogin = new onlogin($configInfo["secretid"], $configInfo["secretkey"], $configInfo["businessid"]);

        $onret = $onlogin->check($params);

//        $ret = [];
//        $ret["code"] = 200;
//        $ret["msg"] = "ok";
//        $ret["data"] = [
//            "phone" => "17574504021",
//            "resultCode" => 0
//        ];

        if ($onret["code"] == 200) {
            $mobile = $onret["data"]["phone"];
            if (empty($mobile)) {
                // 取号失败,建议进行二次验证,例如短信验证码
                $this->error("取号登录失败,请用验证码方式登录!");
            } else {
                // 取号成功, 执行登录等流程
                // 用户登录逻辑 === 开始

                $user = \app\common\model\User::getByMobile($mobile);
                if ($user) {
                    $this->error('账号已经存在,请直接登录');

                    if (!in_array($user->status,[1,2])) {
                        $this->error(__('Account is locked'));
                    }
                    //如果已经有账号则直接登录
                    $ret = $this->auth->direct($user->id);
                    $is_register = 0;


                } else {
                    $extend = [
                        'register_from' => input('register_from',''),
                        'gender' => $gender
                    ];
                    $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, $extend);
                    $is_register = 1;

                }

                //结果

                if ($ret) {
                    $this->success(__('Logged in successful'), $this->auth->getUserinfo());
                } else {
                    $this->error($this->auth->getError());
                }
                // 用户登录逻辑 === 结束
            }
        } else {
            $this->error("登录失败,请用验证码方式登录!");
        }
    }*/


    //微信登录,预先假注册
    /*public function wechatlogin(){
        $code = input('code','');
        if(!$code){
            $this->error(__('Invalid parameters'));
        }
        //微信
        $wechat = new Wechat();
        $wxuserinfo = $wechat->getAccessToken($code);

        if(!$wxuserinfo){
            $this->error('openid获取失败');
        }
        if(!is_array($wxuserinfo) || !isset($wxuserinfo['openid'])){
            $this->error('openid获取失败');
        }

        $openid = $wxuserinfo['openid'];

        //检查用户
        $user = Db::name('user')->where('wechat_openid',$openid)->find();
        if ($user) {
            if ($user['status'] == -1) {
                $this->error('账户已注销');
            }
            if ($user['status'] != 1) {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user['id']);

            if ($ret) {
                $userInfo = $this->auth->getUserinfo();
                $userInfo['is_register'] = 0;
                $userInfo['code'] = $code;
                $this->success(__('Logged in successful'), $userInfo);
            } else {
                $this->error($this->auth->getError());
            }

        } else {
            //记录code和openid,绑定手机号的时候更新openid
            $wechatCodeData = [
                'code' => $code,
                'openid' => $openid,
                'createtime' => time(),
            ];
            $wechatCode = Db::name('wechat_code')->where(['openid'=>$openid])->find();
            if (empty($wechatCode)) {
                Db::name('wechat_code')->insertGetId($wechatCodeData);
            } else {
                Db::name('wechat_code')->where(['openid'=>$openid])->update($wechatCodeData);
            }

            //直接返回
            $userInfo = [];
            $userInfo['is_register'] = 1;
            $userInfo['code'] = $code;
            $this->success('获取信息成功', $userInfo);
        }

    }*/

    /**
     * 微信注册来的,绑定手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    /*public function wechatbindmobile()
    {
        $mobile = $this->request->param('mobile');
        $captcha = $this->request->param('captcha');
        $code = $this->request->param('code');

        if (!$mobile || !$captcha || !$code) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }

        $wechatCodeWhere['code'] = $code;
        $wechatCode = Db::name('wechat_code')->where($wechatCodeWhere)->find();
        if (empty($wechatCode)) {
            $this->error('请先微信登录');
        }

        //检查appid绑定的用户
        $user = Db::name('user')->where('wechat_openid',$wechatCode['openid'])->find();
        if ($user) {
            if ($user['status'] == -1) {
                $this->error('账户已注销');
            }
            if ($user['status'] != 1) {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user['id']);
            $this->success('success',$this->auth->getUserinfo());
        }

        //新的openid用户
        $where = [];
        $where['mobile'] = $mobile;
        $userData = Db::name('user')->where($where)->find();//老用户
        if (!empty($userData)) {
            if (empty($userData['wechat_openid'])) {
                Db::name('user')->where('id',$userData['id'])->update(['wechat_openid' => $wechatCode['openid']]);//老用户更新openid
            } else {
                if ($userData['wechat_openid'] != $wechatCode['openid']) {
                    $this->error('该手机号已被其他用户绑定');
                }
            }
            $ret = $this->auth->direct($userData['id']);
        } else {
            $extend = [
                'wechat_openid' => $wechatCode['openid'],
            ];
            $ret = $this->auth->register('', '','', $mobile, $extend);
        }
        if (!$ret) {
            $this->error($this->auth->getError());
        }

        $this->success('success',$this->auth->getUserinfo());

    }*/

 









    /*
     * 修改用户的坐标
     * */
    public function change_longlat(){
        $longitude = input_post('longitude');
        $latitude  = input_post('latitude');
        $cityname  = input_post('cityname');
        if(empty($longitude) || empty($latitude) || empty($cityname)){
            $this->error();
        }

        $data = [
            'longitude' => $longitude,
            'latitude'  => $latitude,
            'cityname'  => $cityname,
        ];
        Db::name('user')->where('id',$this->auth->id)->update($data);
        $this->success();
    }


    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $oldcaptcha = $this->request->request('oldcaptcha');
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$oldcaptcha || !$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if($user->mobile == $mobile){
            $this->error('新手机号不能与旧手机号相同');
        }
        if (\app\common\model\User::where('mobile', $mobile)->find()) {
            $this->error(__('Mobile already exist'));
        }
        $result = Sms::check($user->mobile, $oldcaptcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $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($user->mobile, 'changemobile');
        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 手机号注册来的,绑定微信
     *
     * @ApiMethod (POST)
     * @param string wechat_openid   微信openid
     */
    /*public function bindopenid()
    {
        $user = $this->auth->getUser();
        $wechat_openid = $this->request->request('wechat_openid');

        if(!empty($this->auth->wechat_openid)){
            $this->error('已经绑定了微信号');
        }
        if (!$wechat_openid) {
            $this->error(__('Invalid parameters'));
        }

        if (\app\common\model\User::where('wechat_openid', $wechat_openid)->find()) {
            $this->error('该微信号已被其他用户绑定');
        }

        $user->wechat_openid = $wechat_openid;
        $user->save();

        $this->success('success',$this->userInfo('return'));
    }*/





    /**
     * 修改密码
     *
     * @ApiMethod (POST)
     * @param string $newpassword 新密码
     * @param string $oldpassword 旧密码
     */
    public function changepwd(){
        $newpassword = input('newpassword');
        $oldpassword = input('oldpassword','');

        if (!$newpassword) {
            $this->error(__('Invalid parameters'));
        }
        if($this->auth->password && empty($oldpassword)){
            $this->error('原密码必填');
        }

        if(empty($this->auth->password)){
            $ret = $this->auth->changepwd($newpassword, '', true);
        }else{
            $ret = $this->auth->changepwd($newpassword,$oldpassword,false);
        }

        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 记录当前登陆的设备ID,设备信息,IP等
     */
   /* public function changeDeviceIp()
    {
        // 接口防并发
        if (!$this->apiLimit(1, 5)) {
            return ;
        }

        $user = $this->auth->getUser();
        $ip = request()->ip();
        $deviceId = $this->request->request('device_id','');
        $phoneModel = $this->request->request('phone_model','');
        $brand = $this->request->request('brand','');
        $apiVersion = $this->request->request('api_version','');
        $deviceOs = $this->request->request('device_os','');

        if ($ip !== $user->loginip){
            $update = [];
            $update['id'] = $user->id;
            $update['loginip'] = $ip;
            \app\common\model\User::update($update);
        }

        $userDeviceInfo = UserDeviceInfo::get(['user_id'=>$user->u_id]);
        if (empty($userDeviceInfo)){
            $userDeviceInfo = new UserDeviceInfo();
            $userDeviceInfo->user_id = $user->u_id;
        }
        $userDeviceInfo->device_os = $deviceOs;
        $userDeviceInfo->device_id = $deviceId;
        $userDeviceInfo->phone_model = $phoneModel;
        $userDeviceInfo->brand = $brand;
        $userDeviceInfo->api_version = $apiVersion;
        $userDeviceInfo->save();

        //首页接口调用,这里不反回信息
//        $this->success("更新成功!");
    }*/



    //修改用户活跃1
    /*public function useractive(){
        $this->success('success');
    }*/


    //公众号获取openid
    /*public function getUserOpenid_gzh(){
        $configValue = Service::getConfig('wechat');

        $wechat = new Wechat($configValue['app_id'],$configValue['app_secret']);
        $rs = $wechat->getOpenid();
        $this->success('success',$rs);
    }*/
    /**
     * 微信内H5-JSAPI支付
     */
    /*public function jssdkBuildConfig() {
        $url = $this->request->request("url");

        $configValue = Service::getConfig('wechat');
        $wechat = new Wechat($configValue['app_id'],$configValue['app_secret']);

        $sign = $wechat->getSignPackage(urldecode($url));
        $this->success("获取成功!",$sign);
    }*/

    //苹果账号登录
    /*public function ioslogin(){
        $ios_openid = input('ios_openid','');
        if (!$ios_openid) {
            $this->error(__('Invalid parameters'));
        }

        $user = Db::name('user')->where(['ios_openid' => $ios_openid])->find();
//        if (!$user) {
//            $this->success('选择性别', ['code' => 5]);
//        }
        if ($user) {
            if (!in_array($user->status,[1,2])) {
                $this->error(__('Account is locked'));
            }
            if ($user->frozentime > time()) {
                $this->error('您的账号已被封禁至' . date('Y-m-d H:i'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $reg_data = [
                'register_from' => input('register_from',''),
                'gender' => -1
            ];
            $ret = $this->auth->iosopenid_register($ios_openid,$reg_data);
        }
        if ($ret) {
            $data = $this->userInfo('return');
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }*/

    //苹果账号注册
    /*public function iosregiter(){
        $ios_openid = input('ios_openid', '', 'trim');
        $gender = input('gender', -1, 'intval'); //性别:1=男,0=女
        if (!$ios_openid) {
            $this->error(__('Invalid parameters'));
        }
        if (!in_array($gender, [1, 0])) {
            $this->error('性别错误');
        }

        $user = Db::name('user')->where(['ios_openid' => $ios_openid])->find();
        if ($user) {
            $this->error('账号已经存在,请直接登录');
        }

        $reg_data = [
            'register_from' => input('register_from',''),
            'gender' => $gender
        ];
        $ret = $this->auth->iosopenid_register($ios_openid,$reg_data);

        if ($ret) {
            $data = $this->userInfo('return');
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }*/
    

    //客服
    public function kefu() {
        $type = input('type', 0, 'intval'); //客服位置: 0客服中心  1充值客服
        if (!in_array($type, [0, 1])) {
            $this->error('您的网络开小差啦~');
        }
        if ($type == 0) {
            $user_id = config('site.customer_service_id') ? : 0; //指定客服id
        } else {
            $user_id = config('site.pay_customer_service_id') ? : 0; //指定客服id
        }

        $list = Db::name('user')->field('id')->where(['status' => 1, 'is_kefu' => 1, 'id' => $user_id])->select();
        if (!$list) {
            $this->success('success', $list);
        }

        foreach ($list as $k => &$v) {
            $v['nickname'] = '客服' . ($k + 1);
            $v['avatar'] = config('avatar_girl');
        }

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


    //修改城市
    public function editcity() {
        $name = input('name', '', 'trim'); //城市名
        if ($name === '') {
            $this->error('参数缺失');
        }

        $hometown_cityid = Db::name('area')->where(['name' => $name])->value('id');
        if (!$hometown_cityid) {
            $this->success('修改成功');
        }

        Db::name('user')->where(['id' => $this->auth->id])->setField('hometown_cityid', $hometown_cityid);
        $this->success('修改成功');
    }

    //搜索用户
    public function searchuser() {
        $keyword = input('keyword', '', 'trim'); //昵称或ID
        if ($keyword === '') {
            $this->error('请输入关键字');
        }

        $id = Db::name('user')->where(['nickname|username' => $keyword])->value('id');
        $id = $id ? : 0;

        $this->success('用户', $id);
    }


 
}