<?php
namespace XYCms;
use app\common\model\EmailTemplate as EmailTemplateModel;
use think\facade\Cache;
use think\Exception;
use XYCms\Email;
/**
 * 邮件消息推送类
 * @Renloong
 * 2021/03/15
 */
class EmailPush
{
	private $is_send=true;
	private $content='';
	private $title='';
	public $sendType='';
	public $email='';
	/**
	 * 构造函数，
	 * 读取配置
	 */
	public function __construct()
	{
	}
	public function setTpl($tpl_alias)
	{
        $tpl=Cache::get('EmailTemplate.'.$tpl_alias);
        if (!$tpl) throw new Exception($tpl_alias.':模板不存在');
    	if ($tpl['status']) {
    		$this->title=$tpl['title'];
    		$this->content=$tpl['content'];
    	}else{
    		$this->is_send=false;
    	}
    	return $this;
	}
	public function setEmail($email)
	{
		$this->email=$email;
        return $this;
	}
	public function setData($Data)
	{
		foreach ($Data as $k => $v) {
			if(is_string($v))
			$this->title=str_replace('{'.$k.'}',$v,$this->title);
		}
		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->title=str_replace('{u.'.$k.'}',$v,$this->title);
			}
			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_email')) {
	        try {
	            $Email=new Email;
	            $name=Cache::get('web.name');
	            $ret=$Email->init($this->email,$name,$this->title,$this->content);
				return true;
	        } catch (\think\Exception $e) {
				throw new Exception($e->getMessage());
	        }
        }
		throw new Exception('取消推送');
	}
}