<?php
namespace app\api\controller;

use taoser\facade\Validate;
use app\model\User as UserModel;

use support\Request;
use support\Response;
use Webman\Captcha\CaptchaBuilder;
use Webman\Captcha\PhraseBuilder;
use Shopwwi\WebmanFilesystem\FilesystemFactory;
use Shopwwi\WebmanFilesystem\Facade\Storage;
use hg\apidoc\annotation as Apidoc;

use think\facade\Db;
/**
 * 公共接口
 */
class CommonController extends BaseController{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    public $noNeedAuth = [];

    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    public $noNeedLogin = ['*'];


    /**
     * 加载初始化
     *
     * @Apidoc\Query("version", type="string", require=true, desc="版本号")
     */
    public function init(Request $request)
    {
        $lang = input('lang','en-US');
        locale( $lang);
        $config = Config('site');
        $disallowFields = [
            'api_token','reward_time_limit',
            'mail_type','mail_smtp_host','mail_smtp_port','mail_smtp_user','mail_smtp_pass','mail_verify_type','mail_from',
            'attachment_category','categorytype','cdkey_category','configgroup','flagtype',
            'languages','forbiddenip','fixedpage','admin_login_captcha',
            'upload_mimetype','upload_multipart','upload_multiple','upload_thumbstyle','upload_previewtpl','upload_timeout','upload_maxsize',
            'yeji_jicha_reward','suanli_rate','agent_expirs_retention','allow_currencys','allow_balance_log',
            'agent_commission_total_rate','agent_commission_layer_rate','differential_commission_total_rate'
        ];
        $config = array_diff_key($config, array_flip($disallowFields));
        if(Request()->client != "web"){
            $config["steps"] = Config('step');
        }
        $config['balance_type_list'] = \app\enum\BalanceType::toArray();
        $config['recharge_status_list'] = \app\enum\RechargeStatus::toArray();
        $config['withdrawl_status_list'] = \app\enum\WithdrawlStatus::toArray();
        $config['server_status_list'] = \app\enum\ServerStatus::toArray();
        return $this->success(__('successful'), $config);
    }

