<?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 addons\epay\library\Wechat;

/**
 * 会员接口，登录，注册，修改资料等
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin','wechatlogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'onlogin','getUserOpenid_gzh','jssdkBuildConfig'];
    protected $noNeedRight = '*';

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

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

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

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = input('account');
        $password = input('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = $this->userInfo('return');
            $this->success(__('Logged in successful'), $data);
        } 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 ($user->status != 1) {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
            //亿米
            $ua = input('ua','','trim');
            $this->yimi_advert($ua);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = $this->userInfo('return');
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    /*public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('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 = $this->userInfo('return');
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }*/

    //微信登录+注册
    public function wechatlogin(){
        $nickname = input('nickname','');
        $avatar = input('avatar','');
        $gender = input('gender',1);
        $wechat_openid = input('wechat_openid','');

        if (!$wechat_openid) {
            $this->error(__('Invalid parameters'));
        }
        if($gender != 1){
            $gender = 0;
        }

        $user = \app\common\model\User::getByOpenid($wechat_openid);
        if ($user) {
            if ($user->status != 1) {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            if (!$nickname || !$avatar) {
                $this->error(__('Invalid parameters'));
            }
            $reg_data = ['nickname'=>$nickname,'avatar'=>$avatar,'gender'=>$gender];
            $ret = $this->auth->openid_register($wechat_openid,$reg_data);
            //亿米
            $ua = input('ua','','trim');
            $this->yimi_advert($ua);
        }
        if ($ret) {
            $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 ($user->status != 1) {
                        $this->error(__('Account is locked'));
                    }
                    //如果已经有账号则直接登录
                    $ret = $this->auth->direct($user->id);
                    $is_register = 0;
                } else {
                    $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
                    $is_register = 1;
                    //亿米
                    $ua = input('ua','','trim');
                    $this->yimi_advert($ua);
                }

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

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

    //用户邀请信息
    public function userintroinfo(){
        $intro_num = Db::name('user')->where('intro_uid',$this->auth->id)->count();
        $money_sum = Db::name('user_money_log')->where(['user_id'=>$this->auth->id,'log_type'=>63])->sum('change_value');

        $user_list = Db::name('user')->field('id,avatar,nickname,createtime')->where('intro_uid',$this->auth->id)->autopage()->select();

        $rs = [
            'intro_num' => $intro_num,
            'money_sum' => $money_sum,
            'user_list' => $user_list,
        ];

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

    public function testhaibao(){
        $haibao = $this->haibao($this->auth->id,['introcode'=>$this->auth->introcode]);
        dump($haibao);
    }

    //海报
    public function haibao($player_id,$data){

        //下载页二维码，没必要保留
        $params = [
            'text' => config('site.domain_name').'/index/index/appdownload',
            'size' => 90,
            'logo' => false,
            'label' => false,
            'padding' => 0,
        ];
        $qrCode = \addons\qrcode\library\Service::qrcode($params);
        $qrcode_path = 'uploads/hbplayer/'.date('Ymd');
        mk_dir($qrcode_path);
        $download_qrcode = $qrcode_path.'/download.png';
        $qrCode->writeFile($download_qrcode);

        //海报
        $haibao = $this->createhaibao($download_qrcode,$player_id,$data);

        return $haibao;
    }

    public function createhaibao($download_qrcode,$player_id,$sub_data){

        //背景图
        $background = config('site.domain_name').'/assets/img/haibao.png';
        //海报图片路径
        $new_path = 'uploads/hbplayer/'.date("Ymd").'/';
        mk_dir($new_path);
        $wap_file_name  = $new_path .'wap_player_'. $player_id . '.png';

        //二维码
        $download_qrcode= config('site.domain_name').'/'.$download_qrcode;


        //合成wap图片
        $image = new \addons\poster\library\Image2();
        $imgurl = $image->createPosterImage($background,$download_qrcode,$sub_data['introcode'],$wap_file_name);

        return '/'.$wap_file_name;
    }


    //申请真人认证
    public function apply_real_confirm(){
        $avatar = input('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if(!$avatar){
            $this->error('请上传真人头像');
        }

        Db::startTrans();

        $data = [
            'avatar' => $avatar,
            'real_status' => 1,
        ];
        $rs = Db::name('user')->where('id',$this->auth->id)->update($data);
        if($rs === false){
            Db::rollback();
            $this->error('认证失败');
        }
        //tag任务赠送金币
        //完成本人基本资料 +15金币《所有资料完善，包括真人认证和实名认证》
        $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,5);
        if($task_rs === false){
            Db::rollback();
            $this->error('完成任务赠送奖励失败');
        }
        //完成真人头像 +5金币
        $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,7);
        if($task_rs === false){
            Db::rollback();
            $this->error('完成任务赠送奖励失败');
        }
        //邀请人拿奖励，男性3元
        $intro_money = $this->auth->gender == 1 ? config('site.intro_man_money') : config('site.intro_woman_money');
        if($this->auth->idcard_status == 1 && !empty($this->auth->intro_uid) && $intro_money > 0){
            $task_rs = model('wallet')->lockChangeAccountRemain($this->auth->intro_uid,'money',$intro_money,63,$remark='');
            if($task_rs['status'] === false){
                Db::rollback();
                $this->error($task_rs['msg']);
            }
        }
        //系统消息
        $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证已经审核通过');

        Db::commit();
        $this->success();
    }

    //实名认证信息
    public function idcard_confirm_info(){
        $check = Db::name('user_idconfirm')->where('user_id',$this->auth->id)->order('id desc')->find();
        $this->success('success',$check);
    }

    //申请实名认证
    public function apply_idcard_confirm(){
        $truename = input('truename','');
        $idcard = input('idcard','');
        //$idcard_images = input('idcard_images','');
        $alipay_account = input('alipay_account','');

        if(empty($truename) || empty($idcard) || empty($alipay_account)){
            $this->error('实名认证信息必填');
        }

        if($this->auth->idcard_status == 1){
            $this->error('您已经完成实名认证');
        }

        if($this->auth->idcard_status == 0){
            $this->error('您已经提交实名认证,请等待审核');
        }

        Db::startTrans();
        $check = Db::name('user_idconfirm')->where('user_id',$this->auth->id)->lock(true)->find();
        if(!empty($check)){
            if($check['status'] == 0){
                Db::rollback();
                $this->error('您已经提交实名认证,请等待审核');
            }
            if($check['status'] == 1){
                Db::rollback();
                $this->error('您已经完成实名认证');
            }
        }

        $data = [
            'user_id' => $this->auth->id,
            'truename' => $truename,
            'idcard' => $idcard,
            //'idcard_images' => $idcard_images,
            'alipay_account' => $alipay_account,
            'status' => 0,
            'createtime' => time(),
            'updatetime' => time(),
        ];

        //更新
        $update_rs = Db::name('user')->where('id',$this->auth->id)->update(['idcard_status'=>0]);
        if(!empty($check)){
            $rs = Db::name('user_idconfirm')->where('id',$check['id'])->update($data);
        }else{
            $rs = Db::name('user_idconfirm')->insertGetId($data);
        }

        if(!$rs || !$update_rs){
            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);

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

    /**
     * 修改会员个人信息
     *
     * @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_id','hobby_ids','job_id','marital_id','tag_ids','wages_id','hometown_cityid','hide_is_finishinfo'];

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

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

            $newone = input($field);

            if($field == 'avatar'){
                $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['hobby_ids'])){
            $data['hobby_ids'] = implode(',',explode(',',$data['hobby_ids']));
        }
        if(isset($data['tag_ids'])){
            $data['tag_ids'] = implode(',',explode(',',$data['tag_ids']));
        }
        if(isset($data['introcode'])){
            $intro_user = Db::name('user')->where('introcode',$data['introcode'])->value('id');
            if(!$intro_user){
                $this->error('不存在的邀请人');
            }
            unset($data['introcode']);//别人的邀请码，不能改了自己的
            $data['intro_uid'] = $intro_user;
        }
        //dump($data);
        if(empty($data)){
            $this->error('没有任何改变');
        }

        //默认头像
        //现在没头像，也没穿头像，但是却传了性别
        if($this->auth->avatar == config('site.domain_cdnurl').'/avatar.png' && isset($data['gender']) && $data['avatar'] == config('site.domain_cdnurl').'/avatar.png'){
            if($data['gender'] == 1){
                $data['avatar'] = 'https://meet-1251365327.cos.ap-beijing.myqcloud.com/uploads/20220314/f9277fba97fd76d9ecfc63b506a3674a.png';
            }else{
                $data['avatar'] = 'https://meet-1251365327.cos.ap-beijing.myqcloud.com/uploads/20220314/5030460c05c86774f60123ffea7b78a1.png';
            }
        }
        //默认头像

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

        //tag任务赠送金币
        //上传头像加5金币
        if(isset($data['avatar'])){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,1);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }
        //上传本人语音介绍 10金币
        if(isset($data['audio_bio'])){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,6);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }
        //上传本人五张照片 10金币
        if(isset($data['photo_images']) && count(explode(',',$data['photo_images'])) >= 5){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,8);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }

        //所有资料完成
        $user_info = Db::name('user')->where('id',$this->auth->id)->find();
        if($user_info['avatar'] && $user_info['nickname'] && $user_info['mobile'] && $user_info['audio_bio'] && $user_info['photo_images']){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,5);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }

        Db::commit();
        $this->success();
    }

    public function set_status_switch(){

    }

    /*
     * 修改用户的坐标
     * */
    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 $email   邮箱
     * @param string $captcha 验证码
     */
    /*public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('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();
    }*/

    /**
     * 修改手机号
     *
     * @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 $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'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

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

    /**
     * 微信注册来的，绑定手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    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 $platform 平台名称
     * @param string $code     Code码
     */
    /*public function third()
    {
        $url = url('user/index');
//        $platform = $this->request->post("platform");
        $platform = 'wechat';
        $code = $this->request->post("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);
    }*/

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

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

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

        $this->auth->logout();
        $this->success('注销成功');
    }

    //APP 转化数据统计方案（即：APP 上报对接方案）： 广告主上报激活数据，亿米平台搭建服务系统关联点击&下载数据和广告主提供的所有激活数据，将激活数据归因到对应广告。
    public function yimi_advert($ua = ''){
        //http://trail.e.mi.com/global/log?appId={appid}&info={data}&conv_type={convType}&customer_id={customerId}
        $api_url      = 'http://trail.e.mi.com/global/log?';
        $api_url_test = 'http://trail.e.mi.com/global/test?';

        //应用id 1453045
        //秘钥A(encrypt_key):ZxdIaVHvFqSQYzWD
        //秘钥B(sign_key):uaeWeunykLRnkyLw
        $sign_key = 'uaeWeunykLRnkyLw'; //真的
        $encrypt_key = 'ZxdIaVHvFqSQYzWD';//真的

        $appid = '1453045';
        $conv_type = 'APP_REGISTER';
        $customer_id = '292232';

        //推荐模式
        /*$imei = md5('imei');
        $data = [
            'imei' => '91b9185dba1772851dd02b276a6c969e',
            'oaid' => '5fb96f268628810c',
            'conv_time' => '1504687208890',
            'client_ip' => '127.0.0.1',
            'ua' => 'Dalvik/2.1.0 (Linux; U; Android 11; M2012K11AC Build/RKQ1.200826.002)',
        ];*/

        //采用模式
        if(empty($ua)){
            return true;
        }
        $data = [
            'conv_time' => time().substr(microtime(),2,3),
            'client_ip' => request()->ip(),
            'ua' => $ua,
        ];

        $data_query = http_build_query($data);
        //dump($data_query);

        $property = $sign_key.'&'.urlencode($data_query);
        //dump($property);

        $signature = md5($property);
        //dump($signature);

        $base_data = $data_query .'&sign='.urlencode($signature);
        //echo $base_data;

        $info = urlencode(base64_encode($this->xor_enc($base_data, $encrypt_key)));
        //dump($info);

        $request_url = $api_url.'appId='.$appid.'&info='.$info.'&customer_id='.$customer_id.'&conv_type='.$conv_type;
        //echo $request_url;

        $result = curl_get($request_url);
        //dump($result);
        //日志
        $log = [
            'param' => $base_data,
            'url'   => $request_url,
            'result'=> $result,
            'createtime' => time(),
        ];
        Db::name('yimi_advert')->insertGetId($log);

        return true;
    }

    //亿米 异或加密，解密
    public function xor_enc($str,$key)
    {
        $crytxt = '';
        $keylen = strlen($key);
        for($i=0;$i<strlen($str);$i++)
        {
            $k = $i%$keylen;
            $crytxt .= $str[$i] ^ $key[$k];
        }
        return $crytxt;
    }

    //公众号获取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);
    }

}
