import { OPERATIONALDATATYPE, TABLENAME } from "../config/enum/dbEnum";
import { MAILTYPE } from "../config/enum/enum";
import { ERRORENUM } from "../config/enum/errorEnum";
import { selectData } from "../data/operationalData";
import { successResult } from "../tools/system";
import { BizError } from "../util/bizError";

const nodemailer = require('nodemailer');

// 创建发送邮件的传输对象
let transporter = nodemailer.createTransport({
    host: 'smtp.qq.com', // SMTP 服务器地址
    port: 465, // SMTP 服务器端口（通常是 465 或 587）
    secure: true, // 使用 SSL
    auth: {
        user: '1685675085@qq.com', // 你的邮箱地址
        pass: 'hppnsfvnzzhlbdfh' // 你的邮箱密码或应用专用密码
    }
});

async function send(toMail, name, type, otherStr?, code?) {
    let {title, mailStr} = getModel(name, type, otherStr, code);
    // 设置邮件选项
    let mailOptions = {
        from: '羽翼 <1685675085@qq.com>', // 发送者地址
        to: toMail,
        subject: `羽翼的${title}通知`, // 邮件主题
        // text: 'Hello world?', // 邮件正文（纯文本）
        html: mailStr // 邮件正文（HTML 格式）
    };

    // new promises
    return new Promise((resolve, reject) => {
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                throw new BizError(ERRORENUM.邮件发送失败);
            }
            resolve(info);
        });
    });
}


function getModel(name, type, otherStr?, code?) {
    let str = "";
    let title = "";
    switch (type) {
        case MAILTYPE.通过入孵材料审核:
            str = "您提交的企业材料审核成功，欢迎入驻羽翼孵化器。";
            title = "审核通过";
        break;
        case MAILTYPE.结束企业服务:
            str = otherStr;
            title = "企业服务受理结果";
        break;
    }

    let mailStr = ""
    mailStr +=`<p>尊敬的${name}：</p>`;
    mailStr +=`<p>您好！</p>`;
    mailStr +=`<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;${str}</p>`;

    return {mailStr, title};
}


/**
 * 系统发送邮件
 * @param userId 
 * @param type 
 */
 export async function systemSendMail(eId, type, otherStr?) {
    let userInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, ["eId", "enterpriseName", "uscc", "mail"]);

    if (!userInfo || !userInfo.eId) throw new BizError(ERRORENUM.企业不存在);
    if (!userInfo.mail) {
        new BizError(ERRORENUM.该用户邮箱为空, eId, eId.enterpriseName);
    } else {
        let result = await send(userInfo.mail, userInfo.enterpriseName, type, otherStr);
    }

    return successResult();
}


