package com.bonus.system.download;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.bonus.common.core.constant.BusinessConstants;
import com.bonus.common.core.enums.AttStatus;
import com.bonus.common.core.utils.DateTimeHelper;
import com.bonus.common.core.utils.ExcelStyleUtil;
import com.bonus.common.core.utils.StringHelper;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.poi.MultiSheetExcelExporter;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.domain.MapVo;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.att.entity.*;
import com.bonus.system.att.service.AttDetailByMonthService;
import com.bonus.system.att.service.AttendanceDetailsService;
import com.bonus.system.att.service.OrgChangeService;
import com.bonus.system.basic.dao.SysOrgDao;
import com.bonus.system.basic.domain.SysOrg;
import com.bonus.system.basic.domain.SysOrgExport;
import com.bonus.system.basic.service.SysOrgService;
import com.bonus.system.dept.dao.ProDeptRoleDao;
import com.bonus.system.dept.entity.EightMembersVacancyVo;
import com.bonus.system.dept.entity.SubOrgBean;
import com.bonus.system.dept.service.EightMembersVacancyService;
import com.bonus.system.dept.service.SubOrgService;
import com.bonus.system.evection.entity.EvectionBean;
import com.bonus.system.evection.service.EvectionService;
import com.bonus.system.holiday.entity.HolidayBean;
import com.bonus.system.holiday.service.HolidayService;
import com.bonus.system.leaveReporting.entity.LeaveReportingBean;
import com.bonus.system.leaveReporting.service.LeaveReportingService;
import com.bonus.system.wechat.entity.WechatBean;
import com.bonus.system.wechat.entity.WechatEvectionBean;
import com.bonus.system.wechat.entity.WechatLeaveReportingBean;
import com.bonus.system.wechat.service.WechatEvectionService;
import com.bonus.system.wechat.service.WechatLeaveReportingService;
import com.bonus.system.wechat.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

import static com.bonus.common.core.text.Convert.str;


/**
 * @author：fly
 * @date：2024-10-14-10:30
 * @version：1.0
 * @description：导出文件-web层
 */
@RestController
@RequestMapping("/export")
@Slf4j
public class ExportFileController {


    /**
     * 分公司项目部服务类
     */
    @Resource(name = "SubOrgService")
    private SubOrgService subOrgService;

    /**
     * 轮休、请假、临时外出导出
     */
    @Resource(name = "HolidayService")
    private HolidayService holidayService;


    /**
     * 休假报备
     */
    @Resource(name = "LeaveReportingService")
    private LeaveReportingService leaveReportingService;

    /**
     * 数据管理-休假报备
     */
    @Resource(name = "WechatLeaveReportingService")
    private WechatLeaveReportingService wechatLeaveReportingService;

    /**
     * 出差报备
     */
    @Resource(name = "EvectionService")
    private EvectionService evectionService;

    /**
     * 数据管理-出差报备
     */
    @Resource(name = "WechatEvectionService")
    private WechatEvectionService wechatevectionService;


    /**
     * 考勤明细导出
     */
    @Resource(name = "attendanceDetailsService")
    private AttendanceDetailsService attendanceDetailsService;

    @Resource(name = "sysOrgService")
    private SysOrgService sysOrgService;

    @Resource(name = "OrgChangeService")
    private OrgChangeService orgChangeService;

    @Resource(name = "WechatService")
    private WechatService wechatService;

    @Resource(name = "attDetailByMonthService")
    private AttDetailByMonthService attDetailByMonthService;

    @Resource(name = "ProDeptRoleDao")
    private ProDeptRoleDao proDeptRoleDao;

    @Resource
    private SysOrgDao sysOrgDao;

    @Resource(name = "EightMembersVacancyService")
    private EightMembersVacancyService eightMembersVacancyService;


    /**
     * 分公司项目部导出
     *
     * @param response
     * @param bean
     * @return void
     * @author：fly
     * @date：2024-10-14-10:30
     */
    @RequiresPermissions("dept:org:export")
    @GetMapping("/exportSubOrg")
    public void exportSubOrg(HttpServletResponse response, SubOrgBean bean) {
        try {
            List<SubOrgBean> personExportVoList = new ArrayList<>();
            List<SubOrgBean> personLists = subOrgService.selectSubOrgList(bean);
            for (int i = 0; i < personLists.size(); i++) {
                SubOrgBean vo = personLists.get(i);
                vo.setId((i + 1));
                vo.setReviewerStatus(BusinessConstants.WAIT_CHECK.equals(vo.getReviewerStatus()) ? "待审核" : BusinessConstants.PASS_CHECK.equals(vo.getReviewerStatus()) ? "已通过" : BusinessConstants.NOT_PASS_CHECK.equals(vo.getReviewerStatus()) ? "未通过" : "撤回");
                // 创建一个 SimpleDateFormat 对象，用于格式化日期
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 将 Date 转换为 String
                String dateString = formatter.format(vo.getCreateTime());
                vo.setApplyTime(dateString);
                personExportVoList.add(vo);
            }
            extracted(personExportVoList, SubOrgBean.class, "分公司项目部导出", "分公司项目部导出", "分公司项目部导出", response);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    /**
     * 轮休、请假、临时外出导出
     *
     * @param response
     * @param bean
     * @return void
     * @author：fly
     * @date：2024-10-14-10:30
     */
    @GetMapping("/exportHoliday")
    public void exportHoliday(HttpServletResponse response, HolidayBean bean) {
        try {
            List<HolidayBean> personExportVoList = new ArrayList<>();
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    if (Collections.frequency(roleId, "15") == 0) {
                        List<MapVo> orgList = sysUser.getOrgList();
                        if (!orgList.isEmpty()) {
                            ArrayList<String> ids = new ArrayList<>();
                            for (MapVo mapVo : orgList) {
                                String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                                // 使用 Arrays.asList() 将数组转换为 ArrayList
                                ArrayList<String> idList = new ArrayList<>(Arrays.asList(id.split(",")));
                                ids.addAll(idList);
//                        ids.add(String.valueOf(mapVo.getId()));
                            }
                            bean.setOrgList(ids);
                        }
                    } else {
                        Long userId = SecurityUtils.getUserId();
                        bean.setUserId(userId);
                    }
                }
            }
            List<HolidayBean> personLists = holidayService.getHolidayList(bean);
            for (int i = 0; i < personLists.size(); i++) {
                HolidayBean vo = personLists.get(i);
                vo.setId((i + 1));
                vo.setExamineStatus(BusinessConstants.WAIT_CHECK.equals(vo.getExamineStatus()) ? "待审核" : BusinessConstants.PASS_CHECK.equals(vo.getExamineStatus()) ? "已通过" : BusinessConstants.NOT_PASS_CHECK.equals(vo.getExamineStatus()) ? "未通过" : "撤回");
                //事件处理
                if ("1".equals(vo.getLeaveStartInterval())) {
                    vo.setLeaveStartInterval(vo.getLeaveStartDate() + " 上午");
                } else {
                    vo.setLeaveStartInterval(vo.getLeaveStartDate() + " 下午");
                }
                if ("1".equals(vo.getLeaveEndInterval())) {
                    vo.setLeaveEndInterval(vo.getLeaveEndDate() + " 上午");
                } else {
                    vo.setLeaveEndInterval(vo.getLeaveEndDate() + " 下午");
                }
                // 创建一个 SimpleDateFormat 对象，用于格式化日期
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 将 Date 转换为 String
                String dateString = formatter.format(vo.getCreateTime());
                vo.setLeaveDate(dateString);
                personExportVoList.add(vo);
            }
            extracted(personExportVoList, HolidayBean.class, "轮休临时外出导出", "轮休临时外出导出", "轮休临时外出导出", response);
        } catch (
                Exception e) {
            log.error(e.toString(), e);
        }

    }

