<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\utils\Service\Tencent\TencentIm;
use think\Validate;
use think\Db;
use app\common\library\Wechat;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login','mobilelogin','register','wechatlogin','bindmobile','resetpwd'];
    protected $noNeedRight = '*';

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

    /**
     * 会员中心
     */
    public function index()
    {
    }

    /**
     * 会员登录
     *
     * @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->auth->getUserinfo_smiple();
            $im = new TencentIm();
            $im->register($data['chat_id'],$data['nickname'],$data['avatar']);
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function setCoord()
    {
        $params = $this->request->param();
        $data = [];
        !empty($params['city']) && $data['city'] = $params['city'];
        !empty($params['lng']) && $data['lng'] = $params['lng'];
        !empty($params['lat']) && $data['lat'] = $params['lat'];
        !empty($data) && Db::name('user')->where('id',$this->auth->id)->update($data);
        return $this->success('获取坐标成功');
    }

    /**
     * 手机验证码登录
     *
     * @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(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $this->error('不存在的用户');
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = $this->auth->getUserinfo_smiple();
            $im = new TencentIm();
            $im->register($data['chat_id'],$data['nickname'],$data['avatar']);
            $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()
    {
        $mobile = input('mobile');
        $captcha = input('captcha');
        $password = input('password');

        if (!$mobile || !$captcha || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $captcha, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register('', $password, '', $mobile, []);
        if ($ret) {
            $data = $this->auth->getUserinfo_smiple();
            $im = new TencentIm();
            $im->register($data['chat_id'],$data['nickname'],$data['avatar']);
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

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

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

        $openid = $wxuserinfo['openid'];
        $unionid = $wxuserinfo['unionid'];

        //检查用户
        $user = Db::name('user')->where('unionid',$unionid)->find();
        if ($user) {
            if ($user['status'] == -1) {
                $this->error('账户已注销');
            }
            if ($user['status'] != 1) {
                $this->error(__('Account is locked'));
            }

            /*$update = [
                $field     => $openid,//应该就只有mini支付时用
            ];
            Db::name('user')->where('id',$user['id'])->update($update);*/

            //如果已经有账号则直接登录
            $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,
                'unionid'    => $unionid,
                'from'       => $from,
                'createtime' => time(),
            ];
            $wechatCode = Db::name('wechat_code')->where(['unionid'=>$unionid,'from'=>$from])->find();
            if (empty($wechatCode)) {
                Db::name('wechat_code')->insertGetId($wechatCodeData);
            } else {
                Db::name('wechat_code')->where(['unionid'=>$unionid,'from'=>$from])->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');

        $from = input('from','app');
        $field = $from == 'app' ? 'app_openid' : 'mini_openid';

        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, 'wechatregister');
        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('unionid',$wechatCode['unionid'])->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['unionid'])) {
                Db::name('user')->where('id',$userData['id'])->update([$field => $wechatCode['openid'],'unionid' => $wechatCode['unionid']]);//老用户更新openid
            } else {
                if ($userData['unionid'] != $wechatCode['unionid']) {
                    $this->error('该手机号已被其他用户绑定');
                }
            }
            $ret = $this->auth->direct($userData['id']);
        } else {
            $extend = [
                $field    => $wechatCode['openid'],
                'unionid' => $wechatCode['unionid'],
            ];
            $ret = $this->auth->register('', '','', $mobile, $extend);
        }
        if (!$ret) {
            $this->error($this->auth->getError());
        }

        $this->success(__('Logged in successful'), $this->auth->getUserinfo_simple());

    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    //真注销
    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,
            'app_openid' => 'close_'.$this->auth->app_openid,
            'mini_openid' => 'close_'.$this->auth->mini_openid,
//            'ios_user_id' => 'close_'.$this->auth->ios_user_id,
        ];
        Db::name('user')->where('id',$this->auth->id)->update($data);

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

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

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

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $field_array = ['nickname','avatar'];

        $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);
        if($update_rs === false){
            $this->error('修改资料失败');
        }

        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();

        $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 (\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'));
        }

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

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

    //修改密码
    public function changepwd()
    {
        $mobile = $this->auth->mobile;
        $captcha = input('captcha');
        $newpassword = input('newpassword','');

        if (!$mobile || !$captcha || !$newpassword) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $result = Sms::check($mobile, $captcha, 'changepwd');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        Sms::flush($mobile, 'changepwd');
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }

        $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 $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $mobile = input("mobile");
        $captcha = input("captcha");
        $newpassword = input("newpassword");

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

        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error('不存在的用户');
        }else{
            if ($user->status != 1) {
                $this->error(__('Account is locked'));
            }
        }

        $ret = Sms::check($mobile, $captcha, 'resetpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        Sms::flush($mobile, 'resetpwd');

        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}