package com.ruoyi.postCheck.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.config.CasConfig;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.DeptCode;
import com.ruoyi.common.enums.SysDeptEnum;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.poi.MergedRegionUtils;
import com.ruoyi.postCheck.domain.*;
import com.ruoyi.postCheck.domain.excel.PostPlanExcelBean;
import com.ruoyi.postCheck.mapper.PostAssessmentRatingOtherMapper;
import com.ruoyi.postCheck.service.*;
import com.ruoyi.postCheck.util.cnooc.SendMailUtils;
import com.ruoyi.postCheck.util.excel.create.PostCheckedCreateExcel;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 发送邮件业务层
 *
 * @author csg
 * @date 2024-01-01
 */
@Service
public class PostSendMailServiceImpl implements IPostSendMailService {
    @Autowired
    private CasConfig casConfig;
    @Autowired
    private RuoYiConfig ruoYiConfig;
    @Autowired
    private SendMailUtils sendMailUtils;
    @Autowired
    private ISysPostService sysPostService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private IPostListService postListService;

    @Autowired
    private IPostProgrammeService postProgrammeService;
    @Autowired
    private IPostPlanService postPlanService;
    @Autowired
    private IPostCheckedService postCheckedService;
    @Autowired
    private IPostCheckedProblemService postCheckedProblemService;
    @Autowired
    private PostAssessmentRatingOtherMapper postAssessmentRatingOtherMapper;