    /**
     * 考勤明细导出/原始数据导出
     *
     * @param response
     * @param bean
     * @return void
     * @author：fly
     * @date：2024-10-14-10:30
     */
    @GetMapping("/exportAttRecord")
    public void att(HttpServletResponse response, AttDataDetailsBean bean) {
        try {
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    // 根据用户id查询是否是管理员或帮忙负责人
                    Long userId = SecurityUtils.getUserId();
                    List<MapVo> orgList = sysOrgDao.getOrgIdList(userId);
                    if (!orgList.isEmpty()) {
                        // 使用 LinkedHashSet 来保证顺序并自动去重
                        Set<String> idsSet = new LinkedHashSet<>();
                        for (MapVo mapVo : orgList) {
                            String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                            if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                // 将分割后的数组添加到 Set 中，自动去重
                                Collections.addAll(idsSet, id.split(","));
                            }
                        }
                        // 如果需要转换回 List 类型
                        List<String> uniqueIds = new ArrayList<>(idsSet);
                        bean.setOrgList(uniqueIds);
                    }else{
                        bean.setUserId(userId);
                    }
                }
            }

            List<AttDataDetailsBean> attList;
            if ("考勤明细".equals(bean.getExportType())) {
                attList = attendanceDetailsService.exportAttDetailsList(bean);
            } else {
                attList = attendanceDetailsService.exportAttOriginalsList(bean);
            }
            //将数据转换成为汉字
            for (AttDataDetailsBean att : attList) {
                String toStatus = att.getToWorkAttStatus();
                String offStatus = att.getOffWorkAttStatus();
                AttStatus attStatus1 = AttStatus.getByCode(toStatus); // 根据状态码获取对应的枚举
                AttStatus attStatus2 = AttStatus.getByCode(offStatus); // 根据状态码获取对应的枚举
                if (attStatus1 != null) {
                    att.setToWorkAttStatus(attStatus1.toString()); // 将考勤状态转换为中文字符或符号
                }
                if (attStatus2 != null) {
                    att.setOffWorkAttStatus(attStatus2.toString()); // 将考勤状态转换为中文字符或符号
                }
            }
            // 将数据按 userId 分组存储到多个列表
            Map<Long, List<AttDataDetailsBean>> userGroups = new HashMap<>();
            for (AttDataDetailsBean user : attList) {
                userGroups.computeIfAbsent(user.getUserId(), k -> new ArrayList<>()).add(user);
            }
            List<String> days = getDays(bean.getStartDate(), bean.getEndDate());
            // 最终的 list 用于保存所有用户的数据
            List<AttDataDetailsBean> listData = new ArrayList<>();
            // 遍历每个 userId 对应的 List，提取第一条数据并组合成新的 AttDataDetailsBean
            for (Map.Entry<Long, List<AttDataDetailsBean>> entry : userGroups.entrySet()) {
                Long userId = entry.getKey();
                List<AttDataDetailsBean> userList = entry.getValue();
                // 提取第一条数据的 orgName 和 userName
                String orgName = userList.get(0).getOrgName();
                String userName = userList.get(0).getUserName();
                // 提取所有的 attCurrentDay 和 ToWorkAttStatus，放入 List<AttDayBean>
                List<AttDayBean> listAttDay = userList.stream()
                        .map(user -> {
                            AttDayBean attDayBean = new AttDayBean();
                            attDayBean.setCurrentDay(user.getAttCurrentDay());
                            if (!user.getToWorkAttStatus().equals(user.getOffWorkAttStatus())) {
                                attDayBean.setAttType(user.getToWorkAttStatus() + "|" + user.getOffWorkAttStatus());
                            } else {
                                attDayBean.setAttType(user.getToWorkAttStatus());
                            }
//                            if(user.getOrgName().contains(",")){
//                                attDayBean.setColor("red");
//                            }
                            return attDayBean;
                        }).collect(Collectors.toList());

                // 遍历 days 列表，将不存在于 listAttDay 中的 currentDay 添加进 listAttDay
                for (String dayStr : days) {
                    // 检查是否存在该 currentDay
                    boolean dayExists = listAttDay.stream()
                            .anyMatch(attDay -> dayStr.equals(attDay.getCurrentDay()));
                    // 如果不存在，则添加新的 AttDayBean 记录
                    if (!dayExists) {
                        listAttDay.add(new AttDayBean(dayStr, "旷", ""));
                    }
                }

                // 定义日期格式
                SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat newFormat = new SimpleDateFormat("M.d");

                // 首先对 listAttDay 按照 Date 类型进行排序
                Collections.sort(listAttDay, new Comparator<AttDayBean>() {
                    @Override
                    public int compare(AttDayBean day1, AttDayBean day2) {
                        try {
                            Date date1 = originalFormat.parse(day1.getCurrentDay());
                            Date date2 = originalFormat.parse(day2.getCurrentDay());
                            return date1.compareTo(date2);
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                    }
                });
                // 排序完成后，转换日期格式为 M.d
                for (AttDayBean attDay : listAttDay) {
                    Date date = originalFormat.parse(attDay.getCurrentDay());
                    String formattedDate = newFormat.format(date); // 转换为 M.d 格式
                    attDay.setCurrentDay(formattedDate);
                }
                // 创建新的 AttDataDetailsBean，并添加到最终的 listData 中
                AttDataDetailsBean newUserData = new AttDataDetailsBean(userId, userName, orgName, listAttDay);
                listData.add(newUserData);
            }

            //开始导出
            ArrayList<Map<String, Object>> rows = new ArrayList<>();
            //数据赋值
            for (int i = 0; i < listData.size(); i++) {
                AttDataDetailsBean o = listData.get(i);
                Map<String, Object> row = new LinkedHashMap<>();
                row.put("序号", i + 1);
                row.put("部门", o.getOrgName());
                row.put("姓名", o.getUserName());
                List<AttDayBean> listAttDay = listData.get(i).getListAttDay();
                for (int j = 0; j < listAttDay.size(); j++) {
                    row.put(listAttDay.get(j).getCurrentDay(), listAttDay.get(j).getAttType());
                }
                rows.add(row);
            }

            // 导出标题
            ExcelWriter writer = ExcelUtil.getWriter(true);
//            writer.merge(0,0,0,2 + days.size(),
//                    "考勤表",true);
//
//
//            writer.merge(1,1,0,2 + days.size(),
//                     bean.getStartDate() + "至" + bean.getEndDate() + "考勤",true);
//            writer.merge(2,2,0,2 + days.size(),
//                    "部门：",true);

            writer.merge(2 + days.size(),
                    bean.getStartDate() + "至" + bean.getEndDate() + "考勤", true);
            int rowNum = 2;
            writer.merge(rowNum + listData.size(), rowNum + listData.size() + 1, 0, 0,
                    "说明", false);
            writer.merge(rowNum + listData.size(), rowNum + listData.size(), 1, 2 + days.size(),
                    "1.考勤记录：出勤记“√”，出差记“Δ”，年休假记“年”，探亲假记“探”，事假记“事”，法定假记“法”，病假记“病”，产假记“产”，婚假记“婚”，丧假记“丧”，育儿假记“育”，陪护假记“陪”，补休记“补”，旷工记“旷”，迟到记“迟”，早退记“退”，流产假记“流”，哺乳假记“哺”，节育假记“节”，父母护理假记“护”，其他记“其他”，省内工地记“工”，省外工地记“外”,出差需在备注栏备注清楚出差地点。", false);
            writer.merge(rowNum + listData.size() + 1, rowNum + listData.size() + 1, 1, 2 + days.size(),
                    "2.员工有关请假凭证，记录清楚准确，与本表于次月3日前一并报人力资源管理部门（专业分公司报送时间为30日前）。", false);
            writer.autoSizeColumn(3);
            writer.write(rows, true);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(bean.getStartDate() + "至" + bean.getEndDate() + "考勤", "UTF-8") + ".xlsx");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            ServletOutputStream out = null;
            try {
                out = response.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.flush(out, true);
            writer.close();
            IoUtil.close(out);

        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }


    /**
     * 组织导出
     *
     * @param response
     * @param bean
     * @return void
     * @author：fly
     * @date：2024-10-14-10:30
     */
