<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\library\Uploadvideo;
use app\utils\RedisKeyEnum;
use app\utils\RedisUtil;
use think\Validate;
use app\common\library\Sms;
/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    public function __construct(){
        $this->error('投票活动结束了');
    }

    //一次注册15w用户
    public function testreg(){
        exit;
        $mobile_s = 19000100000;
        $mobile_e = 19000250000;

        $user = [];
        for($i=$mobile_s;$i<=$mobile_e;$i++){
            $user[] = $this->register($i);
        }

        Db::name('user')->insertAll($user);
    }

    private function register($mobile = '')
    {

        $ip = '127.0.0.1';
        $time = 1731554772;

        $data = [
            'mobile'   => $mobile,
            'avatar'   => '/uploads/20241105/47eb7f0430d48a73346b1630692e20ae.png',
            'nickname'  => $mobile,
            'bind_jigou_id'  => 1,
            'bind_jigou_times'  => 1,
        ];
        $params = array_merge($data, [
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'createtime'  => $time,
            'updatetime'  => $time,
            'status'    => 1
        ]);

        return $params;

    }


    //////////////////////////////////////////////////////
    private function getmobile(){
        $start = 19300000000;
        $mobile = RedisUtil::getInstance(RedisKeyEnum::MOBILE_REGISTER)->incr();
        return $start + $mobile;
    }

    public function auto_register()
    {
        $mobile = $this->getmobile();
        $captcha = '1212';
        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 {
            $ret = $this->auth->register('', '', '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $this->success(__('Logged in successful'), $this->auth->getUserinfo());
        } else {
            $this->error($this->auth->getError());
        }
    }

}