package com.engine.salary.entity.salaryBill.bo;

import cn.hutool.core.io.FileUtil;
import com.cloudstore.dev.api.bean.MessageBean;
import com.cloudstore.dev.api.bean.MessageType;
import com.cloudstore.dev.api.util.Util_Message;
import com.engine.salary.annotation.SalaryFormulaVar;
import com.engine.salary.constant.HrmSalaryPayrollConf;
import com.engine.salary.constant.SalaryArchiveConstant;
import com.engine.salary.constant.SalaryBillConstant;
import com.engine.salary.constant.SalaryTemplateSalaryItemSetGroupConstant;
import com.engine.salary.entity.datacollection.DataCollectionEmployee;
import com.engine.salary.entity.salaryBill.dto.*;
import com.engine.salary.entity.salaryBill.po.SalaryTemplatePO;
import com.engine.salary.entity.salaryformula.dto.SalaryFormulaEmployeeDTO;
import com.engine.salary.enums.salarybill.MessageChannelEnum;
import com.engine.salary.enums.salarybill.SalaryTemplateTextContentPositionEnum;
import com.engine.salary.enums.salarybill.SalaryTemplateWhetherEnum;
import com.engine.salary.util.SalaryDateUtil;
import com.engine.salary.util.SalaryI18nUtil;
import com.engine.salary.util.pdf.HtmlToPdf;
import com.fapiao.neon.util.Base64Utils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.common.MessageUtil;
import weaver.conn.RecordSet;
import weaver.email.EmailWorkRunnable;
import weaver.file.ImageFileManager;
import weaver.general.Util;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.resource.ResourceComInfo;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import static com.engine.salary.constant.HrmSalaryPayrollConf.HAS_SIGN;


public class SalaryBillBO {
    private static final Logger log = LoggerFactory.getLogger(SalaryBillBO.class);


    @Override
    public String toString() {
        return "SalaryBillBO{}";
    }
//
//    /**
//     * 根据模板内容转为工资单模板对象
//     * 注意：不要通过反序列化，可能会因为历史原因修改字段名称而无法序列化
//     *
//     * @param salaryTemplateContent
//     * @return
//     */
//    public static SalaryTemplatePO buildSalaryTemplateContent(String salaryTemplateContent) {
//        Map<String, Object> map = JsonUtil.parseMap(salaryTemplateContent, Object.class);
//        return SalaryTemplatePO.builder()
//                .id(Long.valueOf(map.getOrDefault("id", "0").toString()))
//                .name(map.getOrDefault("name", "").toString())
//                .salarySobId(Long.valueOf(map.getOrDefault("salarySobId", "0").toString()))
//                .useType(Integer.valueOf(map.getOrDefault("useType", "0").toString()))
//                .description(map.getOrDefault("description", "").toString())
//                .emailStatus(Integer.valueOf(map.getOrDefault("emailStatus", "0").toString()))
//                .sendEmailId(Long.valueOf(map.getOrDefault("sendEmailId", "0").toString()))
////                .msgStatus(Integer.valueOf(map.getOrDefault("msgStatus","0").toString()))
////                .imStatus(Integer.valueOf(map.getOrDefault("imStatus","0").toString()))
////                .cloudBridgeStatus(Integer.valueOf(map.getOrDefault("cloudBridgeStatus","0").toString()))
//                .theme(map.getOrDefault("theme", "").toString())
//                .background(map.getOrDefault("background", "").toString())
//                .textContent(map.getOrDefault("textContent", "").toString())
//                .textContentPosition(Integer.valueOf(map.getOrDefault("textContentPosition", "0").toString()))
//                .salaryItemNullStatus(Integer.valueOf(map.getOrDefault("salaryItemNullStatus", "0").toString()))
//                .salaryItemZeroStatus(Integer.valueOf(map.getOrDefault("salaryItemZeroStatus", "0").toString()))
//                .salaryItemSetting(map.getOrDefault("salaryItemSetting", "").toString())
//                .replenishName(map.getOrDefault("replenishName", "").toString())
////                .replTheme(map.getOrDefault("replTheme","").toString())
////                .replBackground(map.getOrDefault("replBackground","").toString())
////                .replTextContent(map.getOrDefault("replTextContent","").toString())
////                .replTextContentPosition(Integer.valueOf(map.getOrDefault("replTextContentPosition","0").toString()))
////                .replSalaryItemNullStatus(Integer.valueOf(map.getOrDefault("replSalaryItemNullStatus","0").toString()))
////                .replSalaryItemZeroStatus(Integer.valueOf(map.getOrDefault("replSalaryItemZeroStatus","0").toString()))
////                .replenishSalaryItemSetting(map.getOrDefault("replenishSalaryItemSetting","").toString())
//                .build();
//    }

    /**
     * 构建人员字段
     * 与SalaryAcctResultBO.buildEmployeeFieldName()的key value对调了一下
     *
     * @return
     */
    public static Map<String, String> buildEmployeeFieldName() {
        Field[] declaredFields = SalaryFormulaEmployeeDTO.class.getDeclaredFields();
        Map<String, String> employeeFieldNameMap = Maps.newHashMapWithExpectedSize(declaredFields.length);
        for (Field declaredField : declaredFields) {
            if (!declaredField.isAnnotationPresent(SalaryFormulaVar.class)) {
                continue;
            }
            SalaryFormulaVar annotation = declaredField.getAnnotation(SalaryFormulaVar.class);
            employeeFieldNameMap.put(SalaryI18nUtil.getI18nLabel(annotation.labelId(), annotation.defaultLabel()), declaredField.getName());
        }
        return employeeFieldNameMap;
    }