//    @RequiresPermissions("org:org:export")
    @GetMapping("/exportOrg")
    public void exportOrg(HttpServletResponse response, SysOrg bean) {
        try {
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    // 根据用户id查询是否是部门负责人、部门考勤员
                    Long userId = SecurityUtils.getUserId();
                    List<MapVo> orgList = sysOrgDao.getOrgIdList(userId);
                    if (!orgList.isEmpty() ) {
                        // 使用 LinkedHashSet 来保证顺序并自动去重
                        Set<String> idsSet = new LinkedHashSet<>();
                        for (MapVo mapVo : orgList) {
                            String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                            if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                // 将分割后的数组添加到 Set 中，自动去重
                                Collections.addAll(idsSet, id.split(","));
                            }
                        }
                        // 如果需要转换回 List 类型
                        List<String> uniqueIds = new ArrayList<>(idsSet);
                        bean.setOrgList(uniqueIds);
                    }else{
                        //剩下的人员全部只能看到自己的信息
                        bean.setUserId(userId);
                    }

                }
            }
            List<SysOrgExport> personExportVoList = new ArrayList<>();
            List<SysOrg> orgList = sysOrgService.selectOrgList(bean);
            for (int i = 0; i < orgList.size(); i++) {
                SysOrg vo = orgList.get(i);
                SysOrgExport voe = new SysOrgExport();
                BeanUtils.copyProperties(vo, voe);
                voe.setId((i + 1));
                voe.setIsProvince("1".equals(vo.getReviewerStatus()) ? "省内" : "省外");
                personExportVoList.add(voe);
            }
            extracted(personExportVoList, SysOrgExport.class, "组织导出", "组织导出", "组织导出", response);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }


    /**
     * 日报表导出
     *
     * @param response
     * @param bean
     * @return void
     * @author：fly
     * @date：2024-10-14-10:30
     */
    @GetMapping("/exportDayReport")
    public void exportDayReport(HttpServletResponse response, AttDayReportBean bean) {
        try {
            MultiSheetExcelExporter exporter = new MultiSheetExcelExporter();
            //将表格时间区间取出来做标题
            String title = bean.getStartDate() + "至" + bean.getEndDate();
            List<AttDayReportBean> attDayReportList = attendanceDetailsService.getAttDayReportList(bean);
            Sheet departmentSheet1 = exporter.createSheet("日报表详情");
            List<String> departmentHeaders1 = Arrays.asList("序号", "考勤日期", "正常打卡人数", "迟到人数", "早退人数",
                    "旷工人数", "请假人数", "打卡地异常人数", "出入异常人数", "轮休人数", "临时外出人数");

            exporter.addHeaderRowAndTitle(departmentSheet1, departmentHeaders1, title);
            List<Map<String, Object>> departmentData1 = new ArrayList<>();
            for (int i = 0; i < attDayReportList.size(); i++) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", i + 1);
                map.put("考勤日期", attDayReportList.get(i).getAttCurrentDay());
                map.put("正常打卡人数", attDayReportList.get(i).getNormalNum());
                map.put("迟到人数", attDayReportList.get(i).getLateNum());
                map.put("早退人数", attDayReportList.get(i).getEarlyNum());
                map.put("旷工人数", attDayReportList.get(i).getSkippingNum());
                map.put("请假人数", attDayReportList.get(i).getLeaveNum());
                map.put("打卡地异常人数", attDayReportList.get(i).getAddressErrorNum());
                map.put("出入异常人数", attDayReportList.get(i).getEinErrorNum());
                map.put("轮休人数", attDayReportList.get(i).getRestNum());
                map.put("临时外出人数", attDayReportList.get(i).getOutNum());
                departmentData1.add(map);
            }
            exporter.addDataRows(departmentSheet1, departmentData1, departmentHeaders1);
            //详情的数据导出
            Map<String, String> headers = new HashMap<>();
            headers.put("1", "正常打卡");
            headers.put("2", "迟到详情");
            headers.put("3", "旷工详情");
            headers.put("4", "早退详情");
            headers.put("5", "轮休详情");
            headers.put("6", "请假详情");
            headers.put("7", "临时外出");
            headers.put("8", "出入异常");
            headers.put("9", "打卡地异常");
            //工作外出单独一个，序号不占用考勤状态
            headers.put("99", "工作外出");
            Map<Long, String> attStatus = getStringStringMap();
            if (StringHelper.isNotEmpty(bean.getStartDate()) && StringHelper.isNotEmpty(bean.getEndDate())) {
                AttDataDetailsBean dayTable = new AttDataDetailsBean();
                dayTable.setStartDate(bean.getStartDate());
                dayTable.setEndDate(bean.getEndDate());
                headers.entrySet()
                        .forEach(entry -> {
                            if ("99".equals(entry.getKey())) {
                                List<AttDataDetailsBean> list = attendanceDetailsService.getOutCountList(dayTable);
                                Sheet departmentSheet2 = exporter.createSheet(entry.getValue());
                                List<String> departmentHeaders2 = Arrays.asList("序号", "考勤日期", "姓名", "所属部门", "打卡时间", "打卡地址");
                                exporter.addHeaderRowAndTitle(departmentSheet2, departmentHeaders2, title);
                                List<Map<String, Object>> departmentData2 = new ArrayList<>();
                                for (int i = 0; i < list.size(); i++) {
                                    Map<String, Object> map = new LinkedHashMap<>();
                                    map.put("序号", i + 1);
                                    map.put("考勤日期", list.get(i).getAttCurrentDay());
                                    map.put("姓名", list.get(i).getUserName());
                                    map.put("所属部门", list.get(i).getOrgName());
                                    map.put("打卡时间", list.get(i).getAttCurrentTime());
                                    map.put("打卡地址", list.get(i).getAttAddress());
                                    departmentData2.add(map);
                                    departmentData2.add(map);
                                }
                                exporter.addDataRows(departmentSheet2, departmentData2, departmentHeaders2);
                            } else {
                                dayTable.setAttStatus(entry.getKey());
                                List<AttDataDetailsBean> list = attendanceDetailsService.getAttDayReportDetailsList(dayTable);
                                Sheet departmentSheet2 = exporter.createSheet(entry.getValue());
                                List<String> departmentHeaders2 = Arrays.asList("序号", "姓名", "所属部门", "考勤日期", "上班打卡时间", "上班状态", "打卡地址", "下班打卡时间", "下班状态", "打卡地址");
//                            exporter.addHeaderRow(departmentSheet2, departmentHeaders2);
                                exporter.addHeaderRowAndTitle(departmentSheet2, departmentHeaders2, title);
                                List<Map<String, Object>> departmentData2 = new ArrayList<>();
                                for (int i = 0; i < list.size(); i++) {
                                    Map<String, Object> map = new LinkedHashMap<>();
                                    map.put("序号", i + 1);
                                    map.put("姓名", list.get(i).getUserName());
                                    map.put("所属部门", list.get(i).getOrgName());
                                    map.put("考勤日期", list.get(i).getAttCurrentDay());
                                    map.put("上班打卡时间", list.get(i).getToWorkAttCurrentTime());
                                    map.put("上班状态", attStatus.get(Long.parseLong(list.get(i).getToWorkAttStatus())));
                                    map.put("上班打卡地址", list.get(i).getToWorkAttAddress());
                                    map.put("下班打卡时间", list.get(i).getOffWorkAttCurrentTime());
                                    map.put("下班状态", attStatus.get(Long.parseLong(list.get(i).getOffWorkAttStatus())));
                                    map.put("下班打卡地址", list.get(i).getOffWorkAttAddress());
                                    departmentData2.add(map);
                                }
                                exporter.addDataRows(departmentSheet2, departmentData2, departmentHeaders2);

                            }
                        });
                // 导出Excel文件
                exporter.exportToResponse(response, "日报表导出");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private Map<Long, String> getStringStringMap() {
//        Map<String, String> attStatus = new HashMap<>();
//
//        attStatus.put("1", "正常");
//        attStatus.put("2", "迟到");
//        attStatus.put("3", "旷工");
//        attStatus.put("4", "早退");
//        attStatus.put("5", "轮休");
//        attStatus.put("6", "请假");
//        attStatus.put("7", "外出");
//        attStatus.put("8", "出入异常");
//        attStatus.put("9", "打卡地异常");
//        attStatus.put("10", "出差");
//        attStatus.put("11", "法定节假日");
//        attStatus.put("12", "年休假");
//        attStatus.put("13", "探亲假");
//        attStatus.put("14", "事假");
//        attStatus.put("15", "病假");
//        attStatus.put("16", "产假");
//        attStatus.put("17", "婚假");
//        attStatus.put("18", "丧假");
//        attStatus.put("19", "育儿假");
//        attStatus.put("20", "陪护假");
        List<MapVo> arrayList = attendanceDetailsService.getAttStatusList();
        return arrayList.stream()
                .collect(Collectors.toMap(MapVo::getId, MapVo::getName, (existing, replacement) -> existing));
    }

    /**
     * 月报表导出
     *
     * @param response
     * @param bean
     * @return void
     * @author：fly
     * @date：2024-10-14-10:30
     */
    @GetMapping("/exportMonthReport")
    public void exportMonthReport(HttpServletResponse response, AttMonthReportBean bean) {
        try {
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    // 根据用户id查询是否是管理员或帮忙负责人
                    Long userId = SecurityUtils.getUserId();
                    List<MapVo> orgList = sysOrgDao.getOrgIdList(userId);
                    if (!orgList.isEmpty()) {
                        // 使用 LinkedHashSet 来保证顺序并自动去重
                        Set<String> idsSet = new LinkedHashSet<>();
                        for (MapVo mapVo : orgList) {
                            String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                            if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                // 将分割后的数组添加到 Set 中，自动去重
                                Collections.addAll(idsSet, id.split(","));
                            }
                        }
                        // 如果需要转换回 List 类型
                        List<String> uniqueIds = new ArrayList<>(idsSet);
                        bean.setOrgList(uniqueIds);
                    }else{
                        bean.setUserId(userId);
                    }
                }
            }
            MultiSheetExcelExporter exporter = new MultiSheetExcelExporter();
            //将表格时间区间取出来做标题
            String title = bean.getStartMonth() + " ~ " + bean.getEndMonth();
            List<AttMonthReportBean> attDayReportList = attendanceDetailsService.getAttMonthReportList(bean);
            Sheet departmentSheet1 = exporter.createSheet("月报表详情");
            List<String> departmentHeaders1 = Arrays.asList("序号", "姓名", "所属部门", "考勤月","打卡记录", "应考勤天数", "正常打卡天数",
                    "迟到天数", "早退天数", "旷工天数", "请假天数", "打卡地异常天数", "出入异常天数", "轮休天数", "临时外出天数", "出差天数");
            exporter.addHeaderRowAndTitle(departmentSheet1, departmentHeaders1, title);
            List<Map<String, Object>> departmentData1 = new ArrayList<>();
            for (int i = 0; i < attDayReportList.size(); i++) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", i + 1);
                map.put("姓名", attDayReportList.get(i).getUserName());
                map.put("所属部门", attDayReportList.get(i).getOrgName());
                map.put("考勤月", attDayReportList.get(i).getAttCurrentMonth());
                map.put("打卡记录", attDayReportList.get(i).getClockingRecordNum());
                map.put("应考勤天数", attDayReportList.get(i).getRequiredDays());
                map.put("正常打卡天数", attDayReportList.get(i).getNormalNum());
                map.put("迟到天数", attDayReportList.get(i).getLateNum());
                map.put("早退天数", attDayReportList.get(i).getEarlyNum());
                map.put("旷工天数", attDayReportList.get(i).getSkippingNum());
                map.put("请假天数", attDayReportList.get(i).getLeaveNum());
                map.put("打卡地异常天数", attDayReportList.get(i).getAddressErrorNum());
                map.put("出入异常天数", attDayReportList.get(i).getEinErrorNum());
                map.put("轮休天数", attDayReportList.get(i).getRestNum());
                map.put("临时外出天数", attDayReportList.get(i).getOutNum());
                map.put("出差天数", attDayReportList.get(i).getBusinessTripNum());
                departmentData1.add(map);
            }
            exporter.addDataRows(departmentSheet1, departmentData1, departmentHeaders1);
            //详情的数据导出
            Map<String, String> headers = new HashMap<>();
            headers.put("1", "正常打卡");
            headers.put("2", "迟到详情");
            headers.put("3", "旷工详情");
            headers.put("4", "早退详情");
            headers.put("5", "轮休详情");
            headers.put("6", "请假详情");
            headers.put("7", "临时外出");
            headers.put("8", "出入异常");
            headers.put("9", "打卡地异常");
            headers.put("10", "出差详情");
            headers.put("99", "工作外出");
            Map<Long, String> attStatus = getStringStringMap();
            if (StringHelper.isNotEmpty(bean.getStartMonth()) && StringHelper.isNotEmpty(bean.getEndMonth())) {
                List<String> monthFirstAndLast = DateTimeHelper.getMonthStartAndEndDay(bean.getStartMonth(), bean.getEndMonth());
                AttDetailBean dayTable = new AttDetailBean();
                dayTable.setStartDate(monthFirstAndLast.get(0));
                dayTable.setEndDate(monthFirstAndLast.get(1));
                dayTable.setName(bean.getUserName());
                if (bean.getOrgId() != null) {
                    dayTable.setOrgId(String.valueOf(bean.getOrgId()));
                }else{
                    //受限于当前登录人
                    if(bean.getOrgList() != null && !bean.getOrgList().isEmpty()){
                        dayTable.setOrgList(bean.getOrgList());
                    }
                }
                headers.entrySet()
                        .forEach(entry -> {
                            if ("99".equals(entry.getKey())) {
                                AttDataDetailsBean att = new AttDataDetailsBean();
//                                att.setAttCurrentMonth(bean.getMonth());
                                att.setStartDate(monthFirstAndLast.get(0));
                                att.setEndDate(monthFirstAndLast.get(1));
                                if (bean.getOrgId() != null) {
                                    att.setOrgId(bean.getOrgId());
                                }else{
                                    //受限于当前登录人
                                    if(bean.getOrgList() != null && !bean.getOrgList().isEmpty()){
                                        att.setOrgList(bean.getOrgList());
                                    }
                                }
                                att.setUserName(bean.getUserName());
                                //存在人员换组织情况，先查人再去查工作外出
                                List<AttDataDetailsBean> list = attendanceDetailsService.getOrgUserOutCountList(att);
                                Sheet departmentSheet2 = exporter.createSheet(entry.getValue());
                                List<String> departmentHeaders2 = Arrays.asList("序号", "考勤日期", "姓名", "所属部门", "打卡时间", "打卡地址");
                                exporter.addHeaderRowAndTitle(departmentSheet2, departmentHeaders2, title);
                                List<Map<String, Object>> departmentData2 = new ArrayList<>();
                                for (int i = 0; i < list.size(); i++) {
                                    Map<String, Object> map = new LinkedHashMap<>();
                                    map.put("序号", i + 1);
                                    map.put("考勤日期", list.get(i).getAttCurrentDay());
                                    map.put("姓名", list.get(i).getUserName());
                                    map.put("所属部门", list.get(i).getOrgName());
                                    map.put("打卡时间", list.get(i).getAttCurrentTime());
                                    map.put("打卡地址", list.get(i).getAttAddress());
                                    departmentData2.add(map);
                                }
                                exporter.addDataRows(departmentSheet2, departmentData2, departmentHeaders2);
                            } else {
                                dayTable.setAttStatis(Integer.parseInt(entry.getKey()));
                                List<AttDetailBean> list = attDetailByMonthService.getDetailList(dayTable);
                                Sheet departmentSheet2 = exporter.createSheet(entry.getValue());
                                List<String> departmentHeaders2 = Arrays.asList("序号", "姓名", "所属部门", "考勤日期", "上班打卡时间", "上班状态", "上班打卡地址", "下班打卡时间", "下班状态", "下班打卡地址");
                                exporter.addHeaderRowAndTitle(departmentSheet2, departmentHeaders2, title);
                                List<Map<String, Object>> departmentData2 = new ArrayList<>();
                                for (int i = 0; i < list.size(); i++) {
                                    Map<String, Object> map = new LinkedHashMap<>();
                                    map.put("序号", i + 1);
                                    map.put("姓名", list.get(i).getName());
                                    map.put("所属部门", list.get(i).getOrgName());
                                    map.put("考勤日期", list.get(i).getAttCurrent());
                                    map.put("上班打卡时间", list.get(i).getGoWorkTime());
                                    map.put("上班状态", attStatus.get(Long.parseLong(String.valueOf(list.get(i).getGoWorkStatus()))));
                                    map.put("上班打卡地址", list.get(i).getGoWorkAddress());
                                    map.put("下班打卡时间", list.get(i).getOffWorkTime());
                                    map.put("下班状态", attStatus.get(Long.parseLong(String.valueOf(list.get(i).getOffWorkStatus()))));
                                    map.put("下班打卡地址", list.get(i).getOffWorkAddress());
                                    departmentData2.add(map);
                                }
                                exporter.addDataRows(departmentSheet2, departmentData2, departmentHeaders2);
                            }
                        });
                // 导出Excel文件
                exporter.exportToResponse(response, "月报表导出");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private List<String> getMonthFirstAndLast(String monthString) {
        List<String> months = new ArrayList<>();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        YearMonth yearMonth;
        // 使用预定义的 ISO_LOCAL_DATE 格式 (yyyy-MM-dd)
        DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE;

        try {
            // 判空及默认为当月
            if (monthString == null || monthString.trim().isEmpty()) {
                // 如果字符串为空或仅包含空白字符，取当前月份
                yearMonth = YearMonth.from(LocalDate.now());
            } else {
                // 尝试将字符串解析为 YearMonth 对象
                yearMonth = YearMonth.parse(monthString, formatter);
            }
            // 获取该月的第一天
            LocalDate firstDayOfMonth = yearMonth.atDay(1);
            // 获取该月的最后一天
            LocalDate lastDayOfMonth = yearMonth.atEndOfMonth();
            months.add(firstDayOfMonth.format(isoFormatter));
            months.add(lastDayOfMonth.format(isoFormatter));
        } catch (DateTimeParseException e) {
            // 如果解析失败，打印错误信息并使用当前月份
            YearMonth currentYearMonth = YearMonth.from(LocalDate.now());
            LocalDate firstDayOfCurrentMonth = currentYearMonth.atDay(1);
            LocalDate lastDayOfCurrentMonth = currentYearMonth.atEndOfMonth();
            months.add(firstDayOfCurrentMonth.format(isoFormatter));
            months.add(lastDayOfCurrentMonth.format(isoFormatter));
        }
        return months;
    }


    /**
     * 导出excel文件
     *
     * @param list      数据
     * @param clazz     bean.class
     * @param title     标题
     * @param sheetName sheet名字
     * @param fileName  文件名
     * @param response  响应
     * @throws IOException
     */
    private static void extracted(List<? extends Object> list, Class<? extends Object> clazz, String title, String sheetName, String fileName, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setStyle(ExcelStyleUtil.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, list);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }

    /**
     * 获取两个日期之间的所有日期
     *
     * @param startTime 开始日期
     * @param endTime   结束日期
     * @return
     */
    public static List<String> getDays(String startTime, String endTime) {
        // 返回的日期集合
        List<String> days = new ArrayList<String>();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {

            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }


    /**
     * 休假报备
     *
     * @param response
     * @param bean
     * @return void
     */
    @GetMapping("/exportLeaveReporting")
    public void exportLeaveReporting(HttpServletResponse response, LeaveReportingBean bean) {
        try {
            List<LeaveReportingBean> personExportVoList = new ArrayList<>();
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    if(Collections.frequency(roleId, "15")==0){
                        List<MapVo> orgList = sysUser.getOrgList();
                        if (!orgList.isEmpty()) {
                            ArrayList<String> ids = new ArrayList<>();
                            for (MapVo mapVo : orgList) {
                                String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                                // 使用 Arrays.asList() 将数组转换为 ArrayList
                                ArrayList<String> idList = new ArrayList<>(Arrays.asList(id.split(",")));
                                ids.addAll(idList);
//                        ids.add(String.valueOf(mapVo.getId()));
                            }
                            bean.setOrgList(ids);
                        }
                    }else{
                        Long userId = SecurityUtils.getUserId();
                        bean.setUserId(userId);
                    }
                }
            }
            List<LeaveReportingBean> personLists = leaveReportingService.getLeaveReportingList(bean);
            for (int i = 0; i < personLists.size(); i++) {
                LeaveReportingBean vo = personLists.get(i);
                vo.setId((i + 1));
                //事件处理
                if ("1".equals(vo.getLeaveStartInterval())) {
                    vo.setLeaveStartInterval(vo.getLeaveStartDate() + " ");
                } else {
                    vo.setLeaveStartInterval(vo.getLeaveStartDate() + " ");
                }
                if ("1".equals(vo.getLeaveEndInterval())) {
                    vo.setLeaveEndInterval(vo.getLeaveEndDate() + " ");
                } else {
                    vo.setLeaveEndInterval(vo.getLeaveEndDate() + " ");
                }
                // 创建一个 SimpleDateFormat 对象，用于格式化日期
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 将 Date 转换为 String
                String dateString = formatter.format(vo.getCreateTime());
                vo.setLeaveDate(dateString);
                personExportVoList.add(vo);
            }
            extracted(personExportVoList, LeaveReportingBean.class, "休假导出", "休假导出", "休假导出", response);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }


    /**
     * 出差报备
     *
     * @param response
     * @param bean
     * @return void
     */
    @GetMapping("/exportEvection")
    public void exportEvection(HttpServletResponse response, EvectionBean bean) {
        try {
            List<EvectionBean> personExportVoList = new ArrayList<>();
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if( roleId !=null && !roleId.isEmpty()){
                if (Collections.frequency(roleId, "1")==0 && Collections.frequency(roleId, "16")==0) {
                    if(Collections.frequency(roleId, "15")==0){
                        List<MapVo> orgList = sysUser.getOrgList();
                        if (!orgList.isEmpty()) {
                            ArrayList<String> ids = new ArrayList<>();
                            for (MapVo mapVo : orgList) {
                                String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                                // 使用 Arrays.asList() 将数组转换为 ArrayList
                                ArrayList<String> idList = new ArrayList<>(Arrays.asList(id.split(",")));
                                ids.addAll(idList);
//                        ids.add(String.valueOf(mapVo.getId()));
                            }
                            bean.setOrgList(ids);
                        }
                    }else{
                        Long userId = SecurityUtils.getUserId();
                        bean.setUserId(userId);
                    }
                }
            }
            List<EvectionBean> personLists = evectionService.getEvectionList(bean);
            for (int i = 0; i < personLists.size(); i++) {
                EvectionBean vo = personLists.get(i);
                vo.setId((i + 1));
                //事件处理
                if ("1".equals(vo.getLeaveStartInterval())) {
                    vo.setLeaveStartInterval(vo.getLeaveStartDate() + " ");
                } else {
                    vo.setLeaveStartInterval(vo.getLeaveStartDate() + " ");
                }
                if ("1".equals(vo.getLeaveEndInterval())) {
                    vo.setLeaveEndInterval(vo.getLeaveEndDate() + " ");
                } else {
                    vo.setLeaveEndInterval(vo.getLeaveEndDate() + " ");
                }
                // 创建一个 SimpleDateFormat 对象，用于格式化日期
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 将 Date 转换为 String
                String dateString = formatter.format(vo.getCreateTime());
                vo.setLeaveDate(dateString);
                personExportVoList.add(vo);
            }
            extracted(personExportVoList, EvectionBean.class, "出差导出", "出差导出", "出差导出", response);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    /**
     * 组织架构变更导出
     *
     * @param response
     * @param bean
     * @return void
     * @author：fly
     * @date：2024-10-14-10:30
     */
//    @RequiresPermissions("att:org:change:export")
    @GetMapping("/exportOrgChange")
    public void exportOrgChange(HttpServletResponse response, OrgChangeBean bean) {
        try {
            List<OrgChangeBean> personExportVoList = new ArrayList<>();
            if ("1".equals(bean.getExportType())) {
                //只查自己的
                Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
                bean.setUserId(userId);
            } else {
                if (StringUtils.isEmpty(bean.getIsCheck())) {
                    //不查撤回的
                    bean.setIsCheck("-1");
                }
            }
            List<OrgChangeBean> personLists = orgChangeService.selectOrgChangeList(bean);
            for (int i = 0; i < personLists.size(); i++) {
                OrgChangeBean vo = personLists.get(i);
                vo.setId((i + 1L));
                vo.setIsCheck(BusinessConstants.WAIT_CHECK.equals(vo.getIsCheck()) ? "待审核" : BusinessConstants.PASS_CHECK.equals(vo.getIsCheck()) ? "已通过" : BusinessConstants.NOT_PASS_CHECK.equals(vo.getIsCheck()) ? "未通过" : "撤回");
                vo.setIsChangeAttGroup(BusinessConstants.WAIT_CHECK.equals(vo.getIsChangeAttGroup()) ? "不变" : "变更");
                // 创建一个 SimpleDateFormat 对象，用于格式化日期
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 将 Date 转换为 String
                String dateString = formatter.format(vo.getCreateTime());
                vo.setStartTime(dateString);
                personExportVoList.add(vo);
            }
            extracted(personExportVoList, OrgChangeBean.class, "组织架构变更记录导出", "组织架构变更记录导出", "组织架构变更记录导出", response);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }


    /**
     * 小程序打卡数据导出
     *
     * @param response
     * @param bean
     * @return void
     * @author：fly
     * @date：2024-10-14-10:30
     */
    @GetMapping("/exportWechatReport")
    public void exportWechatReport(HttpServletResponse response, WechatBean bean) {
        try {
            List<WechatBean> wechatExportVoList = new ArrayList<>();
            List<WechatBean> wechatReportList = wechatService.getWechatUserList(bean);
            for (int i = 0; i < wechatReportList.size(); i++) {
                WechatBean vo = wechatReportList.get(i);
                vo.setId((i + 1));
                String attStatus = getAttStatus(vo.getAttStatus());
                vo.setAttStatus(attStatus);
                wechatExportVoList.add(vo);
            }
            extracted(wechatExportVoList, WechatBean.class, "小程序打卡数据导出", "小程序打卡数据导出", "小程序打卡数据导出", response);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    private String getAttStatus(String attStatus) {
        switch (attStatus) {
            case "1":
                attStatus = "正常";
                break;
            case "2":
                attStatus = "迟到";
                break;
            case "3":
                attStatus = "旷工";
                break;
            case "4":
                attStatus = "早退";
                break;
            case "5":
                attStatus = "轮休";
                break;
            case "6":
                attStatus = "请假";
                break;
            case "7":
                attStatus = "临时外出";
                break;
            case "8":
                attStatus = "出入异常";
                break;
            case "9":
                attStatus = "打卡地异常";
                break;
            case "10":
                attStatus = "出差";
                break;
            case "19":
                attStatus = "育儿假";
                break;
            default:
                attStatus = "休假";
                break;
        }
        return attStatus;
    }


    /**
     * 数据管理-休假报备-微信
     *
     * @param response
     * @param bean
     * @return void
     */
    @GetMapping("/exportWechatLeaveReporting")
    public void exportWechatLeaveReporting(HttpServletResponse response, WechatLeaveReportingBean bean) {
        try {
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    // 根据用户id查询是否是管理员或帮忙负责人
                    Long userId = SecurityUtils.getUserId();
                    List<MapVo> orgList = sysOrgDao.getOrgIdList(userId);
                    if (!orgList.isEmpty()) {
                        // 使用 LinkedHashSet 来保证顺序并自动去重
                        Set<String> idsSet = new LinkedHashSet<>();
                        for (MapVo mapVo : orgList) {
                            String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                            if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                // 将分割后的数组添加到 Set 中，自动去重
                                Collections.addAll(idsSet, id.split(","));
                            }
                        }
                        // 如果需要转换回 List 类型
                        List<String> uniqueIds = new ArrayList<>(idsSet);
                        bean.setOrgList(uniqueIds);
                    }else{
                        bean.setUserId(userId);
                    }
                }
            }
            List<WechatLeaveReportingBean> personExportVoList = new ArrayList<>();
            List<WechatLeaveReportingBean> personLists = wechatLeaveReportingService.getLeaveReportingList(bean);
            for (int i = 0; i < personLists.size(); i++) {
                WechatLeaveReportingBean vo = personLists.get(i);
                vo.setId((i + 1));
                //事件处理
                if ("1".equals(vo.getLeaveStartInterval())) {
                    vo.setLeaveStartInterval(vo.getLeaveStartDate() + " ");
                } else {
                    vo.setLeaveStartInterval(vo.getLeaveStartDate() + " ");
                }
                if ("1".equals(vo.getLeaveEndInterval())) {
                    vo.setLeaveEndInterval(vo.getLeaveEndDate() + " ");
                } else {
                    vo.setLeaveEndInterval(vo.getLeaveEndDate() + " ");
                }
                // 创建一个 SimpleDateFormat 对象，用于格式化日期
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 将 Date 转换为 String
                String dateString = formatter.format(vo.getCreateTime());
                vo.setLeaveDate(dateString);
                personExportVoList.add(vo);
            }
            extracted(personExportVoList, WechatLeaveReportingBean.class, "数据管理-休假导出", "数据管理-休假导出", "数据管理-休假导出", response);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }


    /**
     * 数据管理-出差报备
     *
     * @param response
     * @param bean
     * @return void
     */
    @GetMapping("/exportWechatEvection")
    public void exportWechatEvection(HttpServletResponse response, WechatEvectionBean bean) {
        try {
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    // 根据用户id查询是否是管理员或帮忙负责人
                    Long userId = SecurityUtils.getUserId();
                    List<MapVo> orgList = sysOrgDao.getOrgIdList(userId);
                    if (!orgList.isEmpty()) {
                        // 使用 LinkedHashSet 来保证顺序并自动去重
                        Set<String> idsSet = new LinkedHashSet<>();
                        for (MapVo mapVo : orgList) {
                            String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                            if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                // 将分割后的数组添加到 Set 中，自动去重
                                Collections.addAll(idsSet, id.split(","));
                            }
                        }
                        // 如果需要转换回 List 类型
                        List<String> uniqueIds = new ArrayList<>(idsSet);
                        bean.setOrgList(uniqueIds);
                    }else{
                        bean.setUserId(userId);
                    }
                }
            }
            List<WechatEvectionBean> personExportVoList = new ArrayList<>();
            List<WechatEvectionBean> personLists = wechatevectionService.getEvectionList(bean);
            for (int i = 0; i < personLists.size(); i++) {
                WechatEvectionBean vo = personLists.get(i);
                vo.setId((i + 1));
                //事件处理
                if ("1".equals(vo.getLeaveStartInterval())) {
                    vo.setLeaveStartInterval(vo.getLeaveStartDate() + " ");
                } else {
                    vo.setLeaveStartInterval(vo.getLeaveStartDate() + " ");
                }
                if ("1".equals(vo.getLeaveEndInterval())) {
                    vo.setLeaveEndInterval(vo.getLeaveEndDate() + " ");
                } else {
                    vo.setLeaveEndInterval(vo.getLeaveEndDate() + " ");
                }
                // 创建一个 SimpleDateFormat 对象，用于格式化日期
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 将 Date 转换为 String
                String dateString = formatter.format(vo.getCreateTime());
                vo.setLeaveDate(dateString);
                personExportVoList.add(vo);
            }
            extracted(personExportVoList, WechatEvectionBean.class, "数据管理-出差导出", "数据管理-出差导出", "数据管理-出差导出", response);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    /**
     * 考勤明细二级页面工作外出导出
     *
     * @param response
     * @param bean
     * @return void
     * @author：fly
     * @date：2024-10-14-10:30
     */
//    @RequiresPermissions("att:org:change:export")
    @GetMapping("/exportAttWorkOut")
    public void exportAttWorkOut(HttpServletResponse response, AttDataDetailsBean bean) {
        try {
            List<AttDataDetailsBean> list = attendanceDetailsService.getOutCountList(bean);
            extracted(list, AttDataDetailsBean.class, "外出导出记录导出", "外出导出记录导出", "外出导出记录导出", response);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    /**
     * 八大员缺员兼职查询-导出
     * @param response
     * @param vo
     * @return void
     * @author cwchen
     * @date 2025/2/11 9:16
     */
    @GetMapping("/exportEightMembersVacancy")
    public void exportEightMembersVacancy(HttpServletResponse response, EightMembersVacancyVo vo) {
        try {
            List<EightMembersVacancyVo> list = eightMembersVacancyService.getList(vo);
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSerialNumber(i + 1);
            }
            extracted(list, EightMembersVacancyVo.class, "八大员缺员兼职查询", "八大员缺员兼职查询", "八大员缺员兼职查询", response);
        } catch (IOException e) {
            log.error(e.toString(),e);
        }
    }


}
