package com.sckw.slope.detection.service;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.DictEnum;
import com.sckw.core.model.enums.DictItemEnum;
import com.sckw.core.model.enums.MessageLogEnum;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.web.response.PhpResult;
import com.sckw.excel.utils.DateUtil;
import com.sckw.slope.detection.common.config.SmsTemplateConfig;
import com.sckw.slope.detection.dao.mysql.KwsDeviceReferenceMapper;
import com.sckw.slope.detection.dao.mysql.KwsDictMapper;
import com.sckw.slope.detection.dao.mysql.KwsLogMapper;
import com.sckw.slope.detection.dao.mysql.KwsProjectDeviceMapper;
import com.sckw.slope.detection.dao.tdengine.SlopeDataMapper;
import com.sckw.slope.detection.model.dos.mysql.KwsDeviceReference;
import com.sckw.slope.detection.model.dos.mysql.KwsLog;
import com.sckw.slope.detection.model.dos.tdengine.SlopeData;
import com.sckw.slope.detection.model.dto.HeaderData;
import com.sckw.slope.detection.model.dto.SystemDict;
import com.sckw.slope.detection.model.param.SmsMessageParam;
import com.sckw.slope.detection.model.vo.DeviceIntegrationVo;
import com.sckw.slope.detection.model.vo.QueryDictTypePageReqVo;
import com.sckw.slope.detection.service.api.DetectionApiService;
import com.sckw.slope.detection.utils.MailUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author lfdc
 * @description 公共CommonService
 * @date 2023-10-31 09:10:00
 */
@Slf4j
@Service
@RefreshScope
public class CommonService {
    /**
     * 设备告警短信模板
     */
    private static final String DEVICE_ALARM_SMS_TEMPLATE_CODE = "SMS_464035567";
    /**
     * 数据告警短信模板
     */
    private static final String DATA_ALARM_SMS_TEMPLATE_CODE = "SMS_464050617";

    @Value("${spring.profiles.active}")
    private String isDev;

    @Value("${OkHttpClit.url}")
    String url;

    @Autowired
    DetectionApiService detectionApiService;

    @Autowired
    KwsDictMapper dictMapper;

    @Autowired
    KwsLogMapper logMapper;

    @Autowired
    SlopeDataMapper slopeDataMapper;

    @Autowired
    KwsProjectDeviceMapper projectDeviceMapper;

    public HeaderData getHeaderData(HttpServletRequest request) {
        /**
         * {"companyId":"198","companyName":"四川金顶集团","createBy":"2","createName":"600678","updateBy":"2","updateName":"600678","mountainId":"198"}
         */
        String uInfo = request.getHeader("u_info");
//        String uInfo = "eyJjb21wYW55SWQiOiIxOTgiLCJjb21wYW55TmFtZSI6IuWbm+W3nemHkemhtumbhuWboiIsImNyZWF0ZUJ5IjoiMiIsImNyZWF0ZU5hbWUiOiI2MDA2NzgiLCJ1cGRhdGVCeSI6IjIiLCJ1cGRhdGVOYW1lIjoiNjAwNjc4IiwibW91bnRhaW5JZCI6IjE5OCJ9";
//        if (StringUtils.isBlank(uInfo)) {
//            throw new BusinessException("数据请求异常!");
//        }
        if ("lfdc".equals(isDev)/* || "dev".equals(isDev)*/) {
            uInfo = "eyJjb21wYW55SWQiOiIxOTgiLCJjb21wYW55TmFtZSI6IuWbm+W3nemHkemhtumbhuWboiIsImNyZWF0ZUJ5IjoiMiIsImNyZWF0ZU5hbWUiOiI2MDA2NzgiLCJ1cGRhdGVCeSI6IjIiLCJ1cGRhdGVOYW1lIjoiNjAwNjc4IiwibW91bnRhaW5JZCI6IjE5OCJ9";
        }
        String message = new String(Base64.getDecoder().decode(uInfo));
        log.info("获取请求http数据:{}", message);
        HeaderData headerData = JSONObject.parseObject(message, HeaderData.class);
        log.info("获取解析后请求http数据:{}", JSONObject.toJSONString(headerData));
        /*if (headerData.getMountainId().isBlank()) {
            throw new BusinessException("矿山id不能为空");
        }
        if (headerData.getCompanyId().isBlank()) {
            throw new BusinessException("企业id不能为空");
        }
        if (headerData.getCompanyName().isBlank()) {
            throw new BusinessException("企业名称不能为空");
        }*/
        return headerData;
    }

