package com.bonus.system.dept.controller;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.core.utils.StringHelper;
import com.bonus.common.core.utils.poi.MultiSheetExcelExporter;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.log.annotation.Log;
import com.bonus.common.log.enums.BusinessType;
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.AttDataDetailsBean;
import com.bonus.system.att.entity.AttMonthReportBean;
import com.bonus.system.basic.dao.SysOrgDao;
import com.bonus.system.dept.dao.ProDeptRoleDao;
import com.bonus.system.dept.entity.EightRoleBean;
import com.bonus.system.dept.entity.EightRoleVo;
import com.bonus.system.dept.entity.ProDeptRoleBean;
import com.bonus.system.dept.entity.ProDeptRoleDo;
import com.bonus.system.dept.service.ProDeptRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 项目部角色
 *
 * @author fly
 */
@RestController
@RequestMapping("/proDeptRole")
@Slf4j
public class ProDeptRoleController extends BaseController {

    @Resource(name = "ProDeptRoleService")
    private ProDeptRoleService proDeptRoleService;

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

    @Resource
    private SysOrgDao sysOrgDao;

    /**
     * 获取项目部角色列表(表格)
     */
    @RequiresPermissions("dept:role:list")
    @GetMapping("/getRoleUserList")
    @Log(title = "项目部管理->项目部角色管理->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo list(ProDeptRoleBean 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<ProDeptRoleBean> roleUserList = proDeptRoleService.getRoleUserList(bean);
            return endPage(roleUserList);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 根据组织编号获取详细信息
     */
    @RequiresPermissions("dept:org:query")
    @GetMapping(value = "getRoleInfoById/{orgId}/{deptRoleId}")
    @Log(title = "项目部管理->项目部角色管理->编号获取详细信息", businessType = BusinessType.QUERY)
    public AjaxResult getInfoById(@PathVariable("orgId") Long orgId,@PathVariable("deptRoleId") Long deptRoleId) {
        try{
            ProDeptRoleBean o = new ProDeptRoleBean();
            o.setOrgId(orgId);
            o.setDeptRoleId(deptRoleId);
            return success(proDeptRoleService.getInfoById(o));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");

    }

    /**
     * 修改项目部角色
     */
    @RequiresPermissions("dept:role:edit")
    @PutMapping
    @Log(title = "项目部管理->项目部角色管理->项目部角色分配", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@RequestBody ProDeptRoleDo bean) {
        try{
            //personStatus 第一次分配人员状态（分公司项目部处分配与这个不一致）
            return toAjax(proDeptRoleService.updatePersonAssignment(bean,"1"));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 项目部角色配置审批列表(表格)
     */
    @RequiresPermissions("dept:check:list")
    @GetMapping("/getRoleCheckList")
    @Log(title = "项目部管理->项目部角色审批->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo getRoleCheckList(ProDeptRoleBean bean) {
        try{
            bean.setReviewerStatus("0");
            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<ProDeptRoleBean> roleUserList = proDeptRoleService.getRoleUserList(bean);
            for(ProDeptRoleBean roleUser : roleUserList){
                if (StringHelper.isEmpty(roleUser.getUserName())){
                    roleUser.setUserName("(分配人员已被删除)");
                }
            }
            return endPage(roleUserList);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }


    /**
     * 审批项目部角色配置
     */
    @RequiresPermissions("dept:check:edit")
    @PostMapping
    @Log(title = "项目部管理->项目部角色管理->项目部角色审批", businessType = BusinessType.UPDATE)
    public AjaxResult check(@RequestBody ProDeptRoleDo bean) {
        try{
            return toAjax(proDeptRoleService.checkPersonAssignment(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    @PostMapping("batchRoleCheck")
    @Log(title = "项目部管理->项目部角色管理->项目部角色一键审批", businessType = BusinessType.UPDATE)
    public AjaxResult batchRoleCheck(@RequestBody ProDeptRoleDo bean) {
        return proDeptRoleService.batchRoleCheck(bean);
    }

    /**
     * 查询人员树选择列表
     */
    @GetMapping("/selectOrgUserList")
    @Log(title = "项目部管理->项目部角色管理->查询组织选择列表", businessType = BusinessType.QUERY)
    public AjaxResult selectOrgUserList(ProDeptRoleBean bean) {
        try{
            return success(proDeptRoleService.selectOrgUserList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error();
    }

    /**
     * 获取项目部角色列表(表格)
     */
    @RequiresPermissions("dept:role:list")
    @GetMapping("/getRoleUserNoManagerList")
    @Log(title = "项目部管理->项目部角色管理->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo getRoleUserNoManagerList(ProDeptRoleBean 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<ProDeptRoleBean> roleUserList = proDeptRoleService.getRoleUserNoManagerList(bean);
            return endPage(roleUserList);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }



    /**
     * 查询八大员数据列表
     */
    @RequiresPermissions("dept:eight:list")
    @GetMapping("/getOrgEightRoleTable")
    @Log(title = "项目部管理->项目部角色管理->八大员数据列表", businessType = BusinessType.QUERY)
    public TableDataInfo getOrgEightRoleTable(EightRoleBean bean) {
        try{
            startPage();
            return getDataTable(proDeptRoleService.getOrgEightRoleList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 查询八大员内部详情
     */
    @RequiresPermissions("dept:eight:list")
    @GetMapping("/getOrgEightRoleDetail")
    @Log(title = "项目部管理->项目部角色管理->查询八大员内部详情", businessType = BusinessType.QUERY)
    public TableDataInfo getOrgEightRoleDetail(EightRoleBean bean) {
        try{
                List<EightRoleVo> orgEightRoleDetail = proDeptRoleService.getOrgEightRoleDetail(bean);
            return endPage(orgEightRoleDetail);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 查询八大员兼职详情
     */
    @RequiresPermissions("dept:eight:query")
    @GetMapping("/getMoreOrgData")
    @Log(title = "项目部管理->项目部角色管理->八大员兼职详情", businessType = BusinessType.QUERY)
    public AjaxResult getMoreOrgData(ProDeptRoleBean bean) {
        try{
            return success(proDeptRoleService.getMoreOrgData(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error();
    }

    @GetMapping("/exportEightMembers")
    public void exportEightMembers(HttpServletResponse response, EightRoleBean bean) {
        try {
            MultiSheetExcelExporter exporter = new MultiSheetExcelExporter();
            //将表格时间区间取出来做标题
            String title = bean.getParentOrgName();
            List<EightRoleBean> eightRoleVoList = proDeptRoleService.getOrgEightRoleList(bean);
            Sheet departmentSheet1 = exporter.createSheet(" 八大员统计报表详情");
            List<String> departmentHeaders1 = Arrays.asList("序号", "分公司名称", "缺员情况", "兼职情况");
            exporter.addHeaderRowAndTitle(departmentSheet1, departmentHeaders1, title);
            List<Map<String, Object>> departmentData1 = new ArrayList<>();

            List<String> lackOrgIds = new ArrayList<>();
            List<String> moreOrgIds = new ArrayList<>();

            for (int i = 0; i < eightRoleVoList.size(); i++){
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", i + 1);
                map.put("分公司名称", eightRoleVoList.get(i).getParentOrgName());
                map.put("缺员情况", eightRoleVoList.get(i).getLackOrgName());
                map.put("兼职情况", eightRoleVoList.get(i).getMoreOrgName());
                departmentData1.add(map);

                // 将当前项的LackOrgId加入到列表中
                String currentLackOrgId = eightRoleVoList.get(i).getLackOrgId();
                lackOrgIds.add(currentLackOrgId);

                // 将当前项的moreOrgId加入到列表中
                String currentMoreOrgId = eightRoleVoList.get(i).getMoreOrgId();
                moreOrgIds.add(currentMoreOrgId);

            }
            exporter.addDataRows(departmentSheet1, departmentData1, departmentHeaders1);

            //缺员情况详情的数据导出
            if (CollectionUtils.isNotEmpty(lackOrgIds)){
                EightRoleBean dayTable = new EightRoleBean();
                Sheet departmentSheet2 = exporter.createSheet("缺员情况详情");
                List<String> departmentHeaders2 = Arrays.asList("序号", "项目部名称", "项目经理",
                        "安全员", "质检员", "项目总工", "机械员", "资料员", "施工员", "材料员", "其他");
                exporter.addHeaderRowAndTitle(departmentSheet2, departmentHeaders2, title);
                List<Map<String, Object>> departmentData2 = new ArrayList<>();
                for (String lackOrgId : lackOrgIds){
                    if (lackOrgId == null){
                        continue;
                    }
                    dayTable.setLackOrgId(lackOrgId);
                    List<EightRoleVo> lackOrgNameList = proDeptRoleService.getOrgEightRoleDetail(dayTable);
                    for (int i = 0; i < lackOrgNameList.size(); i++){
                        Map<String, Object> map = new LinkedHashMap<>();
                        map.put("序号", i + 1);
                        map.put("项目部名称", lackOrgNameList.get(i).getOrgName());
                        map.put("项目经理", lackOrgNameList.get(i).getProjectManager());
                        map.put("安全员", lackOrgNameList.get(i).getSafetyOfficer());
                        map.put("质检员", lackOrgNameList.get(i).getQualityInspector());
                        map.put("项目总工", lackOrgNameList.get(i).getChiefEngineer());
                        map.put("机械员", lackOrgNameList.get(i).getMechanicalStaff());
                        map.put("资料员", lackOrgNameList.get(i).getDocumentStaff());
                        map.put("施工员", lackOrgNameList.get(i).getConstructionStaff());
                        map.put("材料员", lackOrgNameList.get(i).getMaterialStaff());
                        map.put("其他", lackOrgNameList.get(i).getOther());
                        departmentData2.add(map);
                    }
                }
                exporter.addDataRows(departmentSheet2, departmentData2, departmentHeaders2);
            }

            if(CollectionUtils.isNotEmpty(moreOrgIds)){
                //兼职情况详情的数据导出
                Sheet departmentSheet3 = exporter.createSheet("兼职情况详情");
                List<String> departmentHeaders3 = Arrays.asList("序号", "项目部名称", "项目经理",
                        "安全员", "质检员", "项目总工", "机械员", "资料员", "施工员", "材料员", "其他");
                exporter.addHeaderRowAndTitle(departmentSheet3, departmentHeaders3, title);
                List<Map<String, Object>> departmentData3 = new ArrayList<>();
                for (String moreOrgId : moreOrgIds) {
                    if(moreOrgId == null){
                        continue;
                    }
                    EightRoleBean dayTable = new EightRoleBean();
                    dayTable.setMoreOrgId(moreOrgId);
                    List<EightRoleVo> moreOrgNameList = proDeptRoleService.getOrgEightRoleDetail(dayTable);
                    for (int i = 0; i < moreOrgNameList.size(); i++){
                        Map<String, Object> map = new LinkedHashMap<>();
                        map.put("序号", i + 1);

                        map.put("项目部名称", moreOrgNameList.get(i).getOrgName());
                        if(moreOrgNameList.get(i).getProjectManager().equals("兼职")){
                            ProDeptRoleBean beans = new ProDeptRoleBean();
                            beans.setOrgId(moreOrgNameList.get(i).getOrgId());
                            beans.setDeptRoleId(1L);
                            List<ProDeptRoleBean> projectList = proDeptRoleService.getMoreOrgData(beans);
                            String project = "";
                            if(!projectList.isEmpty()){
                                for (int j = 0; j < projectList.size(); j++){
                                    project = project + "," + projectList.get(j).getUserName();
                                }
                            }
                            map.put("项目经理", project);
                            map.put("项目经理_isPartTime", true); // 添加一个标志位表示该字段为兼职
                        }else{
                            map.put("项目经理", moreOrgNameList.get(i).getProjectManager());
                            map.put("项目经理_isPartTime", false); // 标志位表示该字段不是兼职
                        }

                        if(moreOrgNameList.get(i).getSafetyOfficer().equals("兼职")){
                            ProDeptRoleBean beans = new ProDeptRoleBean();
                            beans.setOrgId(moreOrgNameList.get(i).getOrgId());
                            beans.setDeptRoleId(2L);
                            List<ProDeptRoleBean> safetyOfficerList = proDeptRoleService.getMoreOrgData(beans);
                            String safetyOfficer = "";
                            if(!safetyOfficerList.isEmpty()){
                                for (int j = 0; j < safetyOfficerList.size(); j++){
                                    safetyOfficer = safetyOfficer + "," + safetyOfficerList.get(j).getUserName();
                                }
                            }
                            map.put("安全员", safetyOfficer);
                            map.put("安全员_isPartTime", true);
                        }else{
                            map.put("安全员", moreOrgNameList.get(i).getSafetyOfficer());
                            map.put("安全员_isPartTime", false);
                        }

                        if(moreOrgNameList.get(i).getQualityInspector().equals("兼职")){
                            ProDeptRoleBean beans = new ProDeptRoleBean();
                            beans.setOrgId(moreOrgNameList.get(i).getOrgId());
                            beans.setDeptRoleId(3L);
                            List<ProDeptRoleBean> qualityInspectorList = proDeptRoleService.getMoreOrgData(beans);
                            String qualityInspector = "";
                            if(!qualityInspectorList.isEmpty()){
                                for (int j = 0; j < qualityInspectorList.size(); j++){
                                    qualityInspector = qualityInspector + "," + qualityInspectorList.get(j).getUserName();
                                }
                            }
                            map.put("质检员", qualityInspector);
                            map.put("质检员_isPartTime", true);
                        }else{
                            map.put("质检员", moreOrgNameList.get(i).getQualityInspector());
                            map.put("质检员_isPartTime", false);
                        }


                        if(moreOrgNameList.get(i).getChiefEngineer().equals("兼职")){
                            ProDeptRoleBean beans = new ProDeptRoleBean();
                            beans.setOrgId(moreOrgNameList.get(i).getOrgId());
                            beans.setDeptRoleId(4L);
                            List<ProDeptRoleBean> chiefEngineerList = proDeptRoleService.getMoreOrgData(beans);
                            String chiefEngineer = "";
                            if(!chiefEngineerList.isEmpty()){
                                for (int j = 0; j < chiefEngineerList.size(); j++){
                                    chiefEngineer = chiefEngineer + "," + chiefEngineerList.get(j).getUserName();
                                }
                            }
                            map.put("项目总工", chiefEngineer);
                            map.put("项目总工_isPartTime", true);
                        }else{
                            map.put("项目总工", moreOrgNameList.get(i).getChiefEngineer());
                            map.put("项目总工_isPartTime", false);
                        }

                        if(moreOrgNameList.get(i).getMechanicalStaff().equals("兼职")){
                            ProDeptRoleBean beans = new ProDeptRoleBean();
                            beans.setOrgId(moreOrgNameList.get(i).getOrgId());
                            beans.setDeptRoleId(5L);
                            List<ProDeptRoleBean> mechanicalStaffList = proDeptRoleService.getMoreOrgData(beans);
                            String mechanicalStaff = "";
                            if(!mechanicalStaffList.isEmpty()){
                                for (int j = 0; j < mechanicalStaffList.size(); j++){
                                    mechanicalStaff = mechanicalStaff + "," + mechanicalStaffList.get(j).getUserName();
                                }
                            }
                            map.put("机械员", mechanicalStaff);
                            map.put("机械员_isPartTime", true);
                        }else{
                            map.put("机械员", moreOrgNameList.get(i).getMechanicalStaff());
                            map.put("机械员_isPartTime", false);
                        }
//                        map.put("项目总工", moreOrgNameList.get(i).getChiefEngineer());
//                        map.put("机械员", moreOrgNameList.get(i).getMechanicalStaff());
                        if(moreOrgNameList.get(i).getDocumentStaff().equals("兼职")){
                            ProDeptRoleBean beans = new ProDeptRoleBean();
                            beans.setOrgId(moreOrgNameList.get(i).getOrgId());
                            beans.setDeptRoleId(6L);
                            List<ProDeptRoleBean> documentStaffList = proDeptRoleService.getMoreOrgData(beans);
                            String documentStaff = "";
                            if(!documentStaffList.isEmpty()){
                                for (int j = 0; j < documentStaffList.size(); j++){
                                    documentStaff = documentStaff + "," + documentStaffList.get(j).getUserName();
                                }
                            }
                            map.put("资料员", documentStaff);
                            map.put("资料员_isPartTime", true);
                        }else {
                            map.put("资料员", moreOrgNameList.get(i).getDocumentStaff());
                            map.put("资料员_isPartTime", false);
                        }

//                        map.put("资料员", moreOrgNameList.get(i).getDocumentStaff());
                        if(moreOrgNameList.get(i).getConstructionStaff().equals("兼职")){
                            ProDeptRoleBean beans = new ProDeptRoleBean();
                            beans.setOrgId(moreOrgNameList.get(i).getOrgId());
                            beans.setDeptRoleId(7L);
                            List<ProDeptRoleBean> constructionStaffList = proDeptRoleService.getMoreOrgData(beans);
                            String constructionStaff = "";
                           if(!constructionStaffList.isEmpty()){
                               for (int j = 0; j < constructionStaffList.size(); j++){
                                   constructionStaff = constructionStaff + "," + constructionStaffList.get(j).getUserName();
                               }
                           }
                           map.put("施工员", constructionStaff);
                           map.put("施工员_isPartTime", true);
                        }else {
                            map.put("施工员", moreOrgNameList.get(i).getConstructionStaff());
                            map.put("施工员_isPartTime", false);
                        }
//                        map.put("施工员", moreOrgNameList.get(i).getConstructionStaff());
                        if(moreOrgNameList.get(i).getMaterialStaff().equals("兼职")){
                            ProDeptRoleBean beans = new ProDeptRoleBean();
                            beans.setOrgId(moreOrgNameList.get(i).getOrgId());
                            beans.setDeptRoleId(8L);
                            List<ProDeptRoleBean> materialStaffList = proDeptRoleService.getMoreOrgData(beans);
                            String materialStaff = "";
                           if(!materialStaffList.isEmpty()){
                               for (int j = 0; j < materialStaffList.size(); j++){
                                   materialStaff = materialStaff + "," + materialStaffList.get(j).getUserName();
                               }
                           }
                           map.put("材料员", materialStaff);
                           map.put("材料员_isPartTime", true);
                        }else {
                            map.put("材料员", moreOrgNameList.get(i).getMaterialStaff());
                            map.put("材料员_isPartTime", false);
                        }

//                        map.put("材料员", moreOrgNameList.get(i).getMaterialStaff());
                        if(moreOrgNameList.get(i).getOther().equals("兼职")){
                            ProDeptRoleBean beans = new ProDeptRoleBean();
                            beans.setOrgId(moreOrgNameList.get(i).getOrgId());
                            beans.setDeptRoleId(9L);
                            List<ProDeptRoleBean> otherList = proDeptRoleService.getMoreOrgData(beans);
                            String other = "";
                            if(!otherList.isEmpty()){
                                for (int j = 0; j < otherList.size(); j++){
                                    other = other + "," + otherList.get(j).getUserName();
                                }
                            }
                            map.put("其他", other);
                            map.put("其他_isPartTime", true);
                        }else {
                            map.put("其他", moreOrgNameList.get(i).getOther());
                            map.put("其他_isPartTime", false);
                        }
                        departmentData3.add(map);
                    }
                }
                exporter.addDataRows(departmentSheet3, departmentData3, departmentHeaders3);

                // 获取工作簿对象
                Workbook workbook = getWorkbookFromSheet(departmentSheet3); // 假设这里有一个方法可以获取Workbook对象
                // 设置单元格样式
                setCellStyle(workbook, departmentSheet3, departmentHeaders3, departmentData3);
            }
            exporter.exportToResponse(response, "八大员统计报表");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private Workbook getWorkbookFromSheet(Sheet sheet) {
        // 这里假设 Sheet 对象有获取其所属 Workbook 的方法
        return sheet.getWorkbook();
    }

    private void setCellStyle(Workbook workbook, Sheet sheet, List<String> headers, List<Map<String, Object>> data) {
        for (int i = 2; i <= data.size(); i++) { // 从1开始，跳过表头
            Row row = sheet.getRow(i);
            if (row == null) {
                continue; // 如果当前行为空，跳过
            }
            for (int j = 0; j < headers.size(); j++) {
                Cell cell = row.getCell(j);
                if (cell != null) {
                    CellStyle style = workbook.createCellStyle();
                    Font font = workbook.createFont();

                    // 启用文本自动换行
                    style.setWrapText(true);

                    // 检查是否需要设置为红色字体
                    String headerName = headers.get(j);
                    Boolean isPartTime = (Boolean) data.get(i - 1).get(headerName + "_isPartTime");
                    if (Boolean.TRUE.equals(isPartTime)) {
                        font.setColor(IndexedColors.RED.getIndex()); // 设置字体颜色为红色
                    } else {
                        font.setColor(IndexedColors.BLACK.getIndex()); // 设置字体颜色为黑色
                    }

                    // 应用字体到样式
                    style.setFont(font);

                    // 应用样式到单元格
                    cell.setCellStyle(style);
                }
            }
        }
    }

}