    /**
     * 邮件通知-岗位责任制清
     *
     * @param serviceId 业务表单ID
     * @return
     */
    @Override
    public AjaxResult postListSendMail(String serviceType, Long serviceId) {

        String webStartPage = casConfig.getWebStartPage();
        webStartPage = webStartPage.substring(0, webStartPage.lastIndexOf("/"));

        //TODO lyp邮件推送：岗位责任制清单
        String content = null;

        //收件人邮箱
        Set<String> userMailSet = new HashSet<>();
        HashSet<Integer> typeSet = new HashSet<>();

        PostList postListData = postListService.selectPostListById(serviceId);

        String deptName = postListData.getDeptName();
        String postName = postListData.getPostName();
        Integer status = postListData.getStatus();
        //状态：1-待审核；2-审核中；3-通过；4-驳回；
        if (status == PostListEnum.STATUS_PASS.getValue()) {
            return AjaxResult.error("已审核通过无需通知审核人或制单人，请检查！");
        }

        //给审核人发邮件：给未审核通过的部门发送邮件-人力资源部、党建工作部、健康安全环保中心、内控法务部&办公室
        if (serviceType.equalsIgnoreCase("list_approve")) {
            List<PostListInfo> children = postListData.getChildren();
            for (PostListInfo child : children) {
                Integer type = child.getType();
                Integer childStatus = child.getStatus();
                if (childStatus == null || childStatus != PostListEnum.STATUS_PASS.getValue()) {
                    typeSet.add(type);
                }
            }
            userMailSet = selectUserEmailPostList(typeSet);//查邮箱
            String href = webStartPage + "/postResponsibility/inventoryReview";
            content = "尊敬的岗位责任制清单审核人大家好：<br> " +
//                    "&nbsp;&nbsp;&nbsp;&nbsp;" + deptName + "-" + postName + "岗位责任制清单待审核，请登录系统处理。！请点击链接，直达审核页面：" + webStartPage + "/postResponsibility/inventoryReview";
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + deptName + "-" + postName + "岗位责任制清单待审核，请登录系统处理。！请点击链接，直达审核页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        }
        //给制单人发邮件：岗位责任制清单驳回
        else if (serviceType.equalsIgnoreCase("list_create_user")) {
            Long createUserId = postListData.getCreateUserId();
            userMailSet = selectUserEmail(createUserId);//查邮箱
//            <a href="http://www.baidu.com">http://www.baidu.com</a>
            String href = webStartPage + "/postResponsibility/postResponsibilityOrganization";
            content = "尊敬的岗位责任制清单编写人，您好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + deptName + "-" + postName + "岗位责任制清单状态发生变更，请登录系统查看。！请点击链接，直达编辑页面：" + "<a href=\"" + href + "\">" + href + "</a>";
//                    "&nbsp;&nbsp;&nbsp;&nbsp;" + deptName + "-" + postName + "岗位责任制清单状态发生变更，请登录系统查看。！请点击链接，直达编辑页面：" + webStartPage + "/postResponsibility/postResponsibilityOrganization";
        } else {
            return AjaxResult.error("业务类型错误【serviceType = " + serviceType + "】，请检查！");
        }


        boolean flag = false;
        try {
            String address = "";

            for (String email : userMailSet) {
                address += email + ";";
            }
            flag = sendMailUtils.sendFile(content, address, null);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        if (flag)
            return AjaxResult.success("成功");
        else
            return AjaxResult.error("未知错误！");

    }

    /**
     * 邮件通知-岗检方案
     *
     * @param serviceType 业务类型
     * @param serviceId   业务表单ID
     * @return
     */
    @Override
    public AjaxResult postProgrammeSendMail(String serviceType, Long serviceId) {

        String webStartPage = casConfig.getWebStartPage();
        webStartPage = webStartPage.substring(0, webStartPage.lastIndexOf("/"));

        //TODO lyp邮件推送：岗位责任制清单
        String content = null;

        //收件人邮箱
        Set<String> userMailSet = new HashSet<>();


        PostProgramme postProgramme = postProgrammeService.selectPostProgrammeById(serviceId);
        String name = postProgramme.getName();
        Integer status = postProgramme.getStatus();

        //状态：1-待审核；2-审核中；3-通过；4-驳回；
        if (status == PostProgrammeEnum.STATUS_PASS.getValue()) {
            return AjaxResult.error("已审核通过无需通知审核人或制单人，请检查！");
        }

        //给审核人发邮件：给未审核通过的部门发送邮件-人力资源部、党建工作部、健康安全环保中心、内控法务部&办公室
        if (serviceType.equalsIgnoreCase("programme_approve")) {
            List<Long> userIdALlList = new ArrayList<>();
            Integer statusIcfa = postProgramme.getStatusIcfa();
            Integer statusHr = postProgramme.getStatusHr();
            //给内控法务发邮件
            if (statusIcfa == null || statusIcfa != PostProgrammeEnum.STATUS_ICFA_PASS.getValue()) {
                List<Long> userIdList = sysPostService.userHaveAuthorityList(DeptCode.DEPT_HR.getCode());
                userIdALlList.addAll(userIdList);
            }
            //给人力资源发邮件
            if (statusHr == null || statusHr != PostProgrammeEnum.STATUS_HR_PASS.getValue()) {
                List<Long> userIdList = sysPostService.userHaveAuthorityList(DeptCode.DEPT_ICFA.getCode());
                userIdALlList.addAll(userIdList);
            }

            //根据用户ID查邮箱
            List<SysUser> sysUserList = sysUserService.postUserList(null, null, null, null, null, userIdALlList, null);
            for (SysUser sysUser : sysUserList) {
                String email = sysUser.getEmail();
                userMailSet.add(email);
            }
            String href = webStartPage + "/postInspectionPlanning/projectManagement";
            content = "尊敬的岗检方案审核人大家好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + name + "-" + "岗检方案待审核，请登录系统处理。！请点击链接，直达审核页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        }
        //给制单人发邮件：岗位责任制清单驳回
        else if (serviceType.equalsIgnoreCase("programme_create_user")) {
            Long createUserId = postProgramme.getCreateUserId();
            userMailSet = selectUserEmail(createUserId);//查邮箱

            String href = webStartPage + "/postInspectionPlanning/projectManagement";
            content = "尊敬的岗检方案编写人，您好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + name + "-" + "岗检方案状态发生变更，请登录系统查看。！请点击链接，直达编辑页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        } else {
            return AjaxResult.error("业务类型错误【serviceType = " + serviceType + "】，请检查！");
        }

        boolean flag = false;
        try {
            String address = "";

            for (String email : userMailSet) {
                address += email + ";";
            }
            flag = sendMailUtils.sendFile(content, address, null);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        if (flag)
            return AjaxResult.success("成功");
        else
            return AjaxResult.error("未知错误！");
    }


    /**
     * 邮件通知-岗检计划
     *
     * @param serviceType 业务类型
     * @param serviceId   业务表单ID
     * @return
     */
    @Override
    public AjaxResult postPalnSendMail(String serviceType, Long serviceId) {
        String webStartPage = casConfig.getWebStartPage();
        webStartPage = webStartPage.substring(0, webStartPage.lastIndexOf("/"));

        //TODO lyp邮件推送：岗位责任制清单
        String content = null;

        //收件人邮箱
        Set<String> userMailSet = new HashSet<>();
        //附件路径：绝对磁盘路径
        JSONArray filePathArray = new JSONArray();


        PostPlan postPlanDB = postPlanService.selectPostPlanById(serviceId);
        String name = postPlanDB.getName();
        Integer status = postPlanDB.getStatus();
        //给审核人发邮件：审核顺序内控法务、人力资源，后台根据当前状态自动判断需要给谁发送
        if (serviceType.equalsIgnoreCase("plan_approve")) {
            //状态：1-待审核；2-审核中；3-通过；4-驳回；
            if (status == PostProgrammeEnum.STATUS_PASS.getValue()) {
                return AjaxResult.error("已审核通过无需通知审核人或制单人，请检查！");
            }

            List<Long> userIdALlList = new ArrayList<>();
            Integer statusIcfa = postPlanDB.getStatusIcfa();
            Integer statusHr = postPlanDB.getStatusHr();
            //给内控法务发邮件
            if (statusIcfa == null || statusIcfa != PostPlanEnum.STATUS_ICFA_PASS.getValue()) {
                List<Long> userIdList = sysPostService.userHaveAuthorityList(DeptCode.DEPT_HR.getCode());
                userIdALlList.addAll(userIdList);
            }
            //给人力资源发邮件
            if (statusHr == null || statusHr != PostPlanEnum.STATUS_HR_PASS.getValue()) {
                List<Long> userIdList = sysPostService.userHaveAuthorityList(DeptCode.DEPT_ICFA.getCode());
                userIdALlList.addAll(userIdList);
            }

            //根据用户ID查邮箱
            List<SysUser> sysUserList = sysUserService.postUserList(null, null, null, null, null, userIdALlList, null);
            for (SysUser sysUser : sysUserList) {
                String email = sysUser.getEmail();
                userMailSet.add(email);
            }

            String href = webStartPage + "/postInspectionPlanning/planManagement/jobPlanAudit";
            content = "尊敬的岗检计划审核人大家好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + name + "-" + "岗检计划待审核，请登录系统处理。！请点击链接，直达审核页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        }
        //给制单人发邮件：审核驳回（内控法务、人力资源）
        else if (serviceType.equalsIgnoreCase("plan_create_user")) {

            //状态：1-待审核；2-审核中；3-通过；4-驳回；
            if (status == PostProgrammeEnum.STATUS_PASS.getValue()) {
                return AjaxResult.error("已审核通过无需通知审核人或制单人，请检查！");
            }

            Long createUserId = postPlanDB.getCreateUserId();
            userMailSet = selectUserEmail(createUserId);//查邮箱

            String href = webStartPage + "/postInspectionPlanning/planManagement/jobPlan";
            content = "尊敬的岗检计划编写人，您好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + name + "-" + "岗检计划状态发生变更，请登录系统查看。！请点击链接，直达编辑页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        }
        //给检查人员发邮件：岗检计划发布，将计划和多张检查表生成N个Excel以附件形式发送给检查人员。
        else if (serviceType.equalsIgnoreCase("plan_checked_user")) {
            String downloadPath = ruoYiConfig.getDownloadPath();

            //当前计划涉及的岗位检查表
            List<PostPlan.PostInfoSendMail> postInfoSendMailList = new ArrayList<>();

            //岗检计划：导出的数据
            List<PostPlanExcelBean> list = new ArrayList<>();

            //数据库查询数据：主单据 + 明细（行单位是明细中的受检部门）
            PostPlan postPlan = new PostPlan();
            postPlan.setId(serviceId);
            List<PostPlan> planList = postPlanService.selectPostPlanListV2(postPlan);
            if (CollectionUtils.isEmpty(planList)) {
                return AjaxResult.error("岗检计划ID错误，请刷新页面再试！");
            }


//            for (int i = 0; i < planList.size(); i++) {
            PostPlan dataDB = planList.get(0);
            postInfoSendMailList.addAll(dataDB.getPostInfoSendMailList());
//            String name = dataDB.getName();//计划名称
//            String content = dataDB.getContent();//计划内容
//            String checkGroupName = dataDB.getCheckGroupName();//工作组
//            String checkTeamName = dataDB.getCheckTeamName();//检查小组
//            String checkedUserNames = dataDB.getCheckedUserNames();//检查人员拼接
//            String checkedDeptName = dataDB.getCheckedDeptName();//部门名称
//            String checkedPostNames = dataDB.getCheckedPostNames();//岗位拼接
//            String checkedTimeView = dataDB.getCheckedTimeView();//检查时间

//            PostPlanExcelBean data = new PostPlanExcelBean();
//            BeanUtils.copyBeanProp(data, dataDB);
//            list.add(data);
            for (PostPlan planDB : planList) {
                PostPlanExcelBean data = new PostPlanExcelBean();
                BeanUtils.copyBeanProp(data, planDB);
                list.add(data);
            }

            List<PostPlanCheckUser> checkUserChildren = dataDB.getCheckUserChildren();
            for (PostPlanCheckUser checkUserChild : checkUserChildren) {
//                String email = checkUserChild.getEmail();
                Long checkedUserId = checkUserChild.getCheckedUserId();
                SysUser sysUser = sysUserService.selectUserById(checkedUserId);
                String email = sysUser == null ? null : sysUser.getEmail();
                if (StringUtils.isBlank(email)) {
                    return AjaxResult.error((sysUser == null ? String.valueOf(checkedUserId) : sysUser.getNickName()) + "检查人员的邮箱为空，请检查！");
                }

                userMailSet.add(email);
            }
//            }


            if (userMailSet.isEmpty()) {
                return AjaxResult.error("未查到检查人员，请检查！");
            }

            //岗检计划：合并单元格
            List<MergedRegionUtils> mergedRegionList = new ArrayList<>();
            MergedRegionUtils mergedRegionUtilsOne = new MergedRegionUtils(2, 2 + planList.size() - 1, 0, 0);
            MergedRegionUtils mergedRegionUtilsTow = new MergedRegionUtils(2, 2 + planList.size() - 1, 1, 1);
            MergedRegionUtils mergedRegionUtilsThree = new MergedRegionUtils(2, 2 + planList.size() - 1, 2, 2);
            MergedRegionUtils mergedRegionUtilsFour = new MergedRegionUtils(2, 2 + planList.size() - 1, 3, 3);
            MergedRegionUtils mergedRegionUtilsFive = new MergedRegionUtils(2, 2 + planList.size() - 1, 4, 4);
            mergedRegionList.add(mergedRegionUtilsOne);
            mergedRegionList.add(mergedRegionUtilsTow);
            mergedRegionList.add(mergedRegionUtilsThree);
            mergedRegionList.add(mergedRegionUtilsFour);
            mergedRegionList.add(mergedRegionUtilsFive);


            //岗检计划：生成Excel
            ExcelUtil<PostPlanExcelBean> util = new ExcelUtil<>(PostPlanExcelBean.class);
            String sheetName = "岗检计划";
            String title = "岗位责任制检查表";

//        ajaxResult = {msg=3897c0b0-baa8-4c37-80f4-79381a1bf4a2_岗检计划.xlsx, code=200}
            AjaxResult ajaxResult = util.exportExcel(list, sheetName, title, mergedRegionList);

            String postPlanFileName = ajaxResult.get("msg").toString();
//            System.out.println("岗检计划Excel文件 = " + downloadPath + postPlanFileName);

            filePathArray.add(downloadPath + postPlanFileName);


            //遍历生成岗检表
            if (CollectionUtils.isEmpty(postInfoSendMailList)) {
                return AjaxResult.error("计划涉及岗位匹配失败！");
            }
            for (PostPlan.PostInfoSendMail postInfoSendMail : postInfoSendMailList) {
                Long deptId = postInfoSendMail.getDeptId();
                String deptName = postInfoSendMail.getDeptName();
                String postName = postInfoSendMail.getPostName();
                Long postid = postInfoSendMail.getPostid();

                PostChecked postCheckedParam = new PostChecked();
                postCheckedParam.setStatus(PostCheckedEnum.STATUS_PASS.getValue());
                postCheckedParam.setCheckedDeptId(deptId);
                postCheckedParam.setCheckedPostId(postid);
                List<PostChecked> postCheckedList = postCheckedService.selectPostCheckedList(postCheckedParam);

                if (CollectionUtils.isEmpty(postCheckedList)) {
                    return AjaxResult.error("岗位检查表不存在【" + deptName + "-" + postName + "】！");
                }

                //按审核时间倒序排列
                Collections.sort(postCheckedList, new Comparator<PostChecked>() {
                    @Override
                    public int compare(PostChecked o1, PostChecked o2) {
                        long currentTimeMillis = System.currentTimeMillis();
                        Date statusApproveTime1 = o1.getStatusApproveTime() != null ? o1.getStatusApproveTime() : new Date(currentTimeMillis);
                        Date statusApproveTime2 = o2.getStatusApproveTime() != null ? o2.getStatusApproveTime() : new Date(currentTimeMillis);
                        return (int) (statusApproveTime2.getTime() - statusApproveTime1.getTime());
                    }
                });

                //取审核时间最大的一个岗检表
                PostChecked postChecked = postCheckedList.get(0);
//            PostChecked postChecked = postCheckedService.selectPostCheckedById(id);
                PostCheckedCreateExcel postCheckedCreateExcel = new PostCheckedCreateExcel();
                String postCheckedFileName = postCheckedCreateExcel.createExcel(postChecked, postChecked.getChildren());
                System.out.println("岗检表Excel文件（" + deptName + "-" + postName + "） = " + downloadPath + postCheckedFileName);

                filePathArray.add(downloadPath + postCheckedFileName);
            }

            content = "尊敬的岗检检查人员大家好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;岗检计划已审核完成，岗检计划表和岗位检查表已发到您的邮箱，详见附件中的表格！";

        } else {
            return AjaxResult.error("业务类型错误【serviceType = " + serviceType + "】，请检查！");
        }


        boolean flag = false;
        try {
            //附件
            String[] filePaths = null;
            int fileSize = filePathArray.size();
            if (fileSize > 0) {
                filePaths = new String[fileSize];
                for (int i = 0; i < filePathArray.size(); i++) {
                    filePaths[i] = filePathArray.get(i).toString();
                }
            }
            String address = "";
            for (String email : userMailSet) {
                address += email + ";";
            }
            flag = sendMailUtils.sendFile(content, address, filePaths);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage(), filePathArray);
        }
        if (flag)
            return AjaxResult.success("成功", filePathArray);
        else
            return AjaxResult.error("未知错误！", filePathArray);
    }

    /**
     * 邮件通知-岗检表
     *
     * @param serviceType 业务类型
     * @param serviceId   业务表单ID
     * @return
     */
    @Override
    public AjaxResult postCheckedSendMail(String serviceType, Long serviceId) {

        String webStartPage = casConfig.getWebStartPage();
        webStartPage = webStartPage.substring(0, webStartPage.lastIndexOf("/"));

        //TODO lyp邮件推送：岗位责任制清单
        String content = null;

        //收件人邮箱
        Set<String> userMailSet = new HashSet<>();


        PostChecked postChecked = postCheckedService.selectPostCheckedById(serviceId);
        Integer status = postChecked.getStatus();
        String deptName = postChecked.getCheckedDeptName();
        String postName = postChecked.getCheckedPostName();

        //状态：1-待审核；2-审核中；3-通过；4-驳回；
        if (status == PostProgrammeEnum.STATUS_PASS.getValue()) {
            return AjaxResult.error("已审核通过无需通知审核人或制单人，请检查！");
        }

        //给审核人发邮件：给未审核通过的部门发送邮件-人力资源部、党建工作部、健康安全环保中心、内控法务部&办公室
        if (serviceType.equalsIgnoreCase("checked_approve")) {
            List<Long> userIdALlList = new ArrayList<>();
            //给管理员发邮件
            if (status == null || status != PostCheckedEnum.STATUS_PASS.getValue()) {
                List<Long> adminUserList = SecurityUtils.getAdminUserList();
                userIdALlList.addAll(adminUserList);
            }
            //根据用户ID查邮箱
            List<SysUser> sysUserList = sysUserService.postUserList(null, null, null, null, null, userIdALlList, null);
            for (SysUser sysUser : sysUserList) {
                String email = sysUser.getEmail();
                userMailSet.add(email);
            }

            String href = webStartPage + "/postInspectionPlanning/tableManagement/tableManagementAudit";
            content = "尊敬的岗检方案审核人大家好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + deptName + "-" + postName + "岗检表待审核，请登录系统处理。！请点击链接，直达审核页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        }
        //给制单人发邮件：岗位责任制清单驳回
        else if (serviceType.equalsIgnoreCase("checked_create_user")) {
            Long createUserId = postChecked.getCreateUserId();
            userMailSet = selectUserEmail(createUserId);//查邮箱

            String href = webStartPage + "/postInspectionPlanning/tableManagement/addTableManagement";
            content = "尊敬的岗检表编写人，您好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + deptName + "-" + postName + "-" + "岗检表状态发生变更，请登录系统查看。！请点击链接，直达编辑页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        } else {
            return AjaxResult.error("业务类型错误【serviceType = " + serviceType + "】，请检查！");
        }

        boolean flag = false;
        try {
            String address = "";

            for (String email : userMailSet) {
                address += email + ";";
            }
            flag = sendMailUtils.sendFile(content, address, null);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        if (flag)
            return AjaxResult.success("成功");
        else
            return AjaxResult.error("未知错误！");
    }

    /**
     * 邮件通知-问题
     *
     * @param serviceType 业务类型
     * @param serviceId   业务表单ID
     * @return
     */
    @Override
    public AjaxResult postProblemSendMail(String serviceType, Long serviceId) {
//        整改	/postImplementation/rectificationProblem/remediationAction
//        审核	/postImplementation/rectificationProblem/rectificationAudit
//        验证	/postImplementation/rectificationProblem/rectificationVerification

        String webStartPage = casConfig.getWebStartPage();
        webStartPage = webStartPage.substring(0, webStartPage.lastIndexOf("/"));

        //TODO lyp邮件推送：问题
        String content = null;

        //收件人邮箱
        Set<String> userMailSet = new HashSet<>();


        PostCheckedProblem postCheckedProblem = postCheckedProblemService.selectPostCheckedProblemById(serviceId);
        Integer status = postCheckedProblem.getStatus();
        String problemNo = postCheckedProblem.getProblemNo();
        Long checkedDeptId = postCheckedProblem.getCheckedDeptId();
        Long deptApproveUserId = postCheckedProblem.getDeptApproveUserId();//部门经理
        Long specialityDepartmentReviewerId = postCheckedProblem.getSpecialityDepartmentReviewerId();//复查人
        Long reviewDepartmentReviewerId = postCheckedProblem.getReviewDepartmentReviewerId();//复查人
//        String deptName = postCheckedProblem.getCheckedDeptName();
//        String postName = postCheckedProblem.getCheckedPostName();


        //1-待指定整改人（问题录入完成时）；2-待填写方案（部门管理员指定整改人后）；
        //10-待部门审核；11-部门审核通过；12-部门审核驳回；
        //20-待专业部门人审核（非必填）；21-专业部门人审核通过（非必填）；22-专业部门人审核驳回（非必填）；
        //30-待整改责任人上传实施（整改责任人上传实施图片）；31-整改责任人上传实施照片完成；
        //40-待复查部门人审核；41-复查部门人审核通过；42-复查部门人审核驳回
        if (status == PostCheckedProblemEnum.FU_CHA_PASS.getValue()) {
            return AjaxResult.error("已复查通过无需通知，请检查！");
        }


        //给管理员发邮件：指定整改负责人
        if (serviceType.equalsIgnoreCase("problem_admin")) {
            //给管理员发邮件
            List<Long> userIdALlList = SecurityUtils.getAdminUserList();
            //根据用户ID查邮箱
            List<SysUser> sysUserList = sysUserService.postUserList(null, null, null, null, null, userIdALlList, null);
            for (SysUser sysUser : sysUserList) {
                String email = sysUser.getEmail();
                userMailSet.add(email);
            }

            String href = webStartPage + "/postImplementation/rectificationProblem/remediationAction";
            content = "尊敬的管理员，大家好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + problemNo + "岗检问题还未指定整改责任人，请登录系统处理。！请点击链接，直达审核页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        }
        //给整改责任人发邮件
        else if (serviceType.equalsIgnoreCase("problem_rectification_responsible_user")) {
            Long rectificationResponsibleUserId = postCheckedProblem.getRectificationResponsibleUserId();
            userMailSet = selectUserEmail(rectificationResponsibleUserId);//查邮箱

            String href = webStartPage + "/postImplementation/rectificationProblem/remediationAction";
            content = "尊敬的岗检问题整改责任人，您好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + problemNo + "-" + "岗检问题状态发生变更，请登录系统查看。！请点击链接，直达编辑页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        }

        //给部门经理发邮件（4个人）：部门审核
        else if (serviceType.equalsIgnoreCase("problem_dept_approve_user")) {
            if (status >= PostCheckedProblemEnum.DEPT_PASS.getValue() && status != PostCheckedProblemEnum.DEPT_BACK.getValue()) {
                return AjaxResult.error("部门审核通过无需通知，请检查！");
            }
            //查询部门编码
            SysDept sysDept = sysDeptService.selectDeptById(checkedDeptId);
            //查看部门下经理
            List<Long> userIdALlList = sysPostService.userHaveAuthorityList(sysDept.getDeptCode());
            //根据用户ID查邮箱
            List<SysUser> sysUserList = sysUserService.postUserList(null, null, null, null, null, userIdALlList, null);
            for (SysUser sysUser : sysUserList) {
                String email = sysUser.getEmail();
                userMailSet.add(email);
            }

            String href = webStartPage + "/postImplementation/rectificationProblem/rectificationAudit";
            content = "尊敬的岗检问题审核人，您好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + problemNo + "-" + "岗检问题状态发生变更，请登录系统查看。！请点击链接，直达编辑页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        }
        //给专业部门审核人发邮件（1个人）：专业部门审核
        else if (serviceType.equalsIgnoreCase("problem_speciality_department_reviewer")) {
            if (status >= PostCheckedProblemEnum.ZHUAN_ZY_PASS.getValue() && status != PostCheckedProblemEnum.ZHUAN_ZY_BACK.getValue()) {
                return AjaxResult.error("专业部门审核审核通过无需通知，请检查！");
            }
            if (specialityDepartmentReviewerId == null) {
                return AjaxResult.error("专业部门审核人为选填项目，当前问题未指定专业部门审核人无需通知，请检查！");
            }

            userMailSet = selectUserEmail(specialityDepartmentReviewerId);//查邮箱

            String href = webStartPage + "/postImplementation/rectificationProblem/rectificationAudit";
            content = "尊敬的岗检问题审核人，您好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + problemNo + "-" + "岗检问题状态发生变更，请登录系统查看。！请点击链接，直达编辑页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        }
        //给复查部门的复查人发邮件（1个人））：整改实施结果和图片上传完成
        else if (serviceType.equalsIgnoreCase("problem_review_department_reviewer")) {
            if (status <= PostCheckedProblemEnum.EDIT_WAIT_TWO.getValue()) {
                return AjaxResult.error("问题整改负责人未填写整改实施信息，请检查！");
            }
            if (reviewDepartmentReviewerId == null) {
                return AjaxResult.error("当前问题未指定复查部门审核人，请问题整改负责人登录系统后指定，请检查！");
            }

            userMailSet = selectUserEmail(reviewDepartmentReviewerId);//查邮箱

            String href = webStartPage + "/postImplementation/rectificationProblem/rectificationVerification";
            content = "尊敬的岗检问题审核人，您好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + problemNo + "-" + "岗检问题状态发生变更，请登录系统查看。！请点击链接，直达编辑页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        } else {
            return AjaxResult.error("业务类型错误【serviceType = " + serviceType + "】，请检查！");
        }

        boolean flag = false;
        try {
            String address = "";

            for (String email : userMailSet) {
                address += email + ";";
            }
            flag = sendMailUtils.sendFile(content, address, null);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        if (flag)
            return AjaxResult.success("成功");
        else
            return AjaxResult.error("未知错误！");
    }


    /**
     * 邮件通知-能部门互评
     * 邮件通知-生产部门日常评分
     *
     * @param serviceType 业务类型
     * @param serviceId   业务表单ID
     * @return
     */
    @Override
    public AjaxResult postAssessmentRatingOtherSendMail(String serviceType, Long serviceId) {
        String webStartPage = casConfig.getWebStartPage();
        webStartPage = webStartPage.substring(0, webStartPage.lastIndexOf("/"));
        String year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());

        //TODO lyp邮件推送：职能部门互评 / 生产部门日常评分
        String content = null;

        //收件人邮箱
        Set<String> userMailSet = new HashSet<>();

        Integer deptType = null;//系统管理的部门类型：1 职能部门 2 生产部门 3 其他
        String deptTypeView = "";//提示语
        Integer type = null;//打分任务表 类型：1-职能互评；2-生产日常；

        //给涉及的13个职能部门分别发邮件
        if (serviceType.equalsIgnoreCase("assessment_rating_other_10")) {
            deptType = SysDeptEnum.TYPE_ZN.getValue();
            deptTypeView = "职能部门";
            type = PostAssessmentRatingOtherEnum.TYPE_ZN_HP.getValue();

            String href = webStartPage + "/examineCompetition/assessment";
            content = "尊敬的部门经理，大家好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + year + "年度职能部门互评已经开始，请登录系统处理。！请点击链接，直达审核页面：" + "<a href=\"" + href + "\">" + href + "</a>";

        }
        //给涉及的13个生产部门分别发邮件
        else if (serviceType.equalsIgnoreCase("assessment_rating_other_20")) {
            deptType = SysDeptEnum.TYPE_SC.getValue();
            deptTypeView = "生产部门";
            type = PostAssessmentRatingOtherEnum.TYPE_SC_RC.getValue();

            String href = webStartPage + "/examineCompetition/produce";
            content = "尊敬的部门经理，大家好：<br> " +
                    "&nbsp;&nbsp;&nbsp;&nbsp;" + year + "年度生产部门日常评分已经开始，请登录系统处理。！请点击链接，直达审核页面：" + "<a href=\"" + href + "\">" + href + "</a>";
        } else {
            return AjaxResult.error("业务类型错误【serviceType = " + serviceType + "】，请检查！");
        }


        //检查评分记录是否已经存在
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostAssessmentRatingOther postAssessmentRatingOtherParam = new PostAssessmentRatingOther();
        postAssessmentRatingOtherParam.setType(type);//职能部门 OR 生产运行部门
        postAssessmentRatingOtherParam.setParams(params);//当前年度打分任务
        List<PostAssessmentRatingOther> postAssessmentRatingOtherList = postAssessmentRatingOtherMapper.selectPostAssessmentRatingOtherList(postAssessmentRatingOtherParam);
        if (CollectionUtils.isEmpty(postAssessmentRatingOtherList)) {
            return AjaxResult.error(year + "年度" + deptTypeView + "还没有创建打分任务，请检查！");
        }

        //过滤还未提交打分的部门
        List<PostAssessmentRatingOther> assessmentRatingOtherIngList = postAssessmentRatingOtherList.stream().filter(a -> a.getStatus() == PostAssessmentRatingOtherEnum.STATUS_ING.getValue()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(assessmentRatingOtherIngList)) {
            return AjaxResult.error(year + "年度" + deptTypeView + "打分任务已全部完成，无需邮件通知，本次未发送邮件通知！");
        }
        //还未提交打分的部门ID
        List<Long> assessmentRatingOtherIngDeptIdList = assessmentRatingOtherIngList.stream().map(a -> a.getDeptId()).collect(Collectors.toList());

        //系统中全部的职能部门 OR 生产运行部门
        SysDept deptParam = new SysDept();
        deptParam.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());//部门状态（0正常 1停用）
        deptParam.setType(deptType);//1 职能部门 2 生产部门 3 其他
        List<SysDept> deptList = sysDeptService.selectDeptListByCondition(deptParam);
        if (CollectionUtils.isEmpty(deptList)) {
            throw new BaseException(deptTypeView + "系统管理->部门管理中未设置部门类型，请检查！");
        }


        //收集收件人邮箱
        String errorMsg = "";
        List<Long> userIdALlList = new ArrayList<>();
        for (SysDept sysDept : deptList) {
            Long deptId = sysDept.getDeptId();
            String deptCode = sysDept.getDeptCode();
            String deptName = sysDept.getDeptName();
            if (assessmentRatingOtherIngDeptIdList.contains(deptId)) {
                List<Long> userIdList = sysPostService.userHaveAuthorityList(deptCode);
                //该部门下无经理岗位，提示页面无法执行发邮件任务
                if (CollectionUtils.isEmpty(userIdList)) {
                    errorMsg += "【" + deptName + "】";
                    continue;
                }
                userIdALlList.addAll(userIdList);
            }
        }
        if (StringUtils.isNotBlank(errorMsg)) {
            return AjaxResult.error("如下部门中未设置经理岗位，请检查！" + errorMsg);
        }
        userMailSet = selectUserEmail(userIdALlList);

        boolean flag = false;
        try {
            String address = "";
            for (String email : userMailSet) {
                address += email + ";";
            }
            flag = sendMailUtils.sendFile(content, address, null);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        if (flag)
            return AjaxResult.success("成功");
        else
            return AjaxResult.error("未知错误！");
    }

    /**
     * 根据用户ID查邮箱
     *
     * @param userId
     * @return
     */
    private Set<String> selectUserEmail(Long userId) {

        List<Long> userIdALlList = new ArrayList<>();
        userIdALlList.add(userId);
        Set<String> emailSet = selectUserEmail(userIdALlList);

//        Set<String> emailSet = new HashSet<>();
//        List<SysUser> sysUserList = sysUserService.postUserList(null, null, null, null, null, userIdALlList, null);
//        for (SysUser sysUser : sysUserList) {
//            String email = sysUser.getEmail();
//            emailSet.add(email);
//        }
        return emailSet;
    }

    /**
     * 根据用户ID查邮箱
     *
     * @param userIdList 用户ID
     * @return
     */
    private Set<String> selectUserEmail(List<Long> userIdList) {
        String errorMsg = "";
        Set<String> emailSet = new HashSet<>();
        List<SysUser> sysUserList = sysUserService.postUserList(null, null, null, null, null, userIdList, null);
        for (SysUser sysUser : sysUserList) {
            String deptName = sysUser.getDeptName();
            String nickName = sysUser.getNickName();
            String email = sysUser.getEmail();
            if (StringUtils.isBlank(email)) {
                errorMsg += "【" + deptName + "-" + nickName + "】";
                continue;
            }
            emailSet.add(email);
        }

        if (StringUtils.isNotBlank(errorMsg)) {
            throw new BaseException("以下人员邮箱为空，请检查！");
        }

        return emailSet;
    }

    /**
     * 根据岗检责任制清单审核类型查对应岗位经理邮箱
     *
     * @param typeSet
     * @return
     */
    private Set<String> selectUserEmailPostList(HashSet<Integer> typeSet) {
        List<Long> userIdALlList = new ArrayList<>();
        Set<String> emailSet = new HashSet<>();
        for (Integer type : typeSet) {
            //TYPE_ONE("业务职责（人力资源部）", 1),
            if (type == PostListEnum.TYPE_ONE.getValue()) {
                List<Long> userIdList = sysPostService.userHaveAuthorityList(DeptCode.DEPT_HR.getCode());
                userIdALlList.addAll(userIdList);
            }
            //TYPE_TWO("党建及党风廉政建设职责（党建工作部）", 2),
            else if (type == PostListEnum.TYPE_TWO.getValue()) {
                List<Long> userIdList = sysPostService.userHaveAuthorityList(DeptCode.DEPT_PARTY.getCode());
                userIdALlList.addAll(userIdList);
            }
            //TYPE_THREE("安全环保职责（健康安全环保中心）", 3),
            else if (type == PostListEnum.TYPE_THREE.getValue()) {
                List<Long> userIdList = sysPostService.userHaveAuthorityList(DeptCode.DEPT_HSE.getCode());
                userIdALlList.addAll(userIdList);
            }
            //TYPE_FOUR("合规保密职责（内控法务部&办公室）", 4),
            else if (type == PostListEnum.TYPE_FOUR.getValue()) {
                List<Long> userHaveAuthorityList = sysPostService.userHaveAuthorityList(DeptCode.DEPT_ICFA.getCode());
                List<Long> userHaveAuthorityListV2 = sysPostService.userHaveAuthorityList(DeptCode.DEPT_OFFICE.getCode());
                userHaveAuthorityList.addAll(userHaveAuthorityListV2);
                List<Long> userIdList = userHaveAuthorityList;
                userIdALlList.addAll(userIdList);
            }
        }
        //根据用户ID查邮箱
        List<SysUser> sysUserList = sysUserService.postUserList(null, null, null, null, null, userIdALlList, null);
        for (SysUser sysUser : sysUserList) {
            String email = sysUser.getEmail();
            emailSet.add(email);
        }
        return emailSet;
    }
}