    /**
     * 构建工资单中的人员信息
     *
     * @param simpleEmployee
     */
    public static void buildEmployeeInfo(SalaryBillSendDTO salaryBillSendParam, DataCollectionEmployee simpleEmployee) {

        SalaryTemplateSalaryItemSetListDTO employeeInformation = salaryBillSendParam.getEmployeeInformation();
        Map<String, String> employeeField = salaryBillSendParam.getEmployeeField();

        if (employeeInformation == null || simpleEmployee == null) {
            return;
        }
        if (CollectionUtils.isNotEmpty(employeeInformation.getItems())) {
            //获取员工信息的字段名和中文描述的map关系
            SalaryFormulaEmployeeDTO salaryFormulaEmployeeDTO = SalaryFormulaEmployeeDTO.builder()
                    .employeeId(simpleEmployee.getEmployeeId())
                    .taxAgentName(salaryBillSendParam.getTaxAgentName())
                    .departmentName(simpleEmployee.getDepartmentName())
                    .email(StringUtils.isEmpty(simpleEmployee.getEmail()) ? "" : simpleEmployee.getEmail())
                    .sex(simpleEmployee.getSex() == null ? "" : simpleEmployee.getSex())
                    .mobile(StringUtils.isEmpty(simpleEmployee.getMobile()) ? "" : simpleEmployee.getMobile()).jobtitleName(simpleEmployee.getJobtitleName())
                    .status(StringUtils.isEmpty(simpleEmployee.getStatus()) ? "" : simpleEmployee.getStatus())
                    .telephone(StringUtils.isEmpty(simpleEmployee.getTelephone()) ? "" : simpleEmployee.getTelephone())
                    .username(StringUtils.isEmpty(simpleEmployee.getUsername()) ? "" : simpleEmployee.getUsername())
                    .workcode(simpleEmployee.getWorkcode())
                    .idNo(simpleEmployee.getIdNo())
                    .statusName(simpleEmployee.getStatusName())
                    .build();
            List<SalaryTemplateSalaryItemListDTO> items = employeeInformation.getItems();
            // 1.SalaryAcctResultBO.buildEmployeeFieldName()的取法
//            Set<Map.Entry<String, String>> entries = employeeField.entrySet();
//            for (SalaryTemplateSalaryItemListDTO e : items) {
//                Optional<Map.Entry<String, String>> entry = entries.stream().filter(f -> Objects.equals(e.getName(), f.getValue())).findFirst();
//                if (entry.isPresent()) {
//                    String key = entry.get().getKey();
//                    if (StringUtils.isNotBlank(key)) {
//                        String getter = "get" + key.substring(0, 1).toUpperCase() + key.substring(1);
//                        try {
//                            Method method = salaryFormulaEmployeeDTO.getClass().getMethod(getter);
//                            Object invoke = method.invoke(salaryFormulaEmployeeDTO);
//                            e.setSalaryItemValue((String) invoke);
//                        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
//                            log.error("no such method", e);
//                        }
//                    }
//                }
//            }
            // 2.SalaryBillBO.buildEmployeeFieldName()
            for (SalaryTemplateSalaryItemListDTO e : items) {
                String employeeFieldName = employeeField.get(e.getName());
                if (!StringUtils.isEmpty(employeeFieldName)) {
                    String getter = "get" + employeeFieldName.substring(0, 1).toUpperCase() + employeeFieldName.substring(1);
                    try {
                        Method method = salaryFormulaEmployeeDTO.getClass().getMethod(getter);
                        Object invoke = method.invoke(salaryFormulaEmployeeDTO);
                        e.setSalaryItemValue((String) invoke);
                    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
                        log.error("no such method", e);
                    }
                }
            }
        }
    }

    /**
     * 获取工资单标题
     *
     * @return
     */
    public static String getBillTitle(String theme, Date salaryMonth, Long employeeId) {

        String companyName = "";
        if (theme.contains("${companyName}")) {
            if (employeeId != null) {
                ResourceComInfo resourceComInfo = null;
                SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
                try {
                    resourceComInfo = new ResourceComInfo();
                    subCompanyComInfo = new SubCompanyComInfo();
                } catch (Exception e) {
                    log.error("资源异常", e);
                }
                companyName = subCompanyComInfo.getSubCompanyname(resourceComInfo.getSubCompanyID(employeeId + ""));
                companyName = Util.formatMultiLang(companyName);
            }
        }

        return theme.replace("${companyName}", companyName).replace("${salaryMonth}", new SimpleDateFormat("yyyy年MM月").format(salaryMonth));
    }

//    /**
//     * 构建发送消息
//     *
//     * @param e
//     * @param allEmployeeMap
//     * @param salaryBillSendParam
//     * @param currentEmployeeId
//     * @param currentTenantKey
//     * @return
//     */
//    public static SendMessageEntity buildSendMessage(Map<String, Object> e, Map<String, SimpleEmployee> allEmployeeMap, SalaryBillSendDTO salaryBillSendParam, Long currentEmployeeId, String currentTenantKey) {
//        // 构建用户基本信息
//        SalaryBillBO.buildEmployeeInfo(salaryBillSendParam.getEmployeeInformation(), allEmployeeMap.get(e.get("employeeId").toString()), salaryBillSendParam.getEmployeeField());
//        // 消息接收者
//        List<UserEntity> receivers = Collections.singletonList(SalaryBillBO.buildUser(Long.valueOf(e.get("employeeId").toString()), Optional.ofNullable(e.get("email")).orElse("").toString(), currentTenantKey));
//        Entity entity = SalaryBillBO.buildEntity(e.get("id").toString(), currentEmployeeId, salaryBillSendParam.getEntityName());
//        EmailEntity emailInfo = new EmailEntity();
//        // 邮箱打开
//        if (salaryBillSendParam.isEnableEmail()) {
//            String emailContent = SalaryBillBO.buildEmailContent(e, salaryBillSendParam);
//            emailInfo = SalaryBillBO.buildEmailInfo(salaryBillSendParam.getText(), emailContent, salaryBillSendParam.getSalaryTemplate().getSendEmailId());
//        }
//        return SalaryBillBO.buildSendMessageEntity(salaryBillSendParam, receivers, entity, emailInfo);
//    }

