package com.ruoyi.web.controller.oa;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.file.domain.FilesAchievement;
import com.ruoyi.file.service.IFilesAchievementService;
import com.ruoyi.oa.domain.*;
import com.ruoyi.oa.service.*;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.qyweixin.MessageController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * cmc项目Controller
 * 
 * @author cmc
 * @date 2024-01-30
 */
@RestController
@RequestMapping("/oa/project")
public class CmcProjectController extends BaseController {
    @Autowired
    private ICmcProjectService cmcProjectService;

    @Autowired
    private ICmcPartyAService cmcPartyAService;

    @Autowired
    private ICmcProjectWorkService cmcProjectWorkService;

    @Autowired
    private ICmcProjectContractService cmcProjectContractService;

    @Autowired
    private ICmcContractService cmcContractService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ICmcManageDeptService cmcManageDeptService;

    @Autowired
    private ICmcArchiveService cmcArchiveService;

    @Autowired
    private ICmcSettleService cmcSettleService;

    @Autowired
    private ICmcCheckService cmcCheckService;

    @Autowired
    private IFilesAchievementService filesAchievementService;

    /**
     * 查询cmc项目列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CmcProject cmcProject) {
        startPage();
        List<CmcProject> list = new ArrayList<>();
        if (cmcProject.getUndertakingDept() != null && cmcProject.getUndertakingDept().equals("113"))
            list = cmcProjectService.selectCmcInvestProjectList(cmcProject);
        else
            list = cmcProjectService.selectCmcProjectList(cmcProject);
        for (CmcProject project : list) {
            project.setUndertakingDeptName(deptIdToName(project));
            inspectorIdToName(project);
            CmcContract contract = joinContract(project);
            project.setContractCode(contract.getContractCode());
            project.setContractNumber(contract.getContractNumber());
            project.setContractName(contract.getContractName());
        }
        return getDataTable(list);
    }

    /**
     * 模糊查询cmc项目列表
     */
    @GetMapping("/listFuzzy")
    public TableDataInfo listFuzzy(CmcProject cmcProject) {
        startPage();
        List<CmcProject> list = cmcProjectService.selectCmcProjectListFuzzy(cmcProject);
        for (CmcProject project : list) {
            project.setUndertakingDeptName(deptIdToName(project));
            inspectorIdToName(project);
            CmcContract contract = joinContract(project);
            project.setContractCode(contract.getContractCode());
            project.setContractNumber(contract.getContractNumber());
            project.setContractName(contract.getContractName());
        }
        return getDataTable(list);
    }

    /**
     * 导出cmc项目列表
     */
    @Log(title = "cmc项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmcProject cmcProject) {
        List<CmcProject> list = new ArrayList<>();
        if (cmcProject.getUndertakingDept() != null && cmcProject.getUndertakingDept().equals("113"))
            list = cmcProjectService.selectCmcInvestProjectList(cmcProject);
        else {
            if (cmcProject.getQueryString() != null && !cmcProject.getQueryString().equals(""))
                list = cmcProjectService.selectCmcProjectListFuzzy(cmcProject);
            else
                list = cmcProjectService.selectCmcProjectList(cmcProject);
        }
        for (CmcProject project : list) {
            project.setUndertakingDeptName(deptIdToName(project));
            inspectorIdToName(project);
            CmcContract contract = joinContract(project);
            project.setContractCode(contract.getContractCode());
            project.setContractNumber(contract.getContractNumber());
            project.setContractName(contract.getContractName());
        }
        ExcelUtil<CmcProject> util = new ExcelUtil<CmcProject>(CmcProject.class);
        util.exportExcel(response, list, "cmc项目数据");
    }

