<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */


namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use think\Db;

class Emailconfig extends Permissions
{
    public function index()
    {
        $data = \app\common\model\Emailconfig::get(1);
        $this->assign('data', $data);
        $grouptabs = (new \app\common\model\ConfigTab())->order('sort desc')->select();
        $this->assign('tabs', $grouptabs);
        return $this->fetch();
    }

    public function publish()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $validate = new \think\Validate([
                ['from_email', 'require|email', '发件箱不能为空|发件箱格式不正确'],
                ['from_name', 'require', '发件人不能为空'],
                ['smtp', 'require', '邮箱smtp服务器不能为空'],
                ['username', 'require|email', '登录账户不能为空|登录账户应为邮箱格式'],
                ['password', 'require', '登录密码不能为空'],
                ['content', 'require', '邮件模板不能为空'],
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }

            if (false == Db::name('emailconfig')->where('email', 'email')->update($post)) {
                $this->error('提交失败');
            } else {
                $this->success('提交成功', 'admin/emailconfig/index');
            }
        } else {
            $this->error('非法请求');
        }
    }

    //测试发送
    public function mailto()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $validate = new \think\Validate([
                ['email', 'require|email', '收件箱不能为空|收件箱格式不正确'],
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }

            $to_email = $post['email'];
            $data = \app\common\model\Emailconfig::get(1);
            $title = $data['title'];
            $content = str_replace(['{nickname}', '{code}', '{passport}', '{email}', '{time}'], ['tplay1', '1234', 'tplay2', 'tplay@test.com', date('Y-m-d H:i:s', time())], $data['content']);
            $from_email = $data['from_email'];
            $from_name = $data['from_name'];
            $smtp = $data['smtp'];
            $username = $data['username'];
            $password = $data['password'];

            if (!$title || !$content || !$from_email || !$from_name || !$smtp || !$username || !$password) {
                $this->error('请先配置发件邮箱信息');
            }

            $mailto = SendMail($to_email, $title, $content, $from_email, $from_name, $smtp, $username, $password);
            if (false == $mailto) {
                $this->error('发送失败');
            } else {
                $this->success('邮件发送成功');
            }
        } else {
            return $this->fetch();
        }
    }
}
