<?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\Keyworld;
use think\Db;
use app\common\library\Wechat;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['wxmini_regmobile_login'];
    protected $noNeedRight = '*';

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

    }

    /**
     * 微信小程序登录+注册
     * code得到注册手机号,此手机号登录+注册
     */
    public function wxmini_regmobile_login(){
        $code     = input('code');
        $opencode = input('opencode');
        if (!$code || !$opencode) {
            $this->error(__('Invalid parameters'));
        }

        $config = config('wxMiniProgram');
        $wechat = new Wechat($config['appid'],$config['secret']);

        $getuserphonenumber = $wechat->getuserphonenumber($code);
        if(!isset($getuserphonenumber['phone_info']['purePhoneNumber'])){
            $this->error('授权获取手机号失败');
        }

        //获取openid
        $getopenid = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$opencode.'&grant_type=authorization_code';
        $openidInfo = $this->getJson($getopenid);
        if(!isset($openidInfo['openid'])) {
            $this->error('用户openid获取失败',$openidInfo);
        }

        $openid  = $openidInfo['openid'];
        if (!$openid) {
            $this->error('用户openid获取失败');
        }

        $mobile = $getuserphonenumber['phone_info']['purePhoneNumber'];

        $userInfo = Db::name('user')->where('mobile',$mobile)->find();
        // 判断用户是否已经存在
        if($userInfo) { // 登录
            if ($userInfo['status'] != 1) {
                $this->error(__('Account is locked'));
            }
            if(empty($userInfo['wxmini_openid'])){
                Db::name('user')->where('id',$userInfo['id'])->update(['wxmini_openid'=>$openid]);
            }
            //如果已经有账号则直接登录
            $res = $this->auth->direct($userInfo['id']);
        } else {
            $extend = ['wxmini_openid'=>$openid];
            $res = $this->auth->register('', '', '',$mobile, $extend);
        }
        if($res) {
            $this->success("登录成功!",$this->auth->getUserinfo_simple());
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * json 请求
     * @param $url
     * @return mixed
     */
    private function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }


    //用户详细资料
    public function userInfo(){
        $info = $this->auth->getUserinfo();

        $this->success(__('success'),$info);
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $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 = [
            'avatar','nickname'
        ];

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

            //前端传不了post,改了
            /*if(!request()->has($field,'post')){
                continue;
            }*/
            if(!input('?'.$field)){
                continue;
            }

            $newone = input($field);

            if($field == 'avatar'){
                $newone = input('avatar', '', 'trim,strip_tags,htmlspecialchars');
            }


            $data[$field] = $newone;
        }

        if(empty($data)){
            $this->success();
        }
        $update_rs = Db::name('user')->where('id',$this->auth->id)->update($data);

        $this->success();
    }

    //绑定上级
    public function bind_intro(){
        $introcode = input('introcode','','trim');

        if(!empty($introcode) && $this->auth->isLogin() && empty($this->auth->intro_uid)){
            $intro_user = Db::name('user')->where('introcode',$introcode)->field('id,intro_uid')->find();

            if(!empty($intro_user) && $intro_user['id'] != $this->auth->id && $intro_user['intro_uid'] != $this->auth->id){
                Db::startTrans();
                Db::name('user')->where('id',$this->auth->id)->update(['intro_uid'=>$intro_user['id']]);
                Db::name('user_wallet')->where('user_id',$this->auth->id)->update(['intro_uid'=>$intro_user['id']]);
                Db::commit();
            }
        }

        $this->success();
    }



    //假注销
    public function cancleUser(){
        /*$captcha = input('captcha','');

        if (!$captcha) {
            $this->error(__('Invalid parameters'));
        }

        if (!Sms::check($this->auth->mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }*/

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

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

//////////////////////////////////////////////////////
    //微信登录,预先假注册
    public function wechatlogin(){
        $code = input('code','');
        if(!$code){
            $this->error();
        }
        //微信
        $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_simple();
                $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 bindmobile()
    {
        $mobile  = input('mobile');
        $captcha = input('captcha');
        $code    = input('code');

        if (!$mobile || !$captcha || !$code) {
            $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'));
        }

        $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(__('Logged in successful'), $this->auth->getUserinfo_simple());
        }

        //新的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(__('Logged in successful'), $this->auth->getUserinfo_simple());

    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $oldcaptcha = input('oldcaptcha');
        $mobile = input('mobile');
        $captcha = input('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('原手机号验证码错误');
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error('新手机号验证码错误');
        }

        Sms::flush($user->mobile, 'changemobile');
        Sms::flush($mobile, 'changemobile');

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

        $this->success();
    }
}