    /**
     * 获取cmc项目详细信息
     */
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable("projectId") String projectId) {
        CmcProject cmcProject = cmcProjectService.selectCmcProjectByProjectId(projectId);
        if (cmcProject != null) {
            cmcProject.setUndertakingDeptName(deptIdToName(cmcProject));
            inspectorIdToName(cmcProject);
            CmcContract contract = joinContract(cmcProject);
            cmcProject.setContractCode(contract.getContractCode());
            cmcProject.setContractNumber(contract.getContractNumber());
            cmcProject.setContractName(contract.getContractName());
        }
        return success(cmcProject);
    }

    /**
     * 查询cmc项目列表
     */
    @GetMapping("/listByPaticipates")
    public TableDataInfo getListByPaticipates(CmcProject cmcProject) {
        startPage();
        List<CmcProject> list = cmcProjectService.selectListByPaticipates(cmcProject);
        return getDataTable(list);
    }

    /**
     * 项目自动编号
     */
    @GetMapping("/projectNumber")
    public AjaxResult getProjectNumberByYear(CmcProject cmcProject) {
        List<CmcProject> list = cmcProjectService.selectCmcAllProjectList(cmcProject);
        String number = "0";
        String projectNumber = "";
        if (list.size() > 0)
            number = list.get(0).getProjectNumber().substring(5);
        if (Integer.parseInt(number) < 9)
            projectNumber = cmcProject.getProjectNumber() + "0" + (Integer.parseInt(number) + 1);
        else
            projectNumber = cmcProject.getProjectNumber() + (Integer.parseInt(number) + 1);
        return success(projectNumber);
    }

    /**
     * 项目类型列表
     */
    @GetMapping("/projectType")
    public AjaxResult getProjectType() {
        List<String> typeList = new ArrayList<>();
        Map<Object, List<CmcProject>> projectType = cmcProjectService.selectCmcAllProjectList(new CmcProject()).stream()
                .collect(Collectors.groupingBy(item -> Optional.ofNullable(item.getProjectType())));
        projectType.forEach((k, v) -> {
            if (k != Optional.empty())
                typeList.add(k.toString().substring(k.toString().indexOf("[") + 1, k.toString().indexOf("]")));
        });
        Collections.sort(typeList);
        return success(typeList);
    }

    /**
     * 获取cmc项目统计信息
     */
    @GetMapping("/statistic")
    public AjaxResult getProjectStatistic(CmcProject cmcProject) throws ParseException {
        JSONObject jsonObject = new JSONObject();
        JSONArray yearArray = new JSONArray();
        JSONObject yearObject = new JSONObject();
        JSONArray monthArray = new JSONArray();
        JSONObject monthObject = new JSONObject();
        JSONArray monthCompleteArray = new JSONArray();
        JSONObject monthCompleteObject = new JSONObject();
        JSONArray monthArchiveArray = new JSONArray();
        JSONObject monthArchiveObject = new JSONObject();
        JSONArray monthSettleArray = new JSONArray();
        JSONObject monthSettleObject = new JSONObject();
        JSONArray monthCheckArray = new JSONArray();
        JSONObject monthCheckObject = new JSONObject();
        JSONArray sourceArray = new JSONArray();
        JSONObject sourceObject = new JSONObject();
        JSONArray typeArray = new JSONArray();
        JSONObject typeObject = new JSONObject();
        JSONArray deptArray = new JSONArray();
        JSONObject deptObject = new JSONObject();
        JSONArray completeArray = new JSONArray();
        JSONObject completeObject = new JSONObject();
        JSONArray archiveArray = new JSONArray();
        JSONObject archiveObject = new JSONObject();
        JSONArray settleArray = new JSONArray();
        JSONObject settleObject = new JSONObject();
        JSONArray checkArray = new JSONArray();
        JSONObject checkObject = new JSONObject();
        String beginTime = "";
        String endTime = "";
        // 整体
        if (cmcProject.getProjectNumber() == null) {
            // 每年项目数量
            if (cmcProject.getParams().size() == 0) {
                for (int i = 2019; i <= Calendar.getInstance().get(Calendar.YEAR); i++) {
                    // 总数
                    cmcProject.setProjectNumber(String.valueOf(i));
                    List<CmcProject> yearList = cmcProjectService.selectCmcAllProjectList(cmcProject);
                    yearObject.put(String.valueOf(i), yearList.size());
                    // 已完成
                    cmcProject.setIsComplete("1");
                    List<CmcProject> completeList = cmcProjectService.selectCmcAllProjectList(cmcProject);
                    completeObject.put(cmcProject.getProjectNumber(), completeList.size());
                    cmcProject.setIsComplete(null);
                    // 获取当年登记的项目ID列表
                    List<String> yearProjectIds = yearList.stream()
                            .map(p -> p.getProjectId())
                            .filter(id -> id != null)
                            .collect(Collectors.toList());

                    // 已归档 - 统计当年登记的项目中有多少已归档
                    List<String> yearArchiveProjectIds = new ArrayList<>();
                    CmcArchive cmcArchive = new CmcArchive();
                    cmcArchive.setProjectNumber(String.valueOf(i));
                    cmcArchive.setArchiveTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
                    List<CmcArchive> archiveList = cmcArchiveService.selectCmcArchiveList(cmcArchive);
                    for (CmcArchive archive : archiveList) {
                        if (yearProjectIds.contains(archive.getProjectId())) {
                            yearArchiveProjectIds.add(archive.getProjectId());
                        }
                    }
                    FilesAchievement filesAchievement = new FilesAchievement();
                    filesAchievement.setProjectNumber(String.valueOf(i));
                    List<FilesAchievement> achievementList = filesAchievementService
                            .selectProjectAchievementList(filesAchievement);
                    for (FilesAchievement achievement : achievementList) {
                        if (achievement.getProjectId() != null && yearProjectIds.contains(achievement.getProjectId())) {
                            yearArchiveProjectIds.add(achievement.getProjectId());
                        }
                    }
                    archiveObject.put(String.valueOf(i), yearArchiveProjectIds.stream().distinct().count());

                    // 已结算 - 统计当年登记的项目中有多少已结算
                    CmcSettle cmcSettle = new CmcSettle();
                    cmcSettle.setProjectNumber(String.valueOf(i));
                    cmcSettle.setGmTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
                    List<CmcSettle> settleList = cmcSettleService.selectCmcSettleList(cmcSettle);
                    long yearSettleCount = settleList.stream()
                            .filter(s -> s.getProjectId() != null && yearProjectIds.contains(s.getProjectId()))
                            .count();
                    settleObject.put(String.valueOf(i), yearSettleCount);

                    // 已核算 - 统计当年登记的项目中有多少已核算
                    CmcCheck cmcCheck = new CmcCheck();
                    cmcCheck.setProjectNumber(String.valueOf(i));
                    cmcCheck.setCheckTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
                    List<CmcCheck> checkList = cmcCheckService.selectCmcCheckList(cmcCheck);
                    long yearCheckCount = checkList.stream()
                            .filter(c -> c.getProjectId() != null && yearProjectIds.contains(c.getProjectId()))
                            .count();
                    checkObject.put(String.valueOf(i), yearCheckCount);
                }
                cmcProject.setProjectNumber(null);
            } else {
                beginTime = (String) cmcProject.getParams().get("beginTime");
                endTime = (String) cmcProject.getParams().get("endTime");
                List<String> monthList = DateUtils.getMonthBetweenDate(beginTime, endTime);
                for (int i = 0; i < monthList.size(); i++) {
                    String beginTimeString = monthList.get(i) + "-01";
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.YEAR, Integer.parseInt(monthList.get(i).split("-")[0]));
                    calendar.set(Calendar.MONTH, Integer.parseInt(monthList.get(i).split("-")[1]) - 1);
                    calendar.set(Calendar.DAY_OF_MONTH, 1);
                    String endTimeString = monthList.get(i) + "-" + calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                    Map<String, Object> params = new HashMap<>();
                    params.put("beginTime", beginTimeString + " 00:00:00");
                    params.put("endTime", endTimeString + " 23:59:59");
                    cmcProject.setParams(params);
                    List<CmcProject> monthProjectList = cmcProjectService.selectCmcProjectListByRange(cmcProject);
                    monthObject.put(monthList.get(i), monthProjectList.size());

                    // 已完成
                    cmcProject.setIsComplete("1");
                    List<CmcProject> monthCompleteList = cmcProjectService.selectCmcProjectListByRange(cmcProject);
                    monthCompleteObject.put(monthList.get(i), monthCompleteList.size());
                    cmcProject.setIsComplete(null);

                    // 获取当月登记的项目ID列表
                    List<String> monthProjectIds = monthProjectList.stream()
                            .map(p -> p.getProjectId())
                            .filter(id -> id != null)
                            .collect(Collectors.toList());

                    // 已归档 - 统计当月登记的项目中有多少已归档
                    List<String> monthArchiveProjectIds = new ArrayList<>();
                    CmcArchive monthCmcArchive = new CmcArchive();
                    monthCmcArchive.setArchiveTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
                    List<CmcArchive> monthArchiveList = cmcArchiveService.selectCmcArchiveList(monthCmcArchive);
                    for (CmcArchive archive : monthArchiveList) {
                        if (monthProjectIds.contains(archive.getProjectId())) {
                            monthArchiveProjectIds.add(archive.getProjectId());
                        }
                    }
                    FilesAchievement monthFilesAchievement = new FilesAchievement();
                    List<FilesAchievement> monthAchievementList = filesAchievementService
                            .selectProjectAchievementList(monthFilesAchievement);
                    for (FilesAchievement achievement : monthAchievementList) {
                        if (achievement.getProjectId() != null
                                && monthProjectIds.contains(achievement.getProjectId())) {
                            monthArchiveProjectIds.add(achievement.getProjectId());
                        }
                    }
                    monthArchiveObject.put(monthList.get(i), monthArchiveProjectIds.stream().distinct().count());

                    // 已结算 - 统计当月登记的项目中有多少已结算
                    CmcSettle monthCmcSettle = new CmcSettle();
                    monthCmcSettle.setProjectNumber(cmcProject.getProjectNumber());
                    monthCmcSettle.setGmTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
                    List<CmcSettle> monthSettleList = cmcSettleService.selectCmcSettleList(monthCmcSettle);
                    long monthSettleCount = monthSettleList.stream()
                            .filter(s -> s.getProjectId() != null && monthProjectIds.contains(s.getProjectId()))
                            .count();
                    monthSettleObject.put(monthList.get(i), monthSettleCount);

                    // 已核算 - 统计当月登记的项目中有多少已核算
                    CmcCheck monthCmcCheck = new CmcCheck();
                    monthCmcCheck.setCheckTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
                    List<CmcCheck> monthCheckList = cmcCheckService.selectCmcCheckList(monthCmcCheck);
                    long monthCheckCount = monthCheckList.stream()
                            .filter(c -> c.getProjectId() != null && monthProjectIds.contains(c.getProjectId()))
                            .count();
                    monthCheckObject.put(monthList.get(i), monthCheckCount);
                }
            }

        }
        // 年度
        else {
            // 输入年份项目数量
            List<CmcProject> yearList = cmcProjectService.selectCmcAllProjectList(cmcProject);
            // 总数
            yearObject.put(cmcProject.getProjectNumber(), yearList.size());
            // 按月份统计
            for (int i = 1; i <= 12; i++) {
                String month = i < 10 ? "0" + i : String.valueOf(i);
                String beginTimeString = cmcProject.getProjectNumber() + "-" + month + "-01";
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, Integer.parseInt(cmcProject.getProjectNumber()));
                calendar.set(Calendar.MONTH, i - 1);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                String endTimeString = cmcProject.getProjectNumber() + "-" + month + "-"
                        + calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                String monthKey = cmcProject.getProjectNumber() + "-" + month;

                // 总数
                Map<String, Object> params = new HashMap<>();
                params.put("beginTime", beginTimeString + " 00:00:00");
                params.put("endTime", endTimeString + " 23:59:59");
                cmcProject.setParams(params);
                List<CmcProject> monthProjectList = cmcProjectService.selectCmcProjectListByRange(cmcProject);
                monthObject.put(monthKey, monthProjectList.size());

                // 已完成
                cmcProject.setIsComplete("1");
                List<CmcProject> monthCompleteList = cmcProjectService.selectCmcProjectListByRange(cmcProject);
                monthCompleteObject.put(monthKey, monthCompleteList.size());
                cmcProject.setIsComplete(null);

                // 获取当月登记的项目ID列表
                List<String> monthProjectIds = monthProjectList.stream()
                        .map(p -> p.getProjectId())
                        .filter(id -> id != null)
                        .collect(Collectors.toList());

                // 已归档 - 统计当月登记的项目中有多少已归档
                List<String> monthArchiveProjectIds = new ArrayList<>();
                CmcArchive monthCmcArchive = new CmcArchive();
                monthCmcArchive.setProjectNumber(cmcProject.getProjectNumber());
                monthCmcArchive.setArchiveTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
                List<CmcArchive> monthArchiveList = cmcArchiveService.selectCmcArchiveList(monthCmcArchive);
                for (CmcArchive archive : monthArchiveList) {
                    if (monthProjectIds.contains(archive.getProjectId())) {
                        monthArchiveProjectIds.add(archive.getProjectId());
                    }
                }
                FilesAchievement monthFilesAchievement = new FilesAchievement();
                monthFilesAchievement.setProjectNumber(cmcProject.getProjectNumber());
                List<FilesAchievement> monthAchievementList = filesAchievementService
                        .selectProjectAchievementList(monthFilesAchievement);
                for (FilesAchievement achievement : monthAchievementList) {
                    if (achievement.getProjectId() != null && monthProjectIds.contains(achievement.getProjectId())) {
                        monthArchiveProjectIds.add(achievement.getProjectId());
                    }
                }
                monthArchiveObject.put(monthKey, monthArchiveProjectIds.stream().distinct().count());

                // 已结算 - 统计当月登记的项目中有多少已结算
                CmcSettle monthCmcSettle = new CmcSettle();
                monthCmcSettle.setProjectNumber(cmcProject.getProjectNumber());
                monthCmcSettle.setGmTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
                List<CmcSettle> monthSettleList = cmcSettleService.selectCmcSettleList(monthCmcSettle);
                long monthSettleCount = monthSettleList.stream()
                        .filter(s -> s.getProjectId() != null && monthProjectIds.contains(s.getProjectId()))
                        .count();
                monthSettleObject.put(monthKey, monthSettleCount);

                // 已核算 - 统计当月登记的项目中有多少已核算
                CmcCheck monthCmcCheck = new CmcCheck();
                monthCmcCheck.setProjectNumber(cmcProject.getProjectNumber());
                monthCmcCheck.setCheckTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
                List<CmcCheck> monthCheckList = cmcCheckService.selectCmcCheckList(monthCmcCheck);
                long monthCheckCount = monthCheckList.stream()
                        .filter(c -> c.getProjectId() != null && monthProjectIds.contains(c.getProjectId()))
                        .count();
                monthCheckObject.put(monthKey, monthCheckCount);
            }
            // 已完成
            cmcProject.setIsComplete("1");
            List<CmcProject> completeList = cmcProjectService.selectCmcAllProjectList(cmcProject);
            completeObject.put(cmcProject.getProjectNumber(), completeList.size());
            cmcProject.setIsComplete(null);

            // 获取当年登记的项目ID列表
            List<CmcProject> yearProjectList = cmcProjectService.selectCmcAllProjectList(cmcProject);
            List<String> yearProjectIds = yearProjectList.stream()
                    .map(p -> p.getProjectId())
                    .filter(id -> id != null)
                    .collect(Collectors.toList());

            // 已归档 - 统计当年登记的项目中有多少已归档
            List<String> yearArchiveProjectIds = new ArrayList<>();
            CmcArchive cmcArchive = new CmcArchive();
            cmcArchive.setProjectNumber(cmcProject.getProjectNumber());
            cmcArchive.setArchiveTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
            List<CmcArchive> archiveList = cmcArchiveService.selectCmcArchiveList(cmcArchive);
            for (CmcArchive archive : archiveList) {
                if (yearProjectIds.contains(archive.getProjectId())) {
                    yearArchiveProjectIds.add(archive.getProjectId());
                }
            }
            FilesAchievement filesAchievement = new FilesAchievement();
            filesAchievement.setProjectNumber(cmcProject.getProjectNumber());
            List<FilesAchievement> achievementList = filesAchievementService
                    .selectProjectAchievementList(filesAchievement);
            for (FilesAchievement achievement : achievementList) {
                if (achievement.getProjectId() != null && yearProjectIds.contains(achievement.getProjectId())) {
                    yearArchiveProjectIds.add(achievement.getProjectId());
                }
            }
            archiveObject.put(cmcProject.getProjectNumber(), yearArchiveProjectIds.stream().distinct().count());

            // 已结算 - 统计当年登记的项目中有多少已结算
            CmcSettle cmcSettle = new CmcSettle();
            cmcSettle.setProjectNumber(cmcProject.getProjectNumber());
            cmcSettle.setGmTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
            List<CmcSettle> settleList = cmcSettleService.selectCmcSettleList(cmcSettle);
            long yearSettleCount = settleList.stream()
                    .filter(s -> s.getProjectId() != null && yearProjectIds.contains(s.getProjectId()))
                    .count();
            settleObject.put(cmcProject.getProjectNumber(), yearSettleCount);

            // 已核算 - 统计当年登记的项目中有多少已核算
            CmcCheck cmcCheck = new CmcCheck();
            cmcCheck.setProjectNumber(cmcProject.getProjectNumber());
            cmcCheck.setCheckTime(new SimpleDateFormat("yyyy").parse("2000-01-01"));
            List<CmcCheck> checkList = cmcCheckService.selectCmcCheckList(cmcCheck);
            long yearCheckCount = checkList.stream()
                    .filter(c -> c.getProjectId() != null && yearProjectIds.contains(c.getProjectId()))
                    .count();
            checkObject.put(cmcProject.getProjectNumber(), yearCheckCount);

        }
        if (!endTime.equals("")) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, Integer.parseInt(endTime.split("-")[0]));
            calendar.set(Calendar.MONTH, Integer.parseInt(endTime.split("-")[1]) - 1);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            endTime = endTime.split("-")[0] + "-" + endTime.split("-")[1] + "-"
                    + calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        getProjectSourceStatistic(cmcProject, sourceObject, beginTime, endTime);
        getProjectTypeStatistic(cmcProject, typeObject, beginTime, endTime);
        getProjectDeptStatistic(cmcProject, deptObject, beginTime, endTime);
        yearArray.add(yearObject);
        monthArray.add(monthObject);
        monthCompleteArray.add(monthCompleteObject);
        monthArchiveArray.add(monthArchiveObject);
        monthSettleArray.add(monthSettleObject);
        monthCheckArray.add(monthCheckObject);
        sourceArray.add(sourceObject);
        deptArray.add(deptObject);
        typeArray.add(typeObject);
        completeArray.add(completeObject);
        archiveArray.add(archiveObject);
        settleArray.add(settleObject);
        checkArray.add(checkObject);
        jsonObject.put("year", yearArray);
        jsonObject.put("month", monthArray);
        jsonObject.put("monthComplete", monthCompleteArray);
        jsonObject.put("monthArchive", monthArchiveArray);
        jsonObject.put("monthSettle", monthSettleArray);
        jsonObject.put("monthCheck", monthCheckArray);
        jsonObject.put("source", sourceArray);
        jsonObject.put("dept", deptArray);
        jsonObject.put("type", typeArray);
        jsonObject.put("complete", completeArray);
        jsonObject.put("archive", archiveArray);
        jsonObject.put("settle", settleArray);
        jsonObject.put("check", checkArray);
        return success(jsonObject);
    }

    /**
     * 新增cmc项目
     */
    @Log(title = "cmc项目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmcProject cmcProject) throws IOException {
        cmcProject.setRegisterTime(new Date());
        cmcProject.setIsFinished("0");
        if (cmcProject.getUndertakingDept().contains(",")) {
            cmcProject.setLeadDept(cmcProject.getUndertakingDept().substring(0, 3));
            cmcProject.setJoinDept(cmcProject.getUndertakingDept().substring(4));
        } else
            cmcProject.setLeadDept(cmcProject.getUndertakingDept());
        return toAjax(cmcProjectService.insertCmcProject(cmcProject));
    }

    /**
     * 修改cmc项目
     */
    @Log(title = "cmc项目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmcProject cmcProject) {
        if (cmcProject.getProjectLeader() != null) {
            SysUser user = userService.selectUserById(cmcProject.getProjectLeader());
            List<SysRole> sysRoleList = user.getRoles();
            Long[] roles = new Long[sysRoleList.size()];
            boolean isProjectLeader = false;
            for (int i = 0; i < sysRoleList.size(); i++) {
                roles[i] = sysRoleList.get(i).getRoleId();
                if (sysRoleList.get(i).getRoleId() == 15L) {
                    isProjectLeader = true;
                }
            }
            // 新增项目负责人角色
            if (!isProjectLeader) {
                Long[] newRoles = new Long[roles.length + 1];
                System.arraycopy(roles, 0, newRoles, 0, roles.length);
                newRoles[newRoles.length - 1] = 15L;
                userService.insertUserAuth(user.getUserId(), newRoles);
            }
        }
        return toAjax(cmcProjectService.updateCmcProject(cmcProject));
    }

    /**
     * 登记项目发送企业微信消息
     */
    @PostMapping("/sendMessage")
    public AjaxResult sendMessage(@RequestBody CmcProject cmcProject) throws IOException {
        String message = "经营发展部已发起项目登记：  \n>" +
                "登记人： <font color='info'>" + userService.selectUserById(cmcProject.getProjectRegistrant()).getNickName()
                + "</font>  \n>" +
                "项目编号：" + cmcProject.getProjectNumber() + "  \n>" +
                "项目名称：" + cmcProject.getProjectName() + "  \n>" +
                "  \n>" +
                "项目类型：<font color='comment'>" + cmcProject.getProjectType() + "</font>  \n>" +
                "项目来源：" + (cmcProject.getProjectSource().equals("0") ? "院内" : "院外") + "  \n>" +
                "甲方单位：" + cmcPartyAService.selectCmcPartyAByPartyAId(cmcProject.getPartyAId()).getPartyAName() + "  \n>"
                +
                "  \n>" +
                "承担部门：<font color='warning'>" + deptIdToName(cmcProject) + "</font>  \n>" +
                "请您确认承担部门，及时跟进项目流转  \n>" +
                "  \n>";
        if (cmcProject.getUndertakingDept() != null) {
            String deptString = cmcProject.getUndertakingDept() + ",105";
            List<String> managerList = new ArrayList<>();
            managerList.add("WangRongHua");
            managerList.add("YuSiHan");
            String[] deptId = deptString.split(",");
            for (String dept : deptId) {
                List<SysUser> manageList = getManageId(dept, "");
                for (SysUser manager : manageList) {
                    managerList.add(manager.getPinyin());

                }
            }
            MessageController.sendAppMessage(message, StringUtils.join(managerList, "|"));
        }
        return success();
    }

    /**
     * 删除cmc项目
     */
    @Log(title = "cmc项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{projectIds}")
    public AjaxResult remove(@PathVariable String[] projectIds) {
        cmcProjectWorkService.deleteCmcProjectWorkByProjectIds(projectIds);
        return success(cmcProjectService.deleteCmcProjectByProjectIds(projectIds));
    }

    public String deptIdToName(CmcProject cmcProject) {
        String underTakingDept = cmcProject.getUndertakingDept();
        String undertakingDeptName = cmcProject.getUndertakingDeptName();
        StringBuilder underTakingDeptNames = new StringBuilder();
        if (underTakingDept != null && !underTakingDept.equals("")
                && (undertakingDeptName == null || undertakingDeptName.equals(""))) {
            for (String dept : underTakingDept.split(","))
                underTakingDeptNames.append(deptService.selectDeptById(Long.parseLong(dept)).getDeptName()).append(",");
            cmcProject.setUndertakingDeptName(underTakingDeptNames.substring(0, underTakingDeptNames.length() - 1));
        }
        return cmcProject.getUndertakingDeptName();
    }

    public void inspectorIdToName(CmcProject cmcProject) {
        String qualityInspector = cmcProject.getQualityInspector();
        String qualityInspectorName = cmcProject.getQualityInspectorName();
        StringBuilder qualityInspectorNames = new StringBuilder();
        if (qualityInspector != null && !qualityInspector.equals("")
                && (qualityInspectorName == null || qualityInspectorName.equals(""))) {
            for (String inspector : qualityInspector.split(","))
                qualityInspectorNames.append(userService.selectUserById(Long.parseLong(inspector)).getNickName())
                        .append(",");
            cmcProject.setQualityInspectorName(qualityInspectorNames.substring(0, qualityInspectorNames.length() - 1));
        }
    }

    public CmcContract joinContract(CmcProject cmcProject) {
        CmcContract contract = new CmcContract();
        CmcProjectContract cmcProjectContract = new CmcProjectContract();
        cmcProjectContract.setProjectId(cmcProject.getProjectId());
        List<CmcProjectContract> cmcProjectContractList = cmcProjectContractService
                .selectCmcProjectContractList(cmcProjectContract);
        cmcProjectContractList.forEach(projectContract -> {
            try {
                CmcContract cmcContract = cmcContractService
                        .selectCmcContractByContractId(projectContract.getContractId());
                if (contract.getContractCode() != null)
                    contract.setContractCode(contract.getContractCode() + "、" + cmcContract.getContractCode());
                else
                    contract.setContractCode(cmcContract.getContractCode());
                if (contract.getContractNumber() != null)
                    contract.setContractNumber(contract.getContractNumber() + "、" + cmcContract.getContractNumber());
                else
                    contract.setContractNumber(cmcContract.getContractNumber());
                if (contract.getContractName() != null)
                    contract.setContractName(contract.getContractName() + "、" + cmcContract.getContractName());
                else
                    contract.setContractName(cmcContract.getContractName());
            } catch (Exception e) {
                System.out.println(cmcProjectContractList);
            }
        });
        return contract;
    }

    public List<SysUser> getManageId(String deptId, String partyAId) {
        List<SysUser> userList = new ArrayList<>();
        CmcManageDept cmcManageDept = new CmcManageDept();
        cmcManageDept.setDeptId(deptId);
        cmcManageDept.setPartyAId(partyAId);
        for (CmcManageDept manageDept : cmcManageDeptService.selectCmcManageDeptList(cmcManageDept)) {
            userList.add(userService.selectUserById(manageDept.getUserId()));
        }
        return userList;
    }

    // 院内外项目数量
    public void getProjectSourceStatistic(CmcProject cmcProject, JSONObject sourceObject, String beginTime,
            String endTime) {
        cmcProject.setProjectSource("1");
        if (beginTime.equals("")) {
            sourceObject.put("院外", cmcProjectService.selectCmcAllProjectList(cmcProject).size());
        } else {
            Map<String, Object> params = new HashMap<>();
            params.put("beginTime", beginTime + " 00:00:00");
            params.put("endTime", endTime + " 23:59:59");
            cmcProject.setParams(params);
            sourceObject.put("院外", cmcProjectService.selectCmcProjectListByRange(cmcProject).size());
        }
        cmcProject.setProjectSource("0");
        if (beginTime.equals("")) {
            sourceObject.put("院内", cmcProjectService.selectCmcAllProjectList(cmcProject).size());
        } else {
            Map<String, Object> params = new HashMap<>();
            params.put("beginTime", beginTime + " 00:00:00");
            params.put("endTime", endTime + " 23:59:59");
            cmcProject.setParams(params);
            sourceObject.put("院内", cmcProjectService.selectCmcProjectListByRange(cmcProject).size());
        }
        cmcProject.setProjectSource(null);
    }

    // 各类型项目数量
    public void getProjectTypeStatistic(CmcProject cmcProject, JSONObject typeObject, String beginTime,
            String endTime) {
        List<CmcProject> projectList;
        if (beginTime.equals("")) {
            projectList = cmcProjectService.selectCmcAllProjectList(cmcProject);
        } else {
            Map<String, Object> params = new HashMap<>();
            params.put("beginTime", beginTime + " 00:00:00");
            params.put("endTime", endTime + " 23:59:59");
            cmcProject.setParams(params);
            projectList = cmcProjectService.selectCmcProjectListByRange(cmcProject);
        }
        Map<Object, Long> typeGroup = projectList.stream().collect(
                Collectors.groupingBy(item -> Optional.ofNullable(item.getProjectType()), Collectors.counting()));
        List<Map.Entry<Object, Long>> typeList = new ArrayList<>(typeGroup.entrySet());
        typeList.sort(Map.Entry.comparingByValue());
        typeList.forEach((item) -> {
            if (item.getKey() != Optional.empty())
                typeObject.put(
                        item.toString().substring(item.toString().indexOf("[") + 1, item.toString().indexOf("]")),
                        item.getValue());
        });
    }

    // 各部门承担项目数量
    public void getProjectDeptStatistic(CmcProject cmcProject, JSONObject deptObject, String beginTime,
            String endTime) {
        for (int i = 107; i <= 115; i++) {
            cmcProject.setUndertakingDept(String.valueOf(i));
            List<CmcProject> deptList = new ArrayList<>();
            if (beginTime.equals("")) {
                if (i != 113)
                    deptList = cmcProjectService.selectCmcProjectList(cmcProject);
                else
                    deptList = cmcProjectService.selectCmcInvestProjectList(cmcProject);
            } else {
                Map<String, Object> params = new HashMap<>();
                params.put("beginTime", beginTime + " 00:00:00");
                params.put("endTime", endTime + " 23:59:59");
                cmcProject.setParams(params);
                deptList = cmcProjectService.selectCmcProjectListByRange(cmcProject);
            }
            deptObject.put(deptService.selectDeptById((long) i).getDeptName(), deptList.size());
        }
        cmcProject.setUndertakingDept(null);
    }

}
