<?php
namespace XYCms;
use app\common\model\SmsTemplate as SmsTemplateModel;
use app\common\model\SmsSendLog as SmsSendLogModel;
use think\facade\Cache;
use think\Exception;
use XYCms\Sms;
/**
 * 短信消息推送类
 * @Renloong
 * 2021/03/15
 */
class SmsPush
{
	private $is_send=true;
	private $content='';
	public $sendType='';
	public $mobile='';
	/**
	 * 构造函数，
	 * 读取配置
	 */
	public function __construct()
	{
	}
	public function setTpl($tpl_alias)
	{
        $tpl=Cache::get('SmsTemplate.'.$tpl_alias);
        if (!$tpl) throw new Exception($tpl_alias.':模板不存在');
    	if ($tpl['status']) {
    		$this->content=$tpl['content'];
    	}else{
    		$this->is_send=false;
    	}
    	return $this;
	}
	public function setType($type)
	{
		$this->sendType=$type;
        return $this;
	}
	public function setMobile($mobile)
	{
		$this->mobile=$mobile;
        return $this;
	}
	public function setData($Data)
	{
		foreach ($Data as $k => $v) {
			if(is_string($v))
			$this->content=str_replace('{'.$k.'}',$v,$this->content);
		}
		if(!empty($Data['u'])){
			foreach ($Data['u'] as $k => $v) {
				if(is_string($v))
				$this->content=str_replace('{u.'.$k.'}',$v,$this->content);
			}
		}
        return $this;
	}
	/**
	 * 初始化
	 */
	public function send()
	{
        if ($this->is_send && Cache::get('xycms_message.status_sms')) {
	        try {
	            $Sms=new Sms;
	            $Sms->phone=$this->mobile;
	            $Sms->msg=$this->content;
	            $ret=$Sms->sendSms();
	        } catch (\think\Exception $e) {
				throw new Exception($e->getMessage());
	        }
			$SmsSendLog=new SmsSendLogModel;
			$SmsSendLog->type=$this->sendType;
			$SmsSendLog->username=$this->mobile;
			$SmsSendLog->msg=$content;
			$SmsSendLog->status=0;
			if ($SmsSendLog->save()) {
				return true;
			}else{
				$this->error='记录验证码失败';
				return false;
			}
        }
		throw new Exception('取消推送');
	}
}