<?php 
namespace sendSms;
use think\facade\Cache;
use think\helper\Str;
use think\Exception;
use app\common\model\SmsSendLog as SmsSendLogModel;
use app\common\model\SmsTemplate as SmsTemplateModel;
use app\common\model\EmailTemplate as EmailTemplateModel;
use XYCms\Sms;
use XYCms\Email;
/**
 * 
 */
class SendSms
{
	public $sendType='';
	public $username='';
	public $vcode='';
	public $action='';
	public $ip='';
	public $template_title='';
	public $template='';
	public $error='';
	function __construct()
	{
		$this->ip=request()->ip();
		$this->action=request()->action();
	}
	public function send()
	{
		return true;
	}
	public function sendVcode()
	{
		$vcode=GetRand(config('sms.sms_length'));
		Cache::set($this->sendType.'.'.$this->action.'.text.'.$this->username,$vcode,config('sms.sms_expire'));
		Cache::set($this->sendType.'.'.$this->action.'.user.'.$this->username,$this->username,config('sms.sms_expire'));
		Cache::set($this->sendType.'.'.$this->action.'.time.'.$this->username,time(),config('sms.sms_expire'));
		if ($this->sendType=='mobile') {
	        try {
				$this->getSmsTemplate($this->action);
				$this->setData([
						'code'		=>	$vcode,
						'sms_expire'=>	formatTime(config('sms.sms_expire'))
					]);
	            $Sms=new Sms;
	            $Sms->phone=$this->username;
	            $Sms->msg=$this->template;
	            $ret=$Sms->sendSms();
	        } catch (\think\Exception $e) {
				$this->error=$e->getMessage();
				return false;
	        }
		}elseif ($this->sendType=='email') {
	        try {
				$this->getEmailTemplate($this->action);
				$this->setData([
						'code'		=>	$vcode,
						'sms_expire'=>	formatTime(config('sms.sms_expire'))
					]);
	            $Email=new Email;
	            $name=config('web.name');
	            $ret=$Email->init($this->username,$name,$this->template_title,$this->template);
	            if ($ret!==true) {
	            	$this->error=$ret;
	            	return false;
	            }
	        } catch (\think\Exception $e) {
				$this->error=$e->getMessage();
				return false;
	        }
		}
		$SmsSendLog=new SmsSendLogModel;
		$SmsSendLog->type=$this->sendType;
		$SmsSendLog->ip=$this->ip;
		$SmsSendLog->action=$this->action;
		$SmsSendLog->username=$this->username;
		$SmsSendLog->msg=$this->template;
		$SmsSendLog->status=0;
		if ($SmsSendLog->save()) {
			return true;
		}else{
			$this->error='记录验证码失败';
			return false;
		}
	}
	public function getSmsTemplate($tpl_alias)
	{
        $tpl=Cache::get('SmsTemplate.'.$tpl_alias);
        if (!$tpl){
        	$tpl=SmsTemplateModel::where(['alias'=>$tpl_alias])->find();
        	if($tpl)
        		$tpl=$tpl->toArray();
        }
        if (!$tpl){
	        $tpl=Cache::get('SmsTemplate.default_vcode');
	        if (!$tpl){
	        	$tpl=SmsTemplateModel::where(['alias'=>'default_vcode'])->find();
	        	if($tpl)
	        		$tpl=$tpl->toArray();
	        }
        }
        if (!$tpl) throw new Exception($tpl_alias.':模板不存在');
    	if ($tpl['status']) {
    		$this->template=$tpl['content'];
    	}else{
    		throw new Exception($tpl_alias.':模板不存在');
    	}
	}
	public function getEmailTemplate($tpl_alias)
	{
        $tpl=Cache::get('EmailTemplate.'.$tpl_alias);
        if (!$tpl){
        	$tpl=EmailTemplateModel::where(['alias'=>$tpl_alias])->find();
        	if($tpl)
        		$tpl=$tpl->toArray();
        }
        if (!$tpl){
	        $tpl=Cache::get('EmailTemplate.default_vcode');
	        if (!$tpl){
	        	$tpl=EmailTemplateModel::where(['alias'=>'default_vcode'])->find();
	        	if($tpl)
	        		$tpl=$tpl->toArray();
	        }
        }
        if (!$tpl) throw new Exception($tpl_alias.':模板不存在');
    	if ($tpl['status']) {
    		$this->template_title=$tpl['title'];
    		$this->template=$tpl['content'];
    	}else{
    		throw new Exception($tpl_alias.':模板不存在');
    	}
	}
	public function setData($Data)
	{
    	$webConfig=config('web');
    	$config=[];
    	foreach ($webConfig as $k => $v) {
    		$config['web'.$k]=$v;
    	}
		foreach (array_merge($Data,$config) as $k => $v) {
			$this->template=str_replace('{'.$k.'}',$v,$this->template);
		}
	}
	public function getError()
	{
		return $this->error;
	}
	public function verification()
	{
		$text=Cache::get($this->sendType.'.'.$this->action.'.text.'.$this->username);
		$user=Cache::get($this->sendType.'.'.$this->action.'.user.'.$this->username);
		if ($text==$this->vcode 
			&& $user==$this->username) {
            return true;
		}else{
			$this->error='验证码错误';
			return false;
		}
	}
	public function delVcode()
	{
		Cache::delete($this->sendType.'.'.$this->action.'.text.'.$this->username);
		Cache::delete($this->sendType.'.'.$this->action.'.user.'.$this->username);
		Cache::delete($this->sendType.'.'.$this->action.'.time.'.$this->username);
	}
}