<?php

namespace Server\ucenter\api;

use Server\ucenter\UcenterService;

class CodeController extends UcenterService {

    public function main(){
        global $_GPC;
        $username = trim($_GPC['username']);
        if (empty($username)){
            return $this->error("用户名不能为空");
        }
        $verifySend = pdo_fetch("SELECT * FROM ".tablename('uni_verifycode').' WHERE uniacid=:uniacid and receiver=:receiver order by id desc',array(':receiver'=>$username,':uniacid'=>$this->uniacid));
        if (!empty($verifySend) && $verifySend['createtime']+120>TIMESTAMP){
            //2分钟内发送过
            return $this->error("请不要频繁获取验证码");
        }
        if (preg_match($this->REGULAR_MOBILE, $username)){
            $smsService = serv('sms');
            if (!$smsService->enabled){
                return $this->error("未配置短信服务");
            }
            $res = $smsService->sendVerifyCode($username);
            if (is_error($res)) return $res;
        }elseif(!preg_match($this->REGULAR_EMAIL, $username)){
            return $this->error("用户名格式不正确");
        }
        $verifyCode = random(5,true);
        $verifyId = pdo_insertgetid("uni_verifycode", array('uniacid'=>$this->uniacid,'receiver'=>$username,'verifycode'=>$verifyCode,'total'=>0,'createtime'=>TIMESTAMP,'failed_count'=>0));
        if (empty($verifyId)) return $this->error("发送失败，请重试");
        $res = $this->sendEmailCode($username, $verifyCode);
        if (is_error($res)){
            pdo_delete('uni_verifycode', array('receiver' => $username));
            return $res;
        }
        return $this->success("发送成功！");
    }

}