    public static void main(String[] args) {
        String uinfo = "eyJjb21wYW55SWQiOm51bGwsImNvbXBhbnlOYW1lIjpudWxsLCJjcmVhdGVCeSI6MSwiY3JlYXRlTmFtZSI6Ilx1OGQ4NVx1N2VhN1x1N2JhMVx1NzQwNlx1NTQ1OCIsInVwZGF0ZUJ5IjoxLCJ1cGRhdGVOYW1lIjoiXHU4ZDg1XHU3ZWE3XHU3YmExXHU3NDA2XHU1NDU4IiwibW91bnRhaW5JZCI6bnVsbH0=";
        String message = new String(Base64.getDecoder().decode(uinfo));
        HeaderData headerData = JSONObject.parseObject(message, HeaderData.class);
    }

    public PageRes getDict(QueryDictTypePageReqVo queryDictTypePageReqVo) {
        PageHelper.startPage(queryDictTypePageReqVo.getPage(), queryDictTypePageReqVo.getPageSize());
        List<QueryDictTypePageReqVo> list = dictMapper.selectListAll(queryDictTypePageReqVo);
        PageInfo<QueryDictTypePageReqVo> info = new PageInfo<>();
        return PageRes.build(info, list);
    }

    public Map<String, SystemDict> getDictList(Map<String, Object> mapBody, Map<String, String> mapPara) {
        PhpResult result = detectionApiService.toSaasGetDict(url,
                "/common/getDict", mapBody
                , mapPara);
        Map<String, SystemDict> map = new HashMap(NumberConstant.SIXTEEN);
        if (result.isStatus()) {
            HashMap hashMap = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), HashMap.class);
            for (Object value : hashMap.values()) {
                SystemDict systemDict = JSONObject.parseObject(value.toString(), SystemDict.class);
                map.put(systemDict.getValue(), systemDict);
            }
        }
        return map;
    }


    public Map<String, SystemDict> getDictByDictCode(DictEnum dictEnum) {
        Map<String, SystemDict> dictList = getDictList(null, new HashMap<String, String>() {{
            put("code", dictEnum.getCodeType());
            put("type", "1");
        }});
        return dictList;
    }

    private static final Long equatorial_circumference = 40075020000L;
    private static final Long LATITUDE_REFERENCE = 111000000L;

    @Autowired
    KwsDeviceReferenceMapper deviceReferenceMapper;

    /**
     * 计算xyz值的偏移量  当前只用于计算偏移数据的offset
     *
     * @param value
     * @param itemName
     * @param deviceRelation
     * @return
     */
    public BigDecimal computeOffset(String value, String itemName, KwsDeviceReference deviceRelation) {
        BigDecimal offsetValue = new BigDecimal("0.00");
        if (DictItemEnum.ALTITUDE_Z.getValue().equals(itemName)) {
            offsetValue = new BigDecimal(value).divide(new BigDecimal(1000), 9, BigDecimal.ROUND_HALF_UP);
        }
        BigDecimal subtract = new BigDecimal(value).subtract((deviceRelation == null ? new BigDecimal("0.00") : deviceRelation.getCurrentValue()));
        if (DictItemEnum.LATITUDE_Y.getValue().equals(itemName)) {
            offsetValue = new BigDecimal(LATITUDE_REFERENCE).multiply(subtract);
        }
        double angleInRadians = 0;
        if (DictItemEnum.LONGITUDE_X.getValue().equals(itemName)) {
            KwsDeviceReference deviceReference = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
                    .eq(KwsDeviceReference::getDeviceId, deviceRelation.getDeviceId())
                    .eq(KwsDeviceReference::getType, NumberConstant.ONE)
                    .eq(KwsDeviceReference::getDelFlag, NumberConstant.ZERO)
                    .eq(KwsDeviceReference::getItem, DictItemEnum.LATITUDE_Y.getValue())
                    .last("limit 1")
                    .orderByDesc(KwsDeviceReference::getCreateTime)
            );
            if (deviceReference != null) {
                angleInRadians = deviceReference.getCurrentValue().doubleValue();
            }
            double cosValue = Math.cos(Math.toRadians(angleInRadians));
            double doubleValue = subtract.divide(new BigDecimal("360"), 18, BigDecimal.ROUND_HALF_UP).doubleValue();

            offsetValue = new BigDecimal(equatorial_circumference).multiply(new BigDecimal(cosValue)).multiply(new BigDecimal(doubleValue));
        }
        double number = offsetValue.doubleValue();
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        String result = decimalFormat.format(number);
        return new BigDecimal(result);
    }

    /**
     * 计算xyz值的偏移量  当前只用于计算偏移数据的offset
     *
     * @param value
     * @param itemName
     * @param deviceRelation
     * @return
     */
    public BigDecimal computeOriginalOffset(String value, String itemName, KwsDeviceReference deviceRelation) {
        BigDecimal offsetValue = new BigDecimal("0.00");
        if (DictItemEnum.ALTITUDE_Z.getValue().equals(itemName)) {
            offsetValue = new BigDecimal(value).divide(new BigDecimal(1000), 18, BigDecimal.ROUND_HALF_UP);
        }
        BigDecimal subtract = new BigDecimal(value).subtract((deviceRelation == null ? new BigDecimal("0.00") : deviceRelation.getOriginalValue()));
        if (DictItemEnum.LATITUDE_Y.getValue().equals(itemName)) {
            offsetValue = new BigDecimal(LATITUDE_REFERENCE).multiply(subtract);
        }
        double angleInRadians = 0;
        if (DictItemEnum.LONGITUDE_X.getValue().equals(itemName)) {
            KwsDeviceReference deviceReference = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
                    .eq(KwsDeviceReference::getDeviceId, deviceRelation.getDeviceId())
                    .eq(KwsDeviceReference::getType, NumberConstant.ONE)
                    .eq(KwsDeviceReference::getDelFlag, NumberConstant.ZERO)
                    .eq(KwsDeviceReference::getItem, DictItemEnum.LATITUDE_Y.getValue())
            );
            if (deviceReference != null) {
                angleInRadians = deviceReference.getOriginalValue().doubleValue();
            }
            double cosValue = Math.cos(Math.toRadians(angleInRadians));
            double doubleValue = subtract.divide(new BigDecimal("360"), 18, BigDecimal.ROUND_HALF_UP).doubleValue();
            offsetValue = new BigDecimal(equatorial_circumference).multiply(new BigDecimal(cosValue)).multiply(new BigDecimal(doubleValue));
        }
        return offsetValue;
    }


    /**
     * 根据偏移量，返回测量值
     *
     * @param value
     * @param itemName
     * @param deviceRelation
     * @return
     */
    public BigDecimal getValueByOffset(String value, String itemName, KwsDeviceReference deviceRelation,String snCode) {
        BigDecimal offsetValue = new BigDecimal("0.00");
        if (DictItemEnum.ALTITUDE_Z.getValue().equals(itemName)) {
            offsetValue = new BigDecimal(value).multiply(new BigDecimal(1000));
        }
        //BigDecimal subtract = new BigDecimal(value).subtract((deviceRelation == null ? new BigDecimal("0.00") : deviceRelation.getCurrentValue()));
        if (DictItemEnum.LATITUDE_Y.getValue().equals(itemName)) {
            SlopeData slopeData = slopeDataMapper.selectListByLine(snCode, DictItemEnum.LATITUDE_Y.getValue());
            String currentY = "0";
            if (!Objects.isNull(slopeData)) {
                currentY = slopeData.getVal();
            }
            offsetValue = new BigDecimal(currentY).subtract(new BigDecimal(value).divide(new BigDecimal(LATITUDE_REFERENCE), 18, BigDecimal.ROUND_HALF_UP));
        }
        double angleInRadians = 0;
        if (DictItemEnum.LONGITUDE_X.getValue().equals(itemName)) {
            KwsDeviceReference deviceReference = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
                    .eq(KwsDeviceReference::getDeviceId, deviceRelation.getDeviceId())
                    .eq(KwsDeviceReference::getType, NumberConstant.ONE)
                    .eq(KwsDeviceReference::getDelFlag, NumberConstant.ZERO)
                    .eq(KwsDeviceReference::getItem, DictItemEnum.LATITUDE_Y.getValue())
            );
            if (deviceReference != null) {
                angleInRadians = deviceReference.getCurrentValue().doubleValue();
            }
            double cosValue = Math.cos(Math.toRadians(angleInRadians));
            BigDecimal doubleValue = new BigDecimal(value).multiply(new BigDecimal(360));//offset*360
            BigDecimal offsetValue1 = new BigDecimal(equatorial_circumference).multiply(new BigDecimal(cosValue));// L*cos(A)
            BigDecimal xTmp = doubleValue.divide(offsetValue1, 18, BigDecimal.ROUND_HALF_UP);
            SlopeData slopeData = slopeDataMapper.selectListByLine(snCode, DictItemEnum.LONGITUDE_X.getValue());
            String currentX = "0";
            if (!Objects.isNull(slopeData)) {
                currentX = slopeData.getVal();
            }
            offsetValue = new BigDecimal(currentX).subtract(xTmp);//
        }
        return offsetValue;
    }

    public int insertLog(MessageLogEnum messageLogEnum, HeaderData headerData, Map<String, Object> logMap, Long operationBy) {
        String content = com.sckw.core.utils.StringUtils.replaceTextVar(messageLogEnum.getContent(), logMap);
        KwsLog log = new KwsLog();
        log.setId(new IdWorker(NumberConstant.ONE).nextId());
        log.setType(messageLogEnum.getCode());
        log.setCompanyId(headerData.getCompanyId());
        log.setMountainId(headerData.getMountainId());
        log.setContent(content);
        log.setCreateBy(operationBy);
        log.setCreateTime(LocalDateTime.now());
        return logMapper.insert(log);
    }

    //集成要数判断
    public double returnIntegrationData(String snCode, List<SlopeData> data, DeviceIntegrationVo inter) {

        BigDecimal offsetValue = new BigDecimal("0.00");
        BigDecimal subtract = new BigDecimal(data.get(0).getVal()).subtract(new BigDecimal(data.get(1).getVal()));
        Date newD = data.get(0).getTs();
        Date oldD = data.get(1).getTs();
        double diff = (newD.getTime() - oldD.getTime()) / (1000 * 60 * 60.0);
        //判断集成要素
        if (DictItemEnum.LONGITUDE_X.getValue().equals(inter.getPartNames())) {
            List<SlopeData> y = slopeDataMapper.selectListByTwoLine(snCode, DictItemEnum.LATITUDE_Y.getValue());
            double angleInRadians = Double.parseDouble(y.get(1).getVal());
            double cosValue = Math.cos(Math.toRadians(angleInRadians));

            double doubleValue = subtract.divide(new BigDecimal("360"), 18, BigDecimal.ROUND_HALF_UP).doubleValue();
            offsetValue = new BigDecimal(equatorial_circumference).multiply(new BigDecimal(cosValue)).multiply(new BigDecimal(doubleValue));
        }
        if (DictItemEnum.LATITUDE_Y.getValue().equals(inter.getPartNames())) {
            offsetValue = new BigDecimal(LATITUDE_REFERENCE).multiply(subtract);
        }
        if (DictItemEnum.ALTITUDE_Z.getValue().equals(inter.getPartNames())) {
            offsetValue = subtract.divide(new BigDecimal(1000), 9, BigDecimal.ROUND_HALF_UP);
        }
        if (inter.getFormula().equals(String.valueOf(NumberConstant.ONE))) {//加速度(a-a’)/t²   formula=1
            BigDecimal t = new BigDecimal(diff).multiply(new BigDecimal(diff));
            return offsetValue.divide(t, 9, BigDecimal.ROUND_HALF_UP).doubleValue();

        } else if (inter.getFormula().equals(String.valueOf(NumberConstant.TWO))) {//速度(a-a’)/t    formula=2
            return offsetValue.divide(new BigDecimal(diff), 9, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        return 0;
    }

    public Map<String, List<Object>> getDateByNull(String dateStart, String dateEnd, String[] arr) throws ParseException {
        Map<String, List<Object>> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
        Date start = sdf.parse(dateStart);
        Date end = sdf.parse(dateEnd);

        for (String ar : arr) {
            Date temp = start;
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(start);
            List<Object> list = new ArrayList<>();

            while (temp.getTime() < end.getTime()) {
                Map<Object, Object> map1 = new HashMap<>();
                temp = calendar.getTime();
                map1.put("ts", sdf.format(temp.getTime()));
                list.add(map1);
                calendar.add(Calendar.HOUR_OF_DAY, 1);
            }
            map.put(ar, list);
        }
        return map;
    }

    public List<Object> returnIntegrationDataArray(String snCode, String dateStart, String dateEnd, DeviceIntegrationVo listvo, String key1, String key2) {
        //首先获取全部数据
        String[] partName = {listvo.getPartNames()};
        List<SlopeData> selectedData = slopeDataMapper.selectLineListByArray(snCode, partName, dateStart, dateEnd);
        Map<String, List<Object>> mapList = new HashMap<>();
        List<Object> listTmp = new ArrayList<>();
        for (int i = 0; i < selectedData.size(); i++) {
            if (i + 1 >= selectedData.size()) {
                continue;
            }
            BigDecimal offsetValue = new BigDecimal("0.00");
            double offsetRetrun = 0;
            BigDecimal subtract = new BigDecimal(selectedData.get(i + 1).getVal()).subtract(new BigDecimal(selectedData.get(i).getVal()));
            Date newD = selectedData.get(i + 1).getTs();
            Date oldD = selectedData.get(i).getTs();
            double diff = (newD.getTime() - oldD.getTime()) / (1000 * 60 * 60.0);
            //判断集成要素
            if (DictItemEnum.LONGITUDE_X.getValue().equals(listvo.getPartNames())) {
                //依次获取当前推送的Y轴数据
                List<SlopeData> y = slopeDataMapper.selectListLineByMsgId(snCode, DictItemEnum.LATITUDE_Y.getValue(), selectedData.get(i).getMsgId());
                if (y.size() > 0) {
                    double angleInRadians = Double.parseDouble(y.get(0).getVal());
                    double cosValue = Math.cos(Math.toRadians(angleInRadians));
                    double doubleValue = subtract.divide(new BigDecimal("360"), 18, BigDecimal.ROUND_HALF_UP).doubleValue();
                    offsetValue = new BigDecimal(equatorial_circumference).multiply(new BigDecimal(cosValue)).multiply(new BigDecimal(doubleValue));
                }
            }
            if (DictItemEnum.LATITUDE_Y.getValue().equals(listvo.getPartNames())) {
                offsetValue = new BigDecimal(LATITUDE_REFERENCE).multiply(subtract);
            }
            if (DictItemEnum.ALTITUDE_Z.getValue().equals(listvo.getPartNames())) {
                offsetValue = subtract.divide(new BigDecimal(1000), 9, BigDecimal.ROUND_HALF_UP);
            }
            if (listvo.getFormula().equals(String.valueOf(NumberConstant.ONE))) {//加速度(a-a’)/t²   formula=1
                BigDecimal t = new BigDecimal(diff).multiply(new BigDecimal(diff));
                offsetRetrun = offsetValue.divide(t, 9, BigDecimal.ROUND_HALF_UP).doubleValue();

            } else if (listvo.getFormula().equals(String.valueOf(NumberConstant.TWO))) {//速度(a-a’)/t    formula=2
                offsetRetrun = offsetValue.divide(new BigDecimal(diff), 9, BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            Map<String, Object> map = new HashMap();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(selectedData.get(i + 1).getRawId());
            map.put(key1, time);
            map.put(key2, offsetRetrun);
            listTmp.add(map);
        }
        //mapList.put(listvo.getIntegrationName(),listTmp);
        return listTmp;
    }


    @Autowired
    SmsTemplateConfig smsTemplateConfig;

    @Value("${sms.url}")
    private String smsUrl;

    /**
     * 推送sms短信
     *
     * @param pushToPhone   手机号
     * @param templateCode  模板编码
     * @param signName      签名
     * @param templateParam 请求参数
     */
//    @Async
    public void pushSmsMessage(List<String> pushToPhone, String templateCode, String signName, Map<String, String> templateParam) {
        SmsMessageParam param = new SmsMessageParam();
        param.setCode("");
        param.setType(2);
        param.setPushTo(pushToPhone);
        SmsMessageParam.Content content = new SmsMessageParam.Content();
        content.setTemplateCode(templateCode);
        content.setSignName(signName);
        content.setTemplateParam(templateParam);
        param.setContent(content);
//        Map<String, String> headerMap = new HashMap<>();
//        headerMap.put("sign", PasswordUtils.md5("sign"));
//        headerMap.put("account", "zhangsan");
//        headerMap.put("msgId", UUIDUtils.get32UUID());
        JSONObject jsonObject = detectionApiService.pushSmsMessage(smsUrl, JSONObject.toJSONString(param));
        log.info("推送短信:请求参数：{}，响应结果：{}", JSONObject.toJSONString(param), jsonObject.toString());
    }

    /**
     * 推送邮箱
     *
     * @param emailAddress
     * @param templateParam
     */
//    @Async
    public void pushEmailMessage(List<String> emailAddress, Map<String, Object> templateParam,String title) {
        SmsMessageParam param = new SmsMessageParam();
        param.setCode("");
        param.setType(4);
        param.setPushTo(emailAddress);
        SmsMessageParam.Content content = new SmsMessageParam.Content();
//        String templateStr = "尊敬的${company}用户，在北京时间${time}监测到有${level}级告警被触发；\n" +
//                "设备名称：${name}；\n" +
//                "所属项目：${project}；\n" +
//                "监测数值：${value};\n" +
//                "请在收到邮件后尽快处理，或查阅操作手册文档，确认告警通知相关信息。";
        /**
         * company-公司 (如名称、账号、地址等)；
         * time-时间；
         * level-等级 (如订单号、密码等)；
         * name-设备名称 (如名称、账号、地址等)；
         * project-项目 (如名称、账号、地址等)；
         * value-监测要素值、触发离线时间；
         * type-数值超阈值告警、设备离线告警；
         * element-监测要素、离线超24小时*/
        String templateStr =
                "标题：设备告警通知邮件\n" +
                        "发件人：四川开物信息科技有限公司\n" +
                        "尊敬的${company}用户:\n" +
                        "    在北京时间的${time}，监测到了${level}级告警，告警类型为${type}。\n" +
                        "    设备名称：${name}；\n" +
                        "    所属项目：${project}；\n" +
                        "    设备告警内容：${element}；\n" +
                        "    触发告警值：${value}；\n" +
                        "    请在收到邮件后尽快处理，或查阅操作手册文档，确认告警通知相关信息,以避免造成相关损失。\n" +
                        "                                                                 ${createTime}";
        templateParam.put("createTime", DateUtil.getDateString(new Date(),"yyyy-MM-dd HH:mm:ss"));
        String text = com.sckw.core.utils.StringUtils.replaceTextVar(templateStr, templateParam);
        content.setSubject(title);
        content.setText(text);
        param.setContent(content);
        JSONObject jsonObject = detectionApiService.pushEmailMessage(smsUrl, JSONObject.toJSONString(param));
        log.info("邮件发送 请求参数:{} 返回结果:{}", JSONObject.toJSONString(param), jsonObject.toString());
    }


    /**
     * 推送邮箱
     *
     * @param emailAddress
     * @param templateParam
     */
    public void pushHtmlEmailMessage(List<String> emailAddress, Map<String, String> templateParam,String title) throws IOException {
        SmsMessageParam param = new SmsMessageParam();
        param.setCode("");
        param.setType(4);
        param.setPushTo(emailAddress);
        SmsMessageParam.Content content = new SmsMessageParam.Content();
        String path = CommonService.class.getResource("/template/Email.html").getPath();
        String htmlContent = MailUtil.readResourceFile(path);
        templateParam.put("createTime", DateUtil.getDateString(new Date(),"yyyy-MM-dd HH:mm:ss"));
        String replacedHtml = MailUtil.replacePlaceholders(htmlContent, templateParam);
        content.setSubject(title);
        content.setText(replacedHtml);
        content.setComplexFlag(true);
        param.setContent(content);
        JSONObject jsonObject = detectionApiService.pushEmailMessage(smsUrl, JSONObject.toJSONString(param));
        log.info("邮件发送 请求参数:{} 返回结果:{}", JSONObject.toJSONString(param), jsonObject.toString());
    }

}