    /**
     * 发送Em消息
     */
    public static void sendMsg(SalaryBillSendDTO salaryBillSendParam, Long id, Long employeeId) {
        SalaryTemplatePO template = salaryBillSendParam.getSalaryTemplate();
        String background = template.getBackground();
        String billTitle = getBillTitle(template.getTheme(), salaryBillSendParam.getSalaryDate(), employeeId);
        MessageType messageType = MessageType.newInstance(499); // 消息来源（见文档第四点补充 必填）
        Set<String> userIdList = new HashSet<>(); // 接收人id 必填
        userIdList.add(employeeId.toString());
        String title = billTitle; // 标题
        String context = "点击查看详情"; // 内容
        // PC端链接
        String linkUrl = weaver.general.GCONST.getContextPath() + "/spa/hrmSalary/static/index.html#/main/hrmSalary/mobilepayroll?id=" + id + "&recipient=" + employeeId;
        // 移动端链接
        String linkMobileUrl = weaver.general.GCONST.getContextPath() + "/spa/hrmSalary/static/index.html#/main/hrmSalary/mobilepayroll?type=phone&id=" + id + "&recipient=" + employeeId;
        try {
            MessageBean messageBean = Util_Message.createMessage(messageType, userIdList, title, context, linkUrl, linkMobileUrl);
            messageBean.setCreater(Integer.parseInt(salaryBillSendParam.getSendUser().getUID() + ""));// 创建人id
            messageBean.setBizState("0");// 需要修改消息为已处理等状态时传入,表示消息最初状态为待处理
            messageBean.setTargetId("499|" + id); //消息来源code +“|”+业务id需要修改消息为已处理等状态时传入

            if (StringUtils.isNotBlank(background)) {
                messageBean.setPictureUrl(background);
            } else {
                messageBean.setPictureUrl("/hrm/hrm_e9/images/payroll.jpg?pictype=jpg");
            }
            Util_Message.store(messageBean);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendEmail(Map<String, Object> e, SalaryBillSendDTO salaryBillSendParam) {
        String content = genPayrollHtmlContent(e, salaryBillSendParam);
        // 消息接收者
        String receivers = Optional.ofNullable(e.get("email")).orElse("").toString();
        String title = getBillTitle(salaryBillSendParam.getSalaryTemplate().getTheme(), salaryBillSendParam.getSalaryDate(), Long.valueOf(e.get("employeeId").toString()));

        if (StringUtils.isNotBlank(receivers)) {
            EmailWorkRunnable.threadModeReminder(receivers, title, content);
        }
    }

    public static void genPdf(Map<String, Object> e, SalaryBillSendDTO salaryBillSendParam) {
        String content = genPayrollHtmlContent(e, salaryBillSendParam);
        String yyyyMM = SalaryDateUtil.getFormatYearMonth(salaryBillSendParam.getSalaryDate());

        Long sendId = salaryBillSendParam.getSalarySend().getId();
        Object id = e.getOrDefault("id", 1L);
        String htmlPath = HrmSalaryPayrollConf.GEN_PATH + yyyyMM + File.separator + sendId + File.separator + id + ".html";

        FileUtil.del(htmlPath);
        File touch = FileUtil.touch(htmlPath);
        FileUtil.appendUtf8String(content, touch);

        String pdfPath = HrmSalaryPayrollConf.GEN_PATH + yyyyMM + File.separator + sendId + File.separator + id + ".pdf";
        FileUtil.del(pdfPath);
        HtmlToPdf.convert(HrmSalaryPayrollConf.TO_PDF_TOOL_PATH, htmlPath, pdfPath);
    }

    /**
     * 合并pdff
     *
     * @param pdfPath      最终合并的pdf
     * @param filesToMerge 待合并的pdf
     */
    public static void mergePdf(String pdfPath, List<String> filesToMerge) {

        // 创建PDF合并工具实例
        PDFMergerUtility merger = new PDFMergerUtility();

        // 遍历要合并的PDF文件列表
        for (String file : filesToMerge) {
            if (FileUtil.isFile(file)) {
                try {
                    merger.addSource(file); // 将每个文件添加到合并工具
                } catch (FileNotFoundException e) {
                    log.error("PDF合并失败1", e);
                }
            }
        }
        // 设置合并后的目标文件
        merger.setDestinationFileName(pdfPath);
        try {
            // 执行合并操作
            FileUtil.del(pdfPath);
            merger.mergeDocuments();
        } catch (IOException e) {
            log.error("PDF合并失败2", e);
        }
    }


    @NotNull
    private static String genPayrollHtmlContent(Map<String, Object> e, SalaryBillSendDTO salaryBillSendParam) {
        StringBuilder emailContent = new StringBuilder();
        emailContent.append("<meta charset=\"UTF-8\">");
        emailContent.append("<div class='container' style='position: relative; overflow: auto;'>");
        SalaryBillBO.buildEmailContent(emailContent, e, salaryBillSendParam);
        // 构建水印内容
        buildEmailWatermarkContent(emailContent, e, salaryBillSendParam);
        emailContent.append("</div>");
        return emailContent.toString();
    }


    public static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = 0;
        try {
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            baos.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        byte[] data = baos.toByteArray();
        try {
            is.close();
            baos.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return data;
    }

    public static void sendSMS(Map<String, Object> e, SalaryBillSendDTO salaryBillSendParam) {


        SalaryTemplateSMSSetDTO smsSetting = salaryBillSendParam.getSmsSetting();
        String content = smsSetting != null ? smsSetting.getContent() : "";
        if (StringUtils.isBlank(content)) {
            return;
        }

        content = content.replace("\n", "\r\n")
                .replace("{薪资所属月}", SalaryDateUtil.getFormatYearMonth(salaryBillSendParam.getSalaryDate()));

        for (SalaryTemplateSalaryItemListDTO item : salaryBillSendParam.getEmployeeInformation().getItems()) {
            content = content.replace("{" + item.getName() + "}", Util.null2String(item.getSalaryItemValue()));
        }

        for (SalaryTemplateSalaryItemSetListDTO salaryTemplateSalaryItemSetListDTO : salaryBillSendParam.getSalaryItemSetList()) {
            for (SalaryTemplateSalaryItemListDTO item : salaryTemplateSalaryItemSetListDTO.getItems()) {
                if (content.contains("{" + item.getName() + "}")) {
                    content = content.replace("{" + item.getName() + "}", e.getOrDefault(item.getId() + SalaryArchiveConstant.DYNAMIC_SUFFIX, "").toString());
                }
            }
        }

        try {
            log.info("发送短信内容, {}", content);
            if (e.get("mobile") != null) {
                MessageUtil.sendSMS(e.get("mobile").toString(), content);
            } else {
                log.error("发送短信失败,{}手机号为空", e.getOrDefault("username", ""));
            }
        } catch (Exception ex) {
            log.error("发送短信失败", ex);
        }
    }

//    /**
//     * 构建发送消息
//     *
//     * @return
//     */
//    public static SendMessageEntity buildSendMessageEntity(SalaryBillSendDTO salaryBillSendParam, List<UserEntity> receivers, Entity entity, EmailEntity emailInfo) {
//        SendMessageEntity smg = new SendMessageEntity();
//        // 模块
//        smg.setModule(MessageModule.HRSA);
//        // 事件
//        smg.setEvent(MessageEvent.PAYROLL);
//
//        // 发送者
//        smg.setSender(salaryBillSendParam.getSendUser() == null ? UserEntity.SYSTEM_USER : salaryBillSendParam.getSendUser());
//        // 接收者
//        smg.setReceivers(receivers);
//        // 发送通道
//        smg.setChannels(salaryBillSendParam.getSendChannels());
//
//        // 消息内容
//        smg.setText(salaryBillSendParam.getTitle());
//
//        // 1.im
//        smg.setEntity(entity);
//        // 2.云桥
//        smg.setPcUrl(entity.getPcUrl());
//        smg.setAppUrl(entity.getH5Url());
//        smg.setTitle(salaryBillSendParam.getTitle());
//        smg.setContent(salaryBillSendParam.getTitle());
//        smg.setPicUrl(salaryBillSendParam.getPicUrl());
//        // 3.邮件
//        smg.setEmailInfo(emailInfo);
//
//        return smg;
//    }
//
//    /**
//     * 构建用户
//     *
//     * @return
//     */
//    public static UserEntity buildUser(Long employeeId, String email, String tenantKey) {
//        UserEntity user = new UserEntity(employeeId, tenantKey);
//        if (!StringUtils.isEmpty(email)) {
//            user.setEmail(email);
//        }
//        return user;
//    }

    /**
     * 构建发送通道
     *
     * @param salaryTemplate
     * @return
     */
    public static Set<MessageChannelEnum> buildSendChannels(SalaryTemplatePO salaryTemplate) {
        Set<MessageChannelEnum> channels = new HashSet<>();
        if (salaryTemplate.getMsgStatus() == null || salaryTemplate.getMsgStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue())) {
            channels.add(MessageChannelEnum.MSG);
        }
        if (salaryTemplate.getEmailStatus() != null && salaryTemplate.getEmailStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue()) && MessageUtil.checkSendEmail()) {
            channels.add(MessageChannelEnum.EMAIL);
        }
        if (salaryTemplate.getSmsStatus() != null && salaryTemplate.getSmsStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue()) && MessageUtil.checkSendSMS()) {
            channels.add(MessageChannelEnum.SMS);
        }
        return channels;
    }
//
//    /**
//     * 构建实体
//     *
//     * @param id
//     * @param currentEmployeeId
//     * @param name
//     * @return
//     */
//    public static Entity buildEntity(String id, Long currentEmployeeId, String name) {
//        Entity e = new Entity();
//        e.setId(String.valueOf(IdGenerator.generate()));
//        e.setModule(EntityType.hrmsalary.name());
//        e.setName(name);
//        e.setH5Url("/mobile/salary/mySalaryBill/view/" + id);
////        e.setH5LinkeType(1);
//        e.setPcUrl("/sp/salary/mySalaryBill/view/" + id);
////        e.setPcLinkeType(0);
//
//        // im添加创建人创建时间、可在对应通道的模板中的内容或辅助信息标题等加上变量${creator}$和${createTime}$
//        e.setCreatorId(currentEmployeeId);
//        e.setCreateTime(new Date());
//        return e;
//    }
//
//    /**
//     * 构建邮件信息
//     *
//     * @param emailSubject      邮件主题
//     * @param emailContent      邮件内容
//     * @param mailUserAccountId 邮箱账号id
//     * @return
//     */
//    public static EmailEntity buildEmailInfo(String emailSubject, String emailContent, Long mailUserAccountId) {
//        EmailEntity entity = new EmailEntity();
//        entity.setEmailContent(emailContent);
//        entity.setEmailSubject(emailSubject);
//        // 发送者邮箱
//        entity.setMailUserAccountId(mailUserAccountId);
//        return entity;
//    }
//
//    /**
//     * 构建撤回消息
//     *
//     * @param msgId
//     * @param text
//     * @param title
//     * @param currentEmployeeId
//     * @param currentTenantKey
//     * @return
//     */
//    public static CancleMessageEntity buildCancleMessageEntity(long msgId, String text, String title, Long currentEmployeeId, String currentTenantKey) {
//        CancleMessageEntity cme = new CancleMessageEntity();
//        cme.setMsgId(msgId);
//        // 模块
//        cme.setModule(MessageModule.HRSA);
//        // 事件
//        cme.setEvent(MessageEvent.PAYROLL);
//
//        cme.setText(text);
//
//        Entity entity = new Entity();
//        entity.setId(String.valueOf(IdGenerator.generate()));
//        entity.setModule(EntityType.hrmsalary.name());
//        entity.setName(title);
//        cme.setEntity(entity);
//        UserEntity user = new UserEntity(currentEmployeeId, currentTenantKey);
//        cme.setOperator(user);
//        return cme;
//    }

