<?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 think\Db;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['emaillogin', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile','register_config'];
    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 emaillogin()
    {
        $account = input('account');
        $password = input('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        //先判断是老师还是学员
        $coach_find = Db::name('coach')->where('email',$account)->find();
        if($coach_find){
            return action('api/coach/user/emaillogin');
        }

        //学员登录
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = $this->auth->getUserinfo();
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $countrycode = input('countrycode',65,'intval');
        $mobile = input('mobile');
        $captcha = input('captcha');
        if (!$countrycode || !$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        /*if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }*/
        $mobile = $countrycode.$mobile;
        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 has been cancelled'));
            }
            if ($user->status != 1) {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            //$ret = $this->auth->register('', '', '', $mobile, []);
            $this->error(__('Account is incorrect'));
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = $this->auth->getUserinfo();
            $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()
    {
        $firstname = input('firstname');
        $lastname  = input('lastname');

        $countrycode = input('countrycode',65,'intval');
        $mobile      = input('mobile');
        $captcha     = input('captcha');

        $email        = input('email');
        $emailcaptcha = input('emailcaptcha');

        $password     = input('password');

        if (!$firstname || !$lastname || !$mobile || !$captcha  || !$email  || !$emailcaptcha || !$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'));
        }*/



        $fullmobile = $countrycode.$mobile;
        $ret = Sms::check($fullmobile, $captcha, 'register');
        if (!$ret) {
            $this->error(__('Mobile Captcha is incorrect'));
        }

        $ret = Ems::check($email, $emailcaptcha, 'register');
        if (!$ret) {
            $this->error(__('Email Captcha is incorrect'));
        }

        $extend = [
            'firstname'    => $firstname,
            'lastname'     => $lastname,
            'simplemobile' => $mobile,
            'height'       => input('height',''),
            'age'          => input('age',''),
            'weight'       => input('weight',''),
            'address'      => input('address',''),
            'knowus'       => input('knowus','')
        ];
        $ret = $this->auth->register('', $password, $email, $fullmobile, $extend);
        if ($ret) {
            $data = $this->auth->getUserinfo();
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    //注册配置,怎么知道我们
    public function register_config(){
        $rs = [
            'Facebook',
            'Instagram',
            'Family and Friends',
            'Google',
            'Whatsapp',
            'Others',
        ];
        $this->success(1,$rs);
    }

    /**
     * 退出登录
     * @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 = ['firstname','lastname','height','age','weight','address','avatar','notice_email','notice_whatsapp','whatsapp'];

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

        Db::name('user')->where('id',$this->auth->id)->update($data);

        $this->success();
    }

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

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

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    /*public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = input('email');
        $captcha = input('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();
        $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'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

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


    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $email = input("email");
        $captcha = input("emailcaptcha");
        $newpassword = input("newpassword");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }

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

    /**
     * 注销账号
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function cancleUser()
    {
        $captcha = input("emailcaptcha");
        if (!$captcha) {
            $this->error(__('Invalid parameters'));
        }

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

        $user = $this->auth->getUser();

        $user->status = -1;

        $user->save();

        $this->auth->logout();

        $this->success("账号注销成功");
    }


}