package com.rongwei.bscommon.sys.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rongwei.bscommon.sys.fegin.SysNotifyFeginService;
import com.rongwei.bsentity.domin.SrmIssuesListDo;
import com.rongwei.commonservice.service.SysConfigService;
import com.rongwei.rwcommon.vo.MailDo;
import com.rongwei.rwcommonentity.commonservers.domain.SysConfigDo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author ：henry
 * @description：TODO
 * @date ：2023/4/17 22:47
 */
@Component
public class NoticeUtils {

    @Autowired
    private SysNotifyFeginService sysNotifyFeginService;

    @Autowired
    private SysConfigService sysConfigService;


    /**
     * 发送邮件
     *
     * @param saveIssueList
     */
    public void notice(List<SrmIssuesListDo> saveIssueList) {

        if(ObjectUtil.isEmpty(saveIssueList)) {
            return ;
        }

        saveIssueList.forEach(this::accept);
    }

    /**
     * 获取配置连接
     *
     * @return
     */
    private String getConfigUrl() {
        SysConfigDo globalConfigObj = sysConfigService.getObjByConfigCode("global_config");
        if(ObjectUtil.isNull(globalConfigObj) || ObjectUtil.isEmpty(globalConfigObj.getRoption())) {
            return "";
        }

        JSONObject globalConfigJo = JSONUtil.parseObj(globalConfigObj.getRoption());

        if(ObjectUtil.isNull(globalConfigJo)) {
            return "";
        }

        JSONObject configs = globalConfigJo.getJSONObject("config");
        if(ObjectUtil.isNull(configs)) {
            return "";
        }

        return configs.getStr("notice_email_link", "");
    }

    private void accept(SrmIssuesListDo item) {
        StringBuilder sb = new StringBuilder();
        sb.append("【");
        sb.append(item.getQuestiontitle());
        sb.append("】");
        sb.append("【");
        sb.append(item.getPsinitiator());
        sb.append("】");
        sb.append("需要");
        sb.append("【");
        String format = DateUtil.format(DateUtil.offsetHour(item.getCreatedate(), 48), "yyyy-MM-dd");
        sb.append(format);
        sb.append("】");
        sb.append("前维护问题描述并提交流程。");
        sb.append(getConfigUrl());

        MailDo mailDo = new MailDo();
        String[] ccemial = new String[0];
        String[] receive = {item.getPsinitiatorid()};
        mailDo.setReceiveEmail(receive);
        mailDo.setNeedTransReceive(true);
        mailDo.setOperationtype("10");
        mailDo.setCcEmail(ccemial);
        mailDo.setContent(sb.toString());
        mailDo.setSubject("问题跟踪与解决-".concat(item.getQuestiontitle()));
        sysNotifyFeginService.sendHtmlMail(mailDo);
    }
}