    /**
     * 构建邮件内容
     * 注意：样式只能在标签style属性中使用，否则样式不生效
     *
     * @param e
     * @param salaryBillSendParam
     * @return
     */
    public static void buildEmailContent(StringBuilder emailContent, Map<String, Object> e, SalaryBillSendDTO salaryBillSendParam) {
        emailContent.append("<div style='display: flex;flex-direction: column;justify-content: flex-start;align-items: center;padding: 16px;background-color: #f6f6f6;width: 850px;margin: 20px auto;box-shadow: 0 0 14px 0 hsla(0,0%,84%,.5);border: 3px solid #fff;'>");
        // 1.标题
        emailContent.append("<div style='width: 100%;min-height: 22px; line-height: 30px; font-family: PingFangSC-Medium;font-size: 22px;color: #020202;font-weight: 500;text-align: center;'>");
//        emailContent.append(salaryBillSendParam.getTitle());
        emailContent.append(getBillTitle(salaryBillSendParam.getSalaryTemplate().getTheme(), salaryBillSendParam.getSalaryDate(), Long.valueOf(e.get("employeeId").toString())));
        emailContent.append("</div>");
        // 2.发送时间
        emailContent.append("<div style='width: 100%;margin-top: 16px;text-align: center;height: 14px;font-family: PingFangSC-Regular;font-size: 14px;color: #999999;line-height: 14px;font-weight: 400;'>");
        emailContent.append(SalaryDateUtil.getFormatLocalDateTime(LocalDateTime.now()));
        emailContent.append("</div>");
        // 3.背景图-base64
//        if (!StringUtils.isEmpty(salaryBillSendParam.getBackgroundBase64())) {
//            emailContent.append("<div style='margin-top: 32px;'><img src='data:image/jpg;base64,");
//            emailContent.append(salaryBillSendParam.getBackgroundBase64());
//            emailContent.append("'/></div>");
//        }
        // 3.背景图-url
//        if (StringUtils.isNotEmpty(salaryBillSendParam.getSalaryTemplate().getBackground())) {
//            emailContent.append("<div style='margin-top: 32px;'><img src='");
//            emailContent.append(salaryBillSendParam.getPicUrl());
//            emailContent.append("'/></div>");
//        }

        // 是否只有一个分组，如果是，则将文本内容放进薪资项目表格前后
        boolean isOnlyOneGroup = salaryBillSendParam.getSalaryItemSetList().stream().filter(st -> CollectionUtils.isNotEmpty(st.getItems())).count() == 1;
        if (isOnlyOneGroup) {
            buildOnlyOneGroupMailMain(emailContent, e, salaryBillSendParam);
        } else {
            buildMailMain(emailContent, e, salaryBillSendParam);
        }

        //签章
        if (HAS_SIGN) {
            RecordSet rs = new RecordSet();
            rs.execute("select * from DocSignature  where hrmresid=" + e.getOrDefault("employeeId", "1") + " order by markid");
            if (rs.next()) {
                int imagefileid = rs.getInt("imagefileid");
                InputStream imageInputStream = ImageFileManager.getInputStreamById(imagefileid);
                byte[] data = readInputStream(imageInputStream);
                String imageBase64 = "data:image/jpeg;base64," + Base64Utils.encodeToString(data);
                emailContent.append("<div style='width: 100%;margin-top: 16px;text-align: right;line-height: 1.5715;font-family: PingFangSC-Regular;font-size: 12px;color: #111111;'>\n" + "           <img style='width: 140px;height: 70px;' src='" + imageBase64 + "'>" + "           </div>");
            }
        }
        emailContent.append("</div>");
    }