    /**
     * 验证是否升级
     */
    public function checkUpgrade(Request $request)
    {
        $field = 'id,type,force,source,version,content';
    	$verUpdate = new \app\model\Version;
        $version = Input('version');
        $platform = Input('platform');
        $version_wgt = Input('version_wgt');

    	// 查询整包、外链数据
    	$update_data = $verUpdate->where(['type'=>['in', '0,2'], 'status'=>1, 'version'=>['>', $version], 'platform'=>$platform])->field($field)->order('id desc')->find();
    	if($update_data) {
            return $this->success('',$update_data);
        }

    	// 查询WGT数据
    	$update_wgt_data = $verUpdate->where(['type'=>1, 'status'=>1, 'version_wgt'=>['>', $version_wgt], 'platform'=>$platform])->field($field)->order('id desc')->find();
    	if($update_wgt_data) {
            return $this->success('',$update_wgt_data);
        }
        return $this->success('',[]);
    }
    /**
     * 注册会员
     *
     * @Apidoc\Method ("POST")
     * @Apidoc\Param("email", type="string",require=true, desc="邮箱")
     * @Apidoc\Param("password", type="string",require=true, desc="密码")
     * @Apidoc\Param("trade_password", type="string",require=true, desc="交易密码")
     * @Apidoc\Param("invite_code", type="string",require=true, desc="推荐码")
     * @Apidoc\Param("code", type="string",require=true, desc="邮箱验证码,event=register")
     */
    public function register()
    {
        $email = input('email');
        $password = input('password');
        $trade_password= input( 'trade_password');
        $username = input('username');
        $mobile = input('mobile');
        $invite_code = input('invite_code');
        $type = input('type');
        if (!in_array($type,Config('site.user_register_way')) ) {
            return $this->error(__('Unknown register way'));
        }
        if ($type == 'email') {
            if(!$email || !Validate::is($email, "email")){
                return $this->error(__('Email is incorrect'));
            }
            $username = $email;
            unset($mobile);
            //captcha_verfiy('email','register',$email,false);
        }
        if ($type == 'mobile') {
            if(!$mobile || !Validate::regex($mobile, "^1\d{10}$")){
                return $this->error(__('Mobile is incorrect'));
            }
            $username = $mobile;
            unset($email);
            //captcha_verfiy('mobile','register',$mobile,false);
        }
        if ($type == 'username') {
            if(!$email || !Validate::is($email, "email")){
                return $this->error(__('Username is incorrect'));
            }
        }
        if (!$password) {
            return $this->error(__('Invalid parameters'));
        }
        // if (!$trade_password) {
        //     return $this->error(__('Invalid trade password'));
        // }else{
        //     $extends['trade_password'] = \plugin\admin\app\common\Util::passwordHash($trade_password);
        // }
        //邀请码
        if ($invite_code) 
        {
            if(strlen($invite_code) == 12){
                //系统生产的一次性推荐吗
                $inviteModel = \app\model\Invitecode::where('code',$invite_code)->find();
                if(!$inviteModel){
                    return $this->error(__('错误的邀请码'));
                }
                $extends['group'] = 2;
                $extends['role_id'] = 1;
                $extends['parent_id'] = 0;
            }else{
                $inviter_user = UserModel::where('invite_code',$invite_code)->field('group,id')->find();
                if(!$inviter_user){
                    return $this->error(__('Invalid invite code'));
                }
                $extends['parent_id'] = $inviter_user['id'];
            }
        }else{
            //return $this->error(__('Invalid invite code'));
        }
        $extends = [
            'role_id'   =>  0,
            'group_id'     =>  0,
            'avatar'    =>  '/static/img/avatar.png',
        ];
        // validate(\app\validate\User::class)
		//     ->scene('edit')
        //     ->check([
        //     'name'  => 'thinkphp',
        //     'email' => 'thinkphp@qq.com',
        // ]);
        try {
            $user = \support\Jwt::register($username, $password, $email, $mobile, $extends);
            if($inviteModel){
                $inviteModel->status = 1;
                $inviteModel->save();
            }
            $data = ['userinfo' => $user];
            // if ($type == 'email') {
            //     captcha_verfiy('email','register',$email,true);
            // }else if ($type == 'mobile') {
            //     captcha_verfiy('mobile','register',$mobile,true);
            // }else{
            //     captcha_verfiy('image','register',$mobile,true);
            // }
            return $this->success(__('Sign up successful'), $data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
    /**
     * 登录
     * @Apidoc\Method("POST")
     * @Apidoc\Param("username", type="string",require=true, desc="用户名")
     * @Apidoc\Param("password", type="string",require=true, desc="密码")
     */
    public function login(Request $request){
        $username = input('username');
        $mobile = input('mobile');
        $email = input('email');
        $password = input('password');
        $type = input(param: 'type');
        if (!$password) {
            return $this->fail(__('Invalid username or password').'0');
        }
        if($type == 'mobile'){
            if (!$mobile ) {
                return $this->fail(__('Invalid username or password').'1');
            }
            $username = $mobile;
        }else if($type == 'email'){
            if (!$email ) {
                return $this->fail(__('Invalid username or password').'2');
            }
            $username = $email;
        }else{
            if (!$username ) {
                return $this->fail(__('Invalid username or password').'3');
            }
        }
        try{
            $user = \support\Jwt::login($username, $password,$type);
            if($user === false){
                return $this->fail(\support\Jwt::getError());
            }
            $user= Hook('user.profile',$user);
            return $this->success(__('successful'), $user[0]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 退出登录
     * @Apidoc\Method("GET")

     */
    public function logout(){
        \support\Jwt::logout();
        return $this->success(__('successful'));
    }
    
    /**
     * 重置密码
     *
     * @Apidoc\Method ("POST")
     * @Apidoc\Param("email", type="string",require=true, desc="邮箱")
     * @Apidoc\Param("newpassword", type="string",require=true, desc="新密码")
     * @Apidoc\Param("code", type="string",require=true, desc="邮箱验证码,event=resetpwd")
     */
    public function resetpwd()
    {
        $email = input("email");
        $mobile = input("mobile");
        $newpassword = input("newpassword");
        if (!$newpassword) {
            return $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            return $this->error(__('Password must be 6 to 30 characters'));
        }
        
        if (!$mobile && !$email){
            try{
                $user = \support\Jwt::getUser();
            }catch(\Exception $e){
                log_alert($e->getMessage());
                $user = false;
            }
            if($user){
                captcha_verfiy('mobile','reset_pwd',$user->mobile);
            }
        }else{
            if ($email && Validate::is($email, "email")) {
                captcha_verfiy('email','reset_pwd',$email);
                $user = UserModel::getByEmail($email);
            }
            if ($mobile && Validate::regex($mobile, "^1\d{10}$")) {
                captcha_verfiy('mobile','reset_pwd',$mobile);
                $user = UserModel::getByMobile($mobile);
            }
        }
        if (!$user) {
            return $this->error(__('Invalid parameters'));
        }
        //模拟一次登录,需不需要充值登录信息?????
        //\support\Jwt::direct($user->id);
        try{
            UserModel::where('id',$user->id)->save([
                'loginfailure' => 0, 
                'password' => \plugin\admin\app\common\Util::passwordHash($newpassword)
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(__('Reset password successful'));
    }
    /**
     * 重置交易密码
     *
     * @Apidoc\Method ("POST")
     * @Apidoc\Param("email", type="string",require=true, desc="邮箱")
     * @Apidoc\Param("newpassword", type="string",require=true, desc="新密码")
     * @Apidoc\Param("code", type="string",require=true, desc="邮箱验证码,event=reset_trade_pwd")
     */
    public function reset_trade_pwd()
    {
        $email = input("email");
        $mobile = input("mobile");
        $newpassword = input("newpassword");
        if (!$newpassword) {
            return $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,6}'])) {
            return $this->error(__('Trade password must be 6 characters'));
        }
        
        if (!$mobile && !$email){
            try{
                $user = \support\Jwt::getUser();
            }catch(\Exception $e){
                log_alert($e->getMessage());
                $user = false;
            }
            if($user){
                captcha_verfiy('mobile','reset_trade_pwd',$user->mobile);
            }
        }else{
            if ($email && Validate::is($email, "email")) {
                captcha_verfiy('email','reset_trade_pwd',$email);
                $user = UserModel::getByEmail($email);
            }
            if ($mobile && Validate::regex($mobile, "^1\d{10}$")) {
                captcha_verfiy('mobile','reset_trade_pwd',$mobile);
                $user = UserModel::getByMobile($mobile);
            }
        }
        if (!$user) {
            return $this->error(__('Invalid parameters'));
        }
        //模拟一次登录,需不需要充值登录信息?????
        //\support\Jwt::direct($user->id);
        try{
            log_alert($user->id.' 重置交易密码'.$newpassword);
            UserModel::where('id',$user->id)->save([
                'trade_password' => \plugin\admin\app\common\Util::passwordHash($newpassword)
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(__('Reset Trade password successful'));
    }
    /**
     * 验证码
     * @Apidoc\Method ("POST")
     * @Apidoc\Param("type", type="string",require=true, desc="GET参数,类型,email:邮箱验证码,image:图片验证码")
     * @Apidoc\Param("event", type="string",require=true, desc="事件,regiser:注册，resetpwd：重置密码,withdrawl:提现")
     * @Apidoc\Param("email", type="string",require=true, desc="邮箱,可选")
     */
    public function captcha(Request $request){
        $debug = true;
        $request->input('type');
        $type = $request->input('type');
        $event = $request->input('event');
        if($type == 'email'){
            $email = $request->input('email');
            if(!$email){
                try {
                    $user = \support\Jwt::getUser();
                    $email = $user->email;
                } catch (\Exception $th) {
                    return $this->error(__('Incoret param'));
                }
            }
            $key = 'captcha_'.$event.'_'.$email;
            $list  = cache($key);
            $list = $list ?:[];
            $expris = 60;
            if(cache('?exp_'.$key)){
                if(cache('exp_'.$key)+$expris > time()){
                    return $this->fail(__('Only one verification code can be sent within %second% seconds',['%second%'=>$expris]));
                }
            }
            $code =\support\Random::numeric(6);
            $list[$code] = time();
            cache($key,$list);
            cache('exp_'.$key,time());
            // addJob([
            //     'email'     =>  $email,
            //     'title'   => __("Mt email code"),
            //     'event'   => $event,
            //     'code'   => $code
            // ],'Email');
            return $this->success(__('Email sent successfully'),[
                'code'=> $debug ? $code : ''
            ]);
        }elseif($type == 'mobile'){
            $mobile = $request->input('mobile');
            if(!$mobile){
                try {
                    $user = \support\Jwt::getUser();
                    $mobile = $user->mobile;
                } catch (\Exception $th) {
                    return $this->error(__('Incoret param'));
                }
            }
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                return $this->error(__('Mobile is incorrect'));
            }
            $key = 'captcha_'.$event.'_'.$mobile;
            $list  = cache($key);
            $list = $list ?:[];
            $expris = 60;
            if(cache('?exp_'.$key)){
                if(cache('exp_'.$key)+$expris > time()){
                    return $this->fail(__('Only one verification code can be sent within %second% seconds',['%second%'=>$expris]));
                }
            }
            $code =\support\Random::numeric(6);
            $list[$code] = time();
            cache($key,$list);
            cache('exp_'.$key,time());
            addJob([
                'mobile'     =>  $mobile,
                'event'   => $event,
                'code'   => $code
            ],'Sms');
            return $this->success(__('SMS sent successfully'),[
                'code'=> $debug ? $code : ''
            ]);
        }else{
            //TODO 图像验证码没有唯一的KEY
            $key = 'captcha_'.$event.'_';
            //abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ
            $builder = new PhraseBuilder(4, '0123456789');
            $captcha = new CaptchaBuilder(null, $builder);
            $captcha->build(120);
            $code = strtolower($captcha->getPhrase());
            $list[$code] = time();
            cache($key,$list);
            if($request->method() =='GET'){
                $img_content = $captcha->get();
                return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
            }else{
                $img_content = $captcha->inline();
                return json([
                    'code'  =>  0,
                    'msg'   =>  __('successful'),
                    'data'  =>  $img_content
                ]);
            }
        }
    }
    /**
     * 校验验证码
     * @Apidoc\Param("type", type="string",require=true, desc="GET参数,类型,email:邮箱验证码,image:图片验证码")
     * @Apidoc\Param("event", type="string",require=true, desc="事件,register:注册，resetpwd：重置密码,withdrawl:提现")
     * @Apidoc\Param("email", type="string",require=false, desc="邮箱,可选,仅type==email时必填")
     * @Apidoc\Param("code", type="string",require=true, desc="验证码")
     */
    public function verify_captcha(Request $request): Response
    {
        $type = $request->input('type');
        $email = $request->post('email');
        $mobile = $request->input('mobile');
        $event = $request->post('event');
        try {
            if($type == 'email'){
                $result = captcha_verfiy('email', $event , $email,false);
            }elseif($type == 'mobile'){
                $result = captcha_verfiy('mobile', $event , $mobile,false);
            }else{
                $result = captcha_verfiy('image', $event , '',false);
            }
            if(!$result){
                return $this->fail(__('Captcha is incorrect'));
            }
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
        return $this->success(__('successful'));
    }
}