    /**
     * 构建邮件内容主体
     *
     * @param emailContent
     * @param e
     * @param salaryBillSendParam
     */
    private static void buildMailMain(StringBuilder emailContent, Map<String, Object> e, SalaryBillSendDTO salaryBillSendParam) {
        // 薪资项是否显示
        boolean isHideNull = salaryBillSendParam.getSalaryTemplate().getSalaryItemNullStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue());
        boolean isHideZero = salaryBillSendParam.getSalaryTemplate().getSalaryItemZeroStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue());
        // 3.文本内容-如果在薪资项目前
        emailContent.append("<div style='width: 100%;margin-top: 16px;text-align: center;min-height: 12px;font-family: PingFangSC-Regular;font-size: 12px;color: #111111;");
        emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContentPosition() == SalaryTemplateTextContentPositionEnum.BEFORE.getValue() ? "" : "display: none");
        emailContent.append("'>");
        emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContent());
        emailContent.append("</div>");
        // 4.薪资项目内容
        emailContent.append("<div style='margin-top: 16px;width: 100%;'>");
        for (SalaryTemplateSalaryItemSetListDTO salaryItemSet : salaryBillSendParam.getSalaryItemSetList()) {
            if (CollectionUtils.isEmpty(salaryItemSet.getItems())) {
                continue;
            }
            emailContent.append(" <div style='margin-bottom: 16px;background-color: #fff;padding: 10px;'>");
            if (!salaryItemSet.getGroupId().equals(SalaryTemplateSalaryItemSetGroupConstant.NO_TYPE_GROUP_ID)) {
                emailContent.append("<div style='line-height: 2.5715;width: 100%;font-family: PingFangSC-Regular;font-size: 14px;box-sizing: border-box;color: #000;font-weight: bold;'>");
                // 4.1.薪资项目组名
                emailContent.append(salaryItemSet.getGroupName());
                emailContent.append("</div>");
            }
            emailContent.append("<table style='table-layout:fixed;border-collapse:collapse;width:100%;border:1px solid rgba(0,0,0,.06);background-color: #fff;'>");
            emailContent.append("<tbody>");
            List<SalaryTemplateSalaryItemListDTO> items = salaryItemSet.getItems();
            List<List<SalaryTemplateSalaryItemListDTO>> itemsPartition = Lists.partition(items, 3);
            itemsPartition.forEach(itemPartition -> {
                emailContent.append("<tr>");
                for (int i = 0; i < itemPartition.size(); i++) {
                    SalaryTemplateSalaryItemListDTO salaryItem = itemPartition.get(i);
                    // 员工基本信息
                    if (salaryItemSet.getGroupId().equals(SalaryTemplateSalaryItemSetGroupConstant.EMPLOYEE_INFO_GROUP_ID) && salaryBillSendParam.getEmployeeInformation() != null) {
                        Optional<SalaryTemplateSalaryItemListDTO> optionalEmpItem = salaryBillSendParam.getEmployeeInformation().getItems().stream().filter(f -> f.getId().equals(salaryItem.getId())).findFirst();
                        // 4.2.员工信息
                        emailContent.append("<th style=\"background-color:#fafafa;padding:16px 24px;color:#000000d9;font-weight:400;font-size:12px;line-height:1.5715;text-align:start;border:1px solid rgba(0,0,0,.06);min-width:100px;max-width:100px\">");
                        emailContent.append((optionalEmpItem.isPresent() ? optionalEmpItem.get().getName() : ""));
                        emailContent.append("</th>");

                        emailContent.append("<td style=\"padding: 16px 24px;display: table-cell;flex: 1;color: #000000d9;font-size: 12px;line-height: 1.5715;word-break: break-word;overflow-wrap: break-word;border-collapse: collapse;border: 1px solid rgba(0,0,0,.06);\">");
                        emailContent.append((optionalEmpItem.isPresent() ? optionalEmpItem.get().getSalaryItemValue() : ""));
                        emailContent.append("</td>");
                    } else {
                        for (Object keyName : e.keySet()) {
                            if ((salaryItem.getId() + SalaryArchiveConstant.DYNAMIC_SUFFIX).equals(keyName.toString())) {
                                boolean isHide = (isHideNull && StringUtils.isEmpty(e.getOrDefault(keyName.toString(), StringUtils.EMPTY).toString()))
                                        ||
                                        (isHideZero && NumberUtils.isCreatable(e.getOrDefault(keyName.toString(), "0").toString())
                                                && BigDecimal.ZERO.compareTo(new BigDecimal(e.getOrDefault(keyName.toString(), "0").toString())) == 0);
                                if (!isHide) {
                                    // 4.2.薪资项目
                                    emailContent.append("<th style=\"background-color:#fafafa;padding:16px 24px;color:#000000d9;font-weight:400;font-size:12px;line-height:1.5715;text-align:start;border:1px solid rgba(0,0,0,.06);min-width:100px;max-width:100px\">");
                                    emailContent.append(salaryItem.getName());
                                    emailContent.append("</th>");

                                    emailContent.append("<td style=\"padding: 16px 24px;display: table-cell;flex: 1;color: #000000d9;font-size: 12px;line-height: 1.5715;word-break: break-word;overflow-wrap: break-word;border-collapse: collapse;border: 1px solid rgba(0,0,0,.06);\">");
                                    emailContent.append(e.get(keyName.toString()));
                                    emailContent.append("</td>");
                                }
                                break;
                            }
                        }
                    }
                }
                emailContent.append("</tr>");
            });
            emailContent.append("</tbody>");
            emailContent.append("</table>");
            emailContent.append("</div>");
        }
        emailContent.append("</div>");
        // 5.文本内容-如果在薪资项目后
        emailContent.append("<div style='width: 100%;margin-top: 16px;text-align: center;min-height: 12px;font-family: PingFangSC-Regular;font-size: 12px;color: #111111;");
        emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContentPosition() == SalaryTemplateTextContentPositionEnum.AFTER.getValue() ? "" : "display: none");
        emailContent.append("'>");
        emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContent());
        emailContent.append("</div>");
    }

    /**
     * 构建邮件内容主体
     * <p>
     * 只有无分类，则将文本内容放进薪资项目表格前后
     *
     * @param emailContent
     * @param e
     * @param salaryBillSendParam
     */
    private static void buildOnlyOneGroupMailMain(StringBuilder emailContent, Map<String, Object> e, SalaryBillSendDTO salaryBillSendParam) {
        // 薪资项是否显示
        boolean isHideNull = salaryBillSendParam.getSalaryTemplate().getSalaryItemNullStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue());
        boolean isHideZero = salaryBillSendParam.getSalaryTemplate().getSalaryItemZeroStatus().equals(SalaryTemplateWhetherEnum.TRUE.getValue());
        // 4.薪资项目内容
        emailContent.append("<div style='margin-top: 16px;width: 100%;'>");
        for (SalaryTemplateSalaryItemSetListDTO salaryItemSet : salaryBillSendParam.getSalaryItemSetList()) {
            if (CollectionUtils.isEmpty(salaryItemSet.getItems())) {
                continue;
            }
            emailContent.append("<div style='margin-bottom: 16px;'>");
            emailContent.append("<div style='margin-top: 16px;width: 100%;display: flex;flex-direction: column;align-items: flex-start;box-sizing: border-box;'>");

            // 3.文本内容-如果在薪资项目前
            emailContent.append("<div style='border: 1px solid #e5e5e5;border-bottom: none;width: 100%;display: flex;justify-content: flex-start;align-items: center;box-sizing: border-box;");
            emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContentPosition() == SalaryTemplateTextContentPositionEnum.BEFORE.getValue() ? "" : "display: none");
            emailContent.append("'>");
            emailContent.append("<div style='min-height: 60px;padding: 0 16px;flex: 2;background: #fbfbfb;border-right: 1px solid #e5e5e5;display: flex;align-items: center;justify-content: left;align-self: stretch;' title={name}>");
            emailContent.append("<span class='text'>");
            emailContent.append(salaryBillSendParam.getRemarkI18n());
            emailContent.append("</span>");
            emailContent.append("</div>");
            emailContent.append("<div style='min-height: 60px;flex: 8;padding-left: 16px;background: #ffffff;display: flex;align-items: center;justify-content: left;'>");
            emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContent());
            emailContent.append("</div>");
            emailContent.append("</div>");

            emailContent.append("<table style='table-layout:fixed;border-collapse:collapse;width:100%;border:1px solid rgba(0,0,0,.06);background-color: #fff;'>");
            emailContent.append("<tbody>");
            List<SalaryTemplateSalaryItemListDTO> items = salaryItemSet.getItems();
            List<List<SalaryTemplateSalaryItemListDTO>> itemsPartition = Lists.partition(items, 3);
            itemsPartition.forEach(itemPartition -> {
                emailContent.append("<tr>");
                for (int i = 0; i < itemPartition.size(); i++) {
                    SalaryTemplateSalaryItemListDTO salaryItem = itemPartition.get(i);
                    for (Object keyName : e.keySet()) {
                        if ((salaryItem.getId() + SalaryArchiveConstant.DYNAMIC_SUFFIX).equals(keyName.toString())) {
                            boolean isHide = (isHideNull && StringUtils.isEmpty(e.getOrDefault(keyName.toString(), StringUtils.EMPTY).toString()))
                                    ||
                                    (isHideZero && NumberUtils.isCreatable(e.getOrDefault(keyName.toString(), "0").toString())
                                            && BigDecimal.ZERO.compareTo(new BigDecimal(e.getOrDefault(keyName.toString(), "0").toString())) == 0);
                            if (!isHide) {
                                // 4.2.薪资项目
                                emailContent.append("<th style=\"background-color:#fafafa;padding:16px 24px;color:#000000d9;font-weight:400;font-size:12px;line-height:1.5715;text-align:start;border:1px solid rgba(0,0,0,.06);min-width:100px;max-width:100px\">");
                                emailContent.append(salaryItem.getName());
                                emailContent.append("</th>");

                                emailContent.append("<td style=\"padding: 16px 24px;display: table-cell;flex: 1;color: #000000d9;font-size: 12px;line-height: 1.5715;word-break: break-word;overflow-wrap: break-word;border-collapse: collapse;border: 1px solid rgba(0,0,0,.06);\">");
                                emailContent.append(e.get(keyName.toString()));
                                emailContent.append("</td>");
                            }
                            break;
                        }
                    }
                }
                emailContent.append("</tr>");
            });


            emailContent.append("</tbody>");
            emailContent.append("</table>");

            // 5.文本内容-如果在薪资项目后
            emailContent.append("<div style='border: 1px solid #e5e5e5;border-bottom: none;width: 100%;display: flex;justify-content: flex-start;align-items: center;box-sizing: border-box;");
            emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContentPosition() == SalaryTemplateTextContentPositionEnum.AFTER.getValue() ? "border-bottom: 1px solid #e5e5e5;" : "display: none");
            emailContent.append("'>");
            emailContent.append("<div style='min-height: 60px;padding: 0 16px;flex: 2;background: #fbfbfb;border-right: 1px solid #e5e5e5;display: flex;align-items: center;justify-content: left;align-self: stretch;' title={name}>");
            emailContent.append("<span class='text'>");
            emailContent.append(salaryBillSendParam.getRemarkI18n());
            emailContent.append("</span>");
            emailContent.append("</div>");

            emailContent.append("<div style='min-height: 60px;flex: 8;padding-left: 16px;background: #ffffff;display: flex;align-items: center;justify-content: left;'>");
            emailContent.append(salaryBillSendParam.getSalaryTemplate().getTextContent());
            emailContent.append("</div>");
            emailContent.append("</div>");

            emailContent.append("</div>");
            emailContent.append("</div>");
        }
        emailContent.append("</div>");
    }


    public static String HRM_Name = "HRM_Name";
    public static String HRM_Num = "HRM_Num";
    public static String HRM_Mobile = "HRM_Mobile";
    public static String HRM_Email = "HRM_Email";
    public static String HRM_CurrentOperatorId = "HRM_CurrentOperatorId";
    public static String HRM_Department = "HRM_Department";
    public static String HRM_SecondDepartment = "HRM_SecondDepartment";
    public static String HRM_CurrentDate = "HRM_CurrentDate";
    public static String HRM_CurrentTime = "HRM_CurrentTime";
    public static String HRM_prefix = "$";

    /**
     * 构建水印
     * <p>
     * 当前所拥有的变量
     * "HRM_Name",当前操作者姓名
     * "HRM_Num",当前操作者编号
     * "HRM_Mobile",当前操作者移动电话
     * "HRM_Email",当前操作者电子邮件
     * "HRM_CurrentOperatorId",当前操作者人员ID
     * "HRM_Department",当前操作者部门
     * "HRM_SecondDepartment",当前操作者分部
     * "HRM_CurrentDate",当前日期
     * "HRM_CurrentTime"当前时间
     *
     * @param emailContent
     * @param e
     * @param salaryBillSendParam
     */
    private static void buildEmailWatermarkContent(StringBuilder emailContent, Map<String, Object> e, SalaryBillSendDTO salaryBillSendParam) {
        if (Objects.isNull(salaryBillSendParam.getWatermarkSetting())) {
            return;
        }
        String emailWmContentTemplate = salaryBillSendParam.getEmailWmContentTemplate();
        List<String> wmTextFieldIds = salaryBillSendParam.getWmTextFieldIds();
        // 没有变量，则直接返回
        if (CollectionUtils.isEmpty(wmTextFieldIds)) {
            emailContent.append(emailWmContentTemplate);
        } else {
            for (String wmTextFieldId : wmTextFieldIds) {
                // 当前操作者姓名
                if (HRM_Name.equals(wmTextFieldId)) {
                    emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_Name, Optional.ofNullable(e.get("username")).orElse(StringUtils.EMPTY).toString());
                    // 当前操作者编号
                } else if (HRM_Num.equals(wmTextFieldId)) {
                    emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_Num, Optional.ofNullable(e.get("jobNum")).orElse(StringUtils.EMPTY).toString());
                    // 当前操作者移动电话
                } else if (HRM_Mobile.equals(wmTextFieldId)) {
                    emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_Mobile, Optional.ofNullable(e.get("mobile")).orElse(StringUtils.EMPTY).toString());
                    // 当前操作者电子邮件
                } else if (HRM_Email.equals(wmTextFieldId)) {
                    emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_Email, Optional.ofNullable(e.get("email")).orElse(StringUtils.EMPTY).toString());
                    // 当前操作者人员ID
                } else if (HRM_CurrentOperatorId.equals(wmTextFieldId)) {
                    emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_CurrentOperatorId, Optional.ofNullable(e.get("id")).orElse(StringUtils.EMPTY).toString());
                    // 当前操作者分部
                } else if (HRM_Department.equals(wmTextFieldId)) {
                    emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_Department, Optional.ofNullable(e.get("department")).orElse(StringUtils.EMPTY).toString());
                } else if (HRM_SecondDepartment.equals(wmTextFieldId)) {
                    emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_SecondDepartment, Optional.ofNullable(e.get("subCompanyName")).orElse(StringUtils.EMPTY).toString());
                    // 当前日期
                } else if (HRM_CurrentDate.equals(wmTextFieldId)) {
                    emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_CurrentDate, SalaryDateUtil.getFormatLocalDate(LocalDate.now()));
                    // 当前时间
                } else if (HRM_CurrentTime.equals(wmTextFieldId)) {
                    emailWmContentTemplate = emailWmContentTemplate.replace(HRM_prefix + HRM_CurrentTime, SalaryDateUtil.getFormatLocalDateTime(LocalDateTime.now()));
                }
            }
            emailContent.append(emailWmContentTemplate);
        }
    }


    /**
     * 获取工资单水印文本动态变量
     *
     * @param domain
     * @param salaryBillWatermark
     * @return
     */
    public static List<String> getWmTextFieldIds(String domain, SalaryBillWatermarkDTO salaryBillWatermark) {
        List<String> wmTextFieldIds = Collections.emptyList();
        // 没有水印、关闭水印、或者系统水印，则不拼接
//        if (Objects.isNull(salaryBillWatermark) || !salaryBillWatermark.getWatermarkStatus() || !SalaryTemplateWatermarkTypeEnum.CUSTOM.getValue().equals(salaryBillWatermark.getWatermarkType())) {
        if (Objects.isNull(salaryBillWatermark) || !salaryBillWatermark.getWatermarkStatus()) {
            return wmTextFieldIds;
        }
        String wmClassify = salaryBillWatermark.getWmSetting().getOrDefault("wmClassify", StringUtils.EMPTY).toString();
        if ("text".equals(wmClassify)) {
            wmTextFieldIds = (List<String>) salaryBillWatermark.getWmSetting().getOrDefault("wmSelectedFieldIds", Collections.emptyList());

            List<String> empFields = Arrays.asList(HRM_Name, HRM_Num, HRM_Mobile, HRM_Email, HRM_CurrentOperatorId, HRM_Department);
            if (wmTextFieldIds.contains(HRM_SecondDepartment)) {
                // 需要查分部
                salaryBillWatermark.getWmSetting().put("needQuerySubDepart", true);
            }
            // 需要查人员
            salaryBillWatermark.getWmSetting().put("needQueryEmp", wmTextFieldIds.stream().anyMatch(empFields::contains));

            salaryBillWatermark.getWmSetting().remove("wmImg");
        } else if ("image".equals(wmClassify)) {
            List<Map<String, Object>> wmImgs = Collections.emptyList();
            try {
                wmImgs = (List<Map<String, Object>>) salaryBillWatermark.getWmSetting().getOrDefault("wmImg", Collections.emptyList());
            } catch (Exception exception) {
                log.error("工资单水印图片转换失败");
            }
            if (CollectionUtils.isNotEmpty(wmImgs)) {
                Map<String, Object> map = wmImgs.get(0);
                String fileid = map.getOrDefault("fileid", StringUtils.EMPTY).toString();
                if (StringUtils.isNotEmpty(fileid)) {

                    String imgSrc = domain + String.format("/weaver/weaver.file.FileDownload?fileid=%s", fileid);
//                    String imgSrc = domain + String.format("/papi/file/preview?type=imgs&fileId=%s&random=123456", fileid);
                    salaryBillWatermark.getWmSetting().put("wmImg", imgSrc);
                }
            }

            salaryBillWatermark.getWmSetting().remove("wmText");
            salaryBillWatermark.getWmSetting().remove("wmSelectedFieldIds");
        }
        // 作为快照，去掉不必要的属性，节省空间
        salaryBillWatermark.getWmSetting().remove("wmOriginText");
        salaryBillWatermark.getWmSetting().remove("pureWmText");
        return wmTextFieldIds;
    }


    public static String buildEmailWmContentTemplate(boolean isEnableEmail, SalaryBillWatermarkDTO watermarkSetting) {
        String emailWmContentTemplate = StringUtils.EMPTY;
        // 没有水印、关闭水印，则不拼接
        if (!isEnableEmail || Objects.isNull(watermarkSetting) || !watermarkSetting.getWatermarkStatus()) {
            return emailWmContentTemplate;
        }
        String wmClassify = watermarkSetting.getWmSetting().getOrDefault("wmClassify", StringUtils.EMPTY).toString();
        String variable = StringUtils.EMPTY;
        if ("text".equals(wmClassify)) {
            variable = watermarkSetting.getWmSetting().getOrDefault("wmText", StringUtils.EMPTY).toString();
        } else if ("image".equals(wmClassify)) {
//            String imgSrc = watermarkSetting.getWmSetting().getOrDefault("wmImg", StringUtils.EMPTY).toString();
//            variable = "<img width='90%' src='" + imgSrc + "' />";
//            watermarkSetting.getWmSetting().put("wmImg", imgSrc);
            // 邮件不支持图片水印
            return emailWmContentTemplate;
        }
        if (StringUtils.isEmpty(variable)) {
            return emailWmContentTemplate;
        }

        String wmNoTransparent = watermarkSetting.getWmSetting().getOrDefault("wmNoTransparent", "0.15").toString();
        double wmRotate = new Double(watermarkSetting.getWmSetting().getOrDefault("wmRotate", 0).toString());
        double noTransparent = new Double(wmNoTransparent) / 100.00;
        StringBuilder emailWmContentTemp = new StringBuilder();
        emailWmContentTemp.append("<div class='water-mark'>");
        emailWmContentTemp.append("<div class='container' style='pointer-events: none; position: absolute; width: 100%; height: 100%; overflow: hidden; z-index: 9999; top: 0px; left: 0px;display: flex; flex-direction: column; justify-content: space-between; align-items: center;'>");
        for (int i = 0; i < 20; i++) {
            emailWmContentTemp.append("<div class='row' style='width: 100%; min-height: 150px ; overflow: hidden; display: flex;justify-content: center;justify-content: center;'>");
            for (int j = 0; j < 8; j++) {
                emailWmContentTemp.append("<div class='item' style='display: flex;flex-direction: column; align-items: center;justify-content: center; min-width: 200px; height: 150px;opacity: " + noTransparent + "; transform: rotate(-" + wmRotate + "deg);'>");
                // 赋值
                emailWmContentTemp.append(variable);
                emailWmContentTemp.append("</div>");
            }
            emailWmContentTemp.append("</div>");
        }
        emailWmContentTemp.append("</div>");
        emailWmContentTemp.append("</div>");
        return emailWmContentTemp.toString();
    }

    public static String handleWmText(String wmText, List<String> wmTextFieldIds, DataCollectionEmployee simpleEmployee) {
        for (String wmTextFieldId : wmTextFieldIds) {
            // 当前操作者姓名
            if (SalaryBillConstant.HRM_Name.equals(wmTextFieldId)) {
                wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_Name, Objects.isNull(simpleEmployee) ? StringUtils.EMPTY : simpleEmployee.getUsername());
                // 当前操作者编号
            } else if (SalaryBillConstant.HRM_Num.equals(wmTextFieldId)) {
                wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_Num, Objects.isNull(simpleEmployee) || StringUtils.isEmpty(simpleEmployee.getWorkcode()) ? StringUtils.EMPTY : simpleEmployee.getWorkcode());
                // 当前操作者移动电话
            } else if (SalaryBillConstant.HRM_Mobile.equals(wmTextFieldId)) {
                wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_Mobile, Objects.isNull(simpleEmployee) || StringUtils.isEmpty(simpleEmployee.getMobile()) ? StringUtils.EMPTY : simpleEmployee.getMobile());
                // 当前操作者电子邮件
            } else if (SalaryBillConstant.HRM_Email.equals(wmTextFieldId)) {
                wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_Email, Objects.isNull(simpleEmployee) || StringUtils.isEmpty(simpleEmployee.getEmail()) ? StringUtils.EMPTY : simpleEmployee.getEmail());
                // 当前操作者人员ID
            } else if (SalaryBillConstant.HRM_CurrentOperatorId.equals(wmTextFieldId)) {
                wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_CurrentOperatorId, Objects.isNull(simpleEmployee) ? StringUtils.EMPTY : simpleEmployee.getEmployeeId().toString());
                // 当前操作者部门
            } else if (SalaryBillConstant.HRM_Department.equals(wmTextFieldId)) {
                wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_Department, Objects.isNull(simpleEmployee) || Objects.isNull(simpleEmployee.getDepartmentName()) ? StringUtils.EMPTY : simpleEmployee.getDepartmentName());
                // 当前操作者分部
            } else if (SalaryBillConstant.HRM_SecondDepartment.equals(wmTextFieldId)) {
                wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_SecondDepartment, Objects.isNull(simpleEmployee) || Objects.isNull(simpleEmployee.getSubcompanyName()) ? StringUtils.EMPTY : simpleEmployee.getSubcompanyName());
                // 当前日期
            } else if (SalaryBillConstant.HRM_CurrentDate.equals(wmTextFieldId)) {
                wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_CurrentDate, SalaryDateUtil.getFormatLocalDate(LocalDate.now()));
                // 当前时间
            } else if (SalaryBillConstant.HRM_CurrentTime.equals(wmTextFieldId)) {
                wmText = wmText.replace(SalaryBillConstant.HRM_prefix + SalaryBillConstant.HRM_CurrentTime, SalaryDateUtil.getFormatLocalDateTime(LocalDateTime.now()));
            }
        }
        return wmText;
    }

}
