package com.bonus.gs.sub.evaluate.evaluate.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bonus.gs.sub.evaluate.evaluate.beans.*;
import com.bonus.gs.sub.evaluate.evaluate.dao.OutsourcerEvaluateDao;
import com.bonus.gs.sub.evaluate.manager.utils.AjaxRes;
import com.bonus.gs.sub.evaluate.manager.utils.UserUtil;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xliu
 * @date 2024/12/19 10:19
 */
@Service("outsourcerEvaluateService")
public class OutsourcerEvaluateServiceImpl implements OutsourcerEvaluateService {

    @Autowired
    private OutsourcerEvaluateDao dao;
    @Resource
    private OutsourcerEvaluateDao outsourcerEvaluateDao;

    @Override
    public List<EvaluateSubBean> getEvaluatSubListById(EvaluateSubBean bean) {
        return outsourcerEvaluateDao.getEvaluatSubListById(bean);
    }

    @Override
    public SetTemplateBean getTemplateListById(String id) {
        return outsourcerEvaluateDao.getTemplateById(id);
    }

    @Override
    public AjaxRes  getTableTitle(EvaluateSubBean o) {
        AjaxRes ar = new AjaxRes();
        String deptId = (StringUtils.isBlank(o.getDeptId()) || "0".equals(o.getDeptId())) ? "0" : o.getDeptId();
        String deptName = (StringUtils.isBlank(o.getDeptId()) || "0".equals(o.getDeptId())) ? "项目部" : dao.getDeptNameById(deptId);

        int isBusinessDivision = 0;
        String orgType = dao.getIsBusinessDivision(deptId);
        if (StringUtils.isNotBlank(orgType)) {
            isBusinessDivision = Integer.parseInt(orgType);
        }
        List<SetTemplateBean> list = outsourcerEvaluateDao.getTemplateDeatailsList(o);

        List<Map<String, Object>> oneList = new ArrayList<>();
        List<Map<String, Object>> twoList = new ArrayList<>();
        List<Map<String, Object>> threeList = new ArrayList<>();
        List<List<Map<String, Object>>> finalList = new ArrayList<>();

        Map<String, Object> mapNum = new LinkedHashMap<>();
        mapNum.put("title", "序号");
        mapNum.put("mergeType", "rowspan");
        mapNum.put("num", 3);
        mapNum.put("minWidth", 100);
        mapNum.put("field", "index");

        Map<String, Object> mapSub = new LinkedHashMap<>();
        mapSub.put("title", "施工业务外包商");
        mapSub.put("mergeType", "rowspan");
        mapSub.put("num", 3);
        mapSub.put("minWidth", 100);
        mapSub.put("field", "subName");

        Map<String, Object> mapPro = new LinkedHashMap<>();
        mapPro.put("title", "工程名称");
        mapPro.put("mergeType", "rowspan");
        mapPro.put("num", 3);
        mapPro.put("minWidth", 100);
        mapPro.put("field", "proName");

        oneList.add(mapNum);
        oneList.add(mapSub);
        oneList.add(mapPro);
        //添加二级标题、三级标题
        for (SetTemplateBean setTemplateBean : list) {
            if (!StringUtils.isBlank(setTemplateBean.getResponsibleDepartment())) {
                if (Arrays.asList(setTemplateBean.getResponsibleDepartment().split(",")).contains(deptId)) {
                    addEvaChildMap(twoList, setTemplateBean, 1);
                    addEvaChildMap(threeList, setTemplateBean, 1, deptName, deptId, o.getType());
                } else if (isBusinessDivision == 1) {
                    if (Arrays.asList(setTemplateBean.getResponsibleDepartment().split(",")).contains("-1") ||
                            Arrays.asList(setTemplateBean.getResponsibleDepartment().split(",")).contains(deptId)) {
                        addEvaChildMap(twoList, setTemplateBean, 1);
                        addEvaChildMap(threeList, setTemplateBean, 1, deptName, deptId, o.getType());
                    }
                }

            }

        }
        //获取二级标题的field
        Set<String> parentIdArr = new HashSet<>();
        for (Map<String, Object> stringObjectMap : twoList) {
            parentIdArr.add(stringObjectMap.get("field").toString());
        }
        //添加一级标题
        for (int i = 0; i < parentIdArr.size(); i++) {
            for (SetTemplateBean setTemplateBean : list) {
                if (parentIdArr.contains(setTemplateBean.getId())) {
                    int num = 0;
                    for (Map<String, Object> stringObjectMap : twoList) {
                        if (stringObjectMap.get("field").equals(setTemplateBean.getId())) {
                            num++;
                        }
                    }
                    setTemplateBean.setParentId(setTemplateBean.getId() + "-");
                    addEvaChildMap(oneList, setTemplateBean, num);
                }
            }
        }
        //添加数据
        String type = StringUtils.isBlank(o.getDeptId()) ? "项目" : "职能";
        if ("0".equals(o.getDeptId())) {
            type = "项目";
        }
        List<EvaluateSubBean> subList = outsourcerEvaluateDao.getSubAndProjectByEvaluateId(o.getEvaluateId(), type,
                UserUtil.getLoginUser().getId().toString());
        List<Map<String, Object>> childList = new ArrayList<>();
        if (subList != null && !subList.isEmpty()) {
            for (EvaluateSubBean subBean : subList) {
                Map<String, Object> childMap = new LinkedHashMap<>();
                childMap.put("subName", subBean.getSubName());
                childMap.put("proName", subBean.getProName());
                childMap.put("subId", subBean.getSubId());
                childMap.put("proId", subBean.getProId());
                for (Map<String, Object> stringObjectMap : threeList) {
                    childMap.put(stringObjectMap.get("field").toString(), "");
                }
                childList.add(childMap);
            }
        }
        oneList = oneList.stream().distinct().collect(Collectors.toList());
        Map<String, Object> upload = new LinkedHashMap<>();
        upload.put("title", "操作");
        upload.put("mergeType", "rowspan");
        upload.put("num", 3);
        upload.put("minWidth", 100);
        upload.put("field", "examineAndApprove");
        oneList.add(upload);

        finalList.add(oneList);
        finalList.add(twoList);
        finalList.add(threeList);
        String resParams = JSONArray.toJSON(finalList).toString();
        String childParams = JSONArray.toJSON(childList).toString();
        ar.setSucceed(resParams, childParams);
        return ar;
    }


    @Override
    public AjaxRes getTableList(EvaluateSubBean o) {
        AjaxRes ar = new AjaxRes();
        String deptId = (StringUtils.isBlank(o.getDeptId()) || "0".equals(o.getDeptId())) ? "0" : o.getDeptId();
        String deptName = (StringUtils.isBlank(o.getDeptId()) || "0".equals(o.getDeptId())) ? "项目部" : dao.getDeptNameById(deptId);

        int isBusinessDivision = 0;
        String orgType = dao.getIsBusinessDivision(deptId);
        if (StringUtils.isNotBlank(orgType)) {
            isBusinessDivision = Integer.parseInt(orgType);
        }
        List<SetTemplateBean> list = outsourcerEvaluateDao.getTemplateDeatailsList(o);

        List<Map<String, Object>> oneList = new ArrayList<>();
        List<Map<String, Object>> twoList = new ArrayList<>();
        List<Map<String, Object>> threeList = new ArrayList<>();
        List<List<Map<String, Object>>> finalList = new ArrayList<>();

        Map<String, Object> mapNum = new LinkedHashMap<>();
        mapNum.put("title", "序号");
        mapNum.put("mergeType", "rowspan");
        mapNum.put("num", 3);
        mapNum.put("minWidth", 100);
        mapNum.put("field", "index");

        Map<String, Object> mapSub = new LinkedHashMap<>();
        mapSub.put("title", "施工业务外包商");
        mapSub.put("mergeType", "rowspan");
        mapSub.put("num", 3);
        mapSub.put("minWidth", 100);
        mapSub.put("field", "subName");

        Map<String, Object> mapPro = new LinkedHashMap<>();
        mapPro.put("title", "工程名称");
        mapPro.put("mergeType", "rowspan");
        mapPro.put("num", 3);
        mapPro.put("minWidth", 100);
        mapPro.put("field", "proName");

        oneList.add(mapNum);
        oneList.add(mapSub);
        oneList.add(mapPro);
        //添加二级标题、三级标题
        for (SetTemplateBean setTemplateBean : list) {
            if (!StringUtils.isBlank(setTemplateBean.getResponsibleDepartment())) {
                if (Arrays.asList(setTemplateBean.getResponsibleDepartment().split(",")).contains(deptId)) {
                    addEvaChildMap(twoList, setTemplateBean, 1);
                    addEvaChildMap(threeList, setTemplateBean, 1, deptName, deptId, o.getType());
                } else if (isBusinessDivision == 1) {
                    if (Arrays.asList(setTemplateBean.getResponsibleDepartment().split(",")).contains("-1") ||
                            Arrays.asList(setTemplateBean.getResponsibleDepartment().split(",")).contains(deptId)) {
                        addEvaChildMap(twoList, setTemplateBean, 1);
                        addEvaChildMap(threeList, setTemplateBean, 1, deptName, deptId, o.getType());
                    }
                }

            }

        }
        //获取二级标题的field
        Set<String> parentIdArr = new HashSet<>();
        for (Map<String, Object> stringObjectMap : twoList) {
            parentIdArr.add(stringObjectMap.get("field").toString());
        }
        //添加一级标题
        for (int i = 0; i < parentIdArr.size(); i++) {
            for (SetTemplateBean setTemplateBean : list) {
                if (parentIdArr.contains(setTemplateBean.getId())) {
                    int num = 0;
                    for (Map<String, Object> stringObjectMap : twoList) {
                        if (stringObjectMap.get("field").equals(setTemplateBean.getId())) {
                            num++;
                        }
                    }
                    setTemplateBean.setParentId(setTemplateBean.getId() + "-");
                    addEvaChildMap(oneList, setTemplateBean, num);
                }
            }
        }
        //添加数据
        String type = StringUtils.isBlank(o.getDeptId()) ? "项目" : "职能";
        if ("0".equals(o.getDeptId())) {
            type = "项目";
        }
        List<EvaluateSubBean> subList = outsourcerEvaluateDao.getSubAndProjectByEvaluateId(o.getEvaluateId(), type,
                UserUtil.getLoginUser().getId().toString());
        List<Map<String, Object>> childList = new ArrayList<>();
        if (subList != null && !subList.isEmpty()) {
            for (EvaluateSubBean subBean : subList) {
                Map<String, Object> childMap = new LinkedHashMap<>();
                childMap.put("subName", subBean.getSubName());
                childMap.put("proName", subBean.getProName());
                childMap.put("subId", subBean.getSubId());
                childMap.put("proId", subBean.getProId());
                for (Map<String, Object> stringObjectMap : threeList) {
                    childMap.put(stringObjectMap.get("field").toString(), "");
                }
                childList.add(childMap);
            }
        }
        oneList = oneList.stream().distinct().collect(Collectors.toList());
        TableData tableData = new TableData();
        tableData.setOneList(oneList);
        tableData.setTwoList(twoList);
        tableData.setThreeList(threeList);
        tableData.setChildList(childList);
        ar.setSucceed(tableData);
        return ar;
    }

    private void addEvaChildMap(List<Map<String, Object>> list, SetTemplateBean setTemplateBean, int num) {
        Map<String, Object> childMap = new LinkedHashMap<>();
        childMap.put("title", setTemplateBean.getIndexName());
        childMap.put("method", setTemplateBean.getMethod());
        childMap.put("standard", setTemplateBean.getStandard());
        childMap.put("countType", setTemplateBean.getCountType());
        childMap.put("standardScore", setTemplateBean.getStandardScore());
        childMap.put("mergeType", "colspan");
        childMap.put("num", num);
        childMap.put("field", setTemplateBean.getParentId());
        list.add(childMap);
    }

    private void addEvaChildMap(List<Map<String, Object>> list, SetTemplateBean setTemplateBean, int num,
                                String deptName, String deptId, String type) {
        Map<String, Object> childMap = new LinkedHashMap<>();
        childMap.put("title", deptName);
        childMap.put("mergeType", "colspan");
        childMap.put("num", num);
        if (!StringUtils.isBlank(type) && "evaluate".equals(type)) {
            childMap.put("edit", "text");
        }
        childMap.put("field", setTemplateBean.getParentId() + "-" + setTemplateBean.getId() + "-" + deptId);
        list.add(childMap);
    }

    private void addAuditChildMap(List<Map<String, Object>> list, SetTemplateBean setTemplateBean, int num,
                                  String deptName, String deptId, Boolean isEdit) {
        Map<String, Object> childMap = new LinkedHashMap<>();
        childMap.put("title", deptName);
        childMap.put("mergeType", "colspan");
        childMap.put("num", num);
        if (isEdit) {
            childMap.put("edit", "text");
        }
        childMap.put("field", setTemplateBean.getParentId() + "-" + setTemplateBean.getId() + "-" + deptId);
        list.add(childMap);
    }


    private void addChildMap(List<Map<String, Object>> list, SetTemplateBean setTemplateBean, int num, int type, String parentId) {
        Map<String, Object> childMap = new LinkedHashMap<>();
        if ("小计".equals(setTemplateBean.getIndexName()) || "合计".equals(setTemplateBean.getIndexName())) {
            if ("小计".equals(setTemplateBean.getIndexName())) {
                childMap.put("field", parentId + "-subtotal");
            } else {
                childMap.put("field", parentId + "-total");
            }
        } else {
            childMap.put("field", parentId);
        }
        childMap.put("title", setTemplateBean.getIndexName());
        childMap.put("method", setTemplateBean.getMethod());
        childMap.put("standard", setTemplateBean.getStandard());
        childMap.put("countType", setTemplateBean.getCountType());
        childMap.put("standardScore", setTemplateBean.getStandardScore());
        childMap.put("mergeType", type == 1 ? "colspan" : "rowspan");
        childMap.put("num", num);
        childMap.put("minWidth", 100);

        list.add(childMap);
    }

    private void addChildMap(List<Map<String, Object>> list, SetTemplateBean setTemplateBean, int num,
                             String deptName, String deptId, String parentId) {
        Map<String, Object> childMap = new LinkedHashMap<>();
        childMap.put("title", deptName);
        childMap.put("mergeType", "colspan");
        childMap.put("num", num);
//        childMap.put("edit", "text");
        childMap.put("minWidth", 100);
        childMap.put("field", parentId + "-" + deptId);
        list.add(childMap);
    }

    @Override
    public List<EvaluateSubBean> getSubAndProjectByEvaluateId(String id) {
        return outsourcerEvaluateDao.getSubAndProjectByEvaluateId(id, "", "");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxRes saveEvaluateData(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            String deptId = UserUtil.getLoginUser().getDeptId();
            String userId = String.valueOf(UserUtil.getLoginUser().getId());
            o.setDeptId(deptId);
            o.setUserId(userId);
            if ("7".equals(UserUtil.getLoginUser().getRoleId()) || Arrays.asList(UserUtil.getLoginUser().getRoleId().split(",")).contains("7")) {
                o.setIsProject("1");
            } else {
                o.setIsProject("0");
                if (!"0".equals(deptId)) {
                    //判断当前用户的部门下是否已经评价
                    int count = outsourcerEvaluateDao.getEvaluateCount(o);
                    if (count > 0) {
                        ar.setFailMsg("当前部门已经有人员进行评价，请勿重复评价！！！");
                        return ar;
                    }
                }

            }
            String[] titleArr = o.getTitleFiled().split(",");
            String jsonData = o.getJsonData();
            List<Map<String, Object>> list = JSONArray.parseObject(jsonData, List.class);
            //pj_evaluate_details表
            outsourcerEvaluateDao.insertEvaluateData(o);
            for (int i = 0; i < list.size(); i++) {
                EvaluateDataBean childBean = new EvaluateDataBean();
                BeanUtils.copyProperties(o, childBean);
                childBean.setJsonData(list.get(i).toString());
                childBean.setDeptId(deptId);
                childBean.setUserId(userId);
                childBean.setParentId(o.getId());
                childBean.setProId(list.get(i).get("proId").toString());
                childBean.setProName(list.get(i).get("proName").toString());
                childBean.setSubId(list.get(i).get("subId").toString());
                childBean.setSubName(list.get(i).get("subName").toString());
                //pj_evaluate_result表
                outsourcerEvaluateDao.insertEvaluateChildData(childBean);
            }
            //对list循环打印
            List<EvaluateDataDetailsBean> detailsList = new ArrayList<>();
            for (Map<String, Object> map : list) {
                for (String title : titleArr) {
                    EvaluateDataDetailsBean detailsBean = new EvaluateDataDetailsBean();
                    detailsBean.setEvaluateId(o.getEvaluateId());
                    detailsBean.setTemplateId(o.getTemplateId());
                    detailsBean.setDeptId(deptId);
                    detailsBean.setUserId(userId);
                    detailsBean.setParentId(o.getId());
                    detailsBean.setProId(map.get("proId").toString());
                    detailsBean.setProName(map.get("proName").toString());
                    detailsBean.setSubId(map.get("subId").toString());
                    detailsBean.setSubName(map.get("subName").toString());
                    detailsBean.setTitleId(title);
                    detailsBean.setScore(map.get(title).toString());
                    detailsList.add(detailsBean);
                }
            }
            outsourcerEvaluateDao.saveEvaluateData(detailsList);
            ar.setSucceedMsg("保存成功");
            //判断是否需要等待评价完毕后统一审核
            ExamineBean examineBean = new ExamineBean();
            examineBean.setEvaluateId(o.getEvaluateId());
            examineBean.setEvaluateId(o.getEvaluateId());
            examineBean.setPostId(deptId);
            examineBean.setEvaluateType("0");
            String orgType = UserUtil.getLoginUser().getOrgType();
            String roleName = UserUtil.getLoginUser().getRoleName();
            examineBean.setUserId(userId);
            if ("0".equals(deptId) || ("1".equals(orgType) && "评价人".equals(roleName))) {
                System.err.println("项目部或者事业部评价人");
                int num = isWait(o.getEvaluateId());
                System.err.println("isWait==" + num);
                if (num <= 0) {
                    addExaminePerson(examineBean);
                }
            } else {
                System.err.println("其他部门,直接去审核");
                //直接去审核
                addExaminePerson(examineBean);
            }
            //

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            System.err.println("e======" + e.toString());
            ar.setFailMsg("保存失败");
        }
        return ar;
    }


    @Override
    public AjaxRes updateEvaluateData(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            String deptId = UserUtil.getLoginUser().getDeptId();
            String userId = String.valueOf(UserUtil.getLoginUser().getId());
            o.setDeptId(deptId);
            o.setUserId(userId);
            if ("7".equals(UserUtil.getLoginUser().getRoleId()) || Arrays.asList(UserUtil.getLoginUser().getRoleId().split(",")).contains("7")) {
                o.setIsProject("1");
            } else {
                o.setIsProject("0");
                //判断当前用户的部门下是否已经评价
//                o.setType("edit");
//                int count = outsourcerEvaluateDao.getEvaluateCount(o);
//                if (count > 0) {
//                    ar.setFailMsg("当前部门已经有人员进行评价，请勿重复评价！！！");
//                    return ar;
//                }
            }
            String[] titleArr = o.getTitleFiled().split(",");
            String jsonData = o.getJsonData();
            List<Map<String, Object>> list = JSONArray.parseObject(jsonData, List.class);
            //pj_evaluate_details表
            outsourcerEvaluateDao.updateEvaluateData(o);
            for (int i = 0; i < list.size(); i++) {
                if ("2".equals(list.get(i).get("isApprove").toString()) || "0".equals(list.get(i).get("isApprove").toString())) {
                    EvaluateDataBean childBean = new EvaluateDataBean();
                    BeanUtils.copyProperties(o, childBean);
                    childBean.setJsonData(list.get(i).toString());
                    childBean.setDeptId(deptId);
                    childBean.setUserId(userId);
                    childBean.setParentId(o.getId());
                    childBean.setProId(list.get(i).get("proId").toString());
                    childBean.setProName(list.get(i).get("proName").toString());
                    childBean.setSubId(list.get(i).get("subId").toString());
                    childBean.setSubName(list.get(i).get("subName").toString());
                    childBean.setIsApprove("0");
                    childBean.setId(list.get(i).get("id").toString());
                    //pj_evaluate_result表
                    outsourcerEvaluateDao.updateEvaluateChildData(childBean);
                }
            }
            //对list循环打印
            List<EvaluateDataDetailsBean> detailsList = new ArrayList<>();
            for (Map<String, Object> map : list) {
                for (String title : titleArr) {
                    EvaluateDataDetailsBean detailsBean = new EvaluateDataDetailsBean();
                    detailsBean.setEvaluateId(o.getEvaluateId());
                    detailsBean.setTemplateId(o.getTemplateId());
                    detailsBean.setDeptId(deptId);
                    detailsBean.setUserId(userId);
                    detailsBean.setParentId(o.getId());
                    detailsBean.setProId(map.get("proId").toString());
                    detailsBean.setProName(map.get("proName").toString());
                    detailsBean.setSubId(map.get("subId").toString());
                    detailsBean.setSubName(map.get("subName").toString());
                    detailsBean.setTitleId(title);
                    detailsBean.setScore(map.get(title).toString());
                    detailsList.add(detailsBean);
                }
            }
            outsourcerEvaluateDao.deleteEvaluateData(o);
            outsourcerEvaluateDao.updateEvalStatus("2",o.getEvaluateId());
            outsourcerEvaluateDao.saveEvaluateData(detailsList);
            o.setIsApprove("0");
            o.setEvaluateType("3");
            o.setDetailsId(o.getId());
            outsourcerEvaluateDao.updatepjEvaluateDetailsStatus(o);
            //pj_evaluate_details修改checkOne
            ar.setSucceedMsg("保存成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ar.setFailMsg("保存失败");
        }
        return ar;
    }

    @Override
    public AjaxRes getAuditBtn(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            //查询所有的部门
            List<EvaluateDataBean> list = outsourcerEvaluateDao.getAuditBtn(o);
            Set<String> set = new HashSet<>();
            //取出所有部门 单个id
            for (EvaluateDataBean dataBean : list) {
                String[] arr = dataBean.getDeptId().split(",");
                set.addAll(Arrays.asList(arr));
            }
            List<EvaluateDataBean> finalList = new ArrayList<>();
            //对set排序
            List<String> sortList = new ArrayList<>(set);
            sortList.forEach(s -> {
                EvaluateSubBean subBean = new EvaluateSubBean();
                EvaluatePersonBean personBean = new EvaluatePersonBean();
                String name = "";
                if ("-1".equals(s)) {
                    subBean.setEvaluateId(o.getEvaluateId());
                    personBean = dao.getDeptName(subBean);
                } else {
                    name = dao.getDeptNameById(s);
                }
                EvaluateDataBean dataBean = new EvaluateDataBean();
                if ("0".equals(s)) {
                    dataBean.setName("项目部");
                    dataBean.setId("0");
                } else if ("-1".equals(s)) {
                    dataBean.setName(personBean.getDeptName());
                    dataBean.setId(personBean.getDeptId());
                } else {
                    dataBean.setName(name);
                    dataBean.setId(s);
                }
                //判断当前部门是否已经审核
                int isApproval = outsourcerEvaluateDao.getIsApprovalByDeptId(o, dataBean);
                int isRejection = outsourcerEvaluateDao.getIsRejectionByDeptId(o, dataBean);
                if (isApproval > 0) {
                    dataBean.setIsApprove("0");
                } else {
                    dataBean.setIsApprove("1");
                }
                if (isRejection > 0) {
                    dataBean.setIsApprove("2");
                }
                finalList.add(dataBean);
            });
            ar.setSucceed(finalList);
        } catch (Exception e) {
            ar.setFailMsg("获取失败");
        }
        return ar;
    }

    @Override
    public AjaxRes getTotalTitle(EvaluateSubBean o) {
        AjaxRes ar = new AjaxRes();
        EvaluateDataBean bean = outsourcerEvaluateDao.getSummaryJsonData(o);
        String jsonData = bean.getJsonData();
        List<Map<String, Object>> list = JSONArray.parseObject(jsonData, List.class);
        List<List<Map<String, Object>>> finalList = new ArrayList<>();
        //获取所有带total的字段
        Set<String> titleSet = new HashSet<>();
        for (Map<String, Object> map : list) {
            for (String key : map.keySet()) {
                if (key.contains("-total")) {
                    titleSet.add(key);
                }
            }
        }
        //对titleSet排序  根据title.split("-")[0]排序
        List<String> sortList = titleSet.stream().sorted(Comparator.comparing(s -> s.split("-")[0])).collect(Collectors.toList());
        List<Map<String, Object>> oneList = new ArrayList<>();
        //添加一级标题
        addTitleMap(oneList, "序号", "index", 1, 100);
        addTitleMap(oneList, "施工业务外包商", "subName", 1, 180);
        addTitleMap(oneList, "工程名称", "proName", 1, 180);
        for (String title : sortList) {
            String name = outsourcerEvaluateDao.getIndexNameById(title.split("-")[0]);
            addTitleMap(oneList, name, title, 1, 180);
        }
        addTitleMap(oneList, "合计", "totalScore", 1, 180);
        List<Map<String, Object>> childDataList = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Map<String, Object> childMap = new LinkedHashMap<>();
            childMap.put("subName", map.get("subName"));
            childMap.put("subId", map.get("subId"));
            childMap.put("proName", map.get("proName"));
            childMap.put("proId", map.get("proId"));
            Float score = 0.0F;
            for (String title : sortList) {
                childMap.put(title, map.get(title));
                score += Float.parseFloat(map.get(title).toString());
            }
            //合计为加和

            childMap.put("totalScore", String.format("%.2f", score));
            childDataList.add(childMap);
        }

        finalList.add(oneList);
        String resParams = JSONArray.toJSON(finalList).toString();
        String childParams = JSONArray.toJSON(childDataList).toString();
        ar.setSucceed(resParams, childParams);
        return ar;
    }

    @Override
    public AjaxRes getCollectTitle(EvaluateSubBean o) {
        AjaxRes ar = new AjaxRes();
        EvaluateDataBean bean = outsourcerEvaluateDao.getSummaryJsonData(o);
        String jsonData = bean.getJsonData();
        List<Map<String, Object>> list = JSONArray.parseObject(jsonData, List.class);
        List<List<Map<String, Object>>> finalList = new ArrayList<>();
        //获取所有带total的字段
        Set<String> titleSet = new HashSet<>();
        for (Map<String, Object> map : list) {
            for (String key : map.keySet()) {
                if (key.contains("-total")) {
                    titleSet.add(key);
                }
            }
        }
        //对titleSet排序  根据title.split("-")[0]排序
        List<String> sortList = titleSet.stream().sorted(Comparator.comparing(s -> s.split("-")[0])).collect(Collectors.toList());
        List<Map<String, Object>> oneList = new ArrayList<>();
        //添加一级标题
        addTitleMap(oneList, "序号", "index", 1, 100);
        addTitleMap(oneList, "施工业务外包商", "subName", 1, 180);
        for (String title : sortList) {
            String name = outsourcerEvaluateDao.getIndexNameById(title.split("-")[0]);
            String countType = outsourcerEvaluateDao.getCountTypeById(title.split("-")[0]);
            String standardScore = outsourcerEvaluateDao.getStandardScoreById(title.split("-")[0]);
            addCollectTitleMap(oneList, name, title, 1, 180, countType, standardScore);
        }
        addTitleMap(oneList, "合计", "totalScore", 1, 180);
        List<Map<String, Object>> childDataList = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Map<String, Object> childMap = new LinkedHashMap<>();
            childMap.put("subName", map.get("subName"));
            childMap.put("subId", map.get("subId"));
            childMap.put("proId", map.get("proId"));
            Float score = 0.0F;
            for (String title : sortList) {
                childMap.put(title, map.get(title));
                score += Float.parseFloat(map.get(title).toString());
            }
            //合计为加和
            childMap.put("totalScore", score);
            childDataList.add(childMap);
        }

        //获取所有的承包商 从childDataList
        Set<String> subNameSet = new HashSet<>();
        for (Map<String, Object> map : childDataList) {
            subNameSet.add(map.get("subName").toString());
        }
        List<Map<String, Object>> finalChildList = new ArrayList<>();
        for (String subName : subNameSet) {
            Map<String, Object> childMap = new LinkedHashMap<>();
            childMap.put("subName", subName);
            //从childDataList中获取subId 和 proId 根据subName
            String subId = "";
            String proId = "";
            for (Map<String, Object> map : childDataList) {
                if (subName.equals(map.get("subName").toString())) {
                    subId = map.get("subId").toString();
                    proId = map.get("proId").toString();
                }
            }

            childMap.put("subId", subId);
            childMap.put("proId", proId);
            Float score = 0.0F;
            for (String title : sortList) {
                //从oneList中获取title的countType 和 standardScore
                String countType = "";
                String standardScore = "";
                for (Map<String, Object> oneMap : oneList) {
                    if (title.equals(oneMap.get("field").toString())) {
                        countType = oneMap.get("countType").toString();
                        standardScore = oneMap.get("standardScore").toString();
                    }
                }
                ArrayList<Float> total = new ArrayList<>();
                for (Map<String, Object> map : childDataList) {
                    if (subName.equals(map.get("subName").toString())) {
                        total.add(Float.parseFloat(map.get(title).toString()));
                    }
                }
                Float totalScore = 0.0F;
                if ("累加".equals(countType)) {
                    for (Float aFloat : total) {
                        totalScore += aFloat;
                    }
                    childMap.put(title, totalScore);
                } else if ("累减".equals(countType)) {
                    for (Float aFloat : total) {
                        totalScore += aFloat;
                    }
                    totalScore = Float.parseFloat(standardScore) - totalScore;
                } else if ("平均值".equals(countType)) {
                    for (Float aFloat : total) {
                        totalScore += aFloat;
                    }
                    totalScore = totalScore / total.size();
                } else if ("最大值".equals(countType)) {
                    for (Float aFloat : total) {
                        if (aFloat > totalScore) {
                            totalScore = aFloat;
                        }
                    }
                } else if ("最小值".equals(countType)) {
                    totalScore = total.get(0);
                    for (Float aFloat : total) {
                        if (aFloat < totalScore) {
                            totalScore = aFloat;
                        }
                    }
                }
                score += totalScore;
                childMap.put(title, String.format("%.2f", totalScore));
            }
            childMap.put("totalScore", String.format("%.2f", score));
            finalChildList.add(childMap);
        }
        finalList.add(oneList);
        String resParams = JSONArray.toJSON(finalList).toString();
        String childParams = JSONArray.toJSON(finalChildList).toString();
        ar.setSucceed(resParams, childParams);
        return ar;
    }

    @Override
    public AjaxRes getCollectData(EvaluateSubBean o) {
        AjaxRes ar = new AjaxRes();
        //获取模板详情
        List<SetTemplateBean> templateList = outsourcerEvaluateDao.getTemplateDeatailsList(o);
        //获取评价数据
        List<EvaluateDataDetailsBean> childList = outsourcerEvaluateDao.getCollectChildData(o);

        List<Map<String, Object>> oneList = new ArrayList<>();
        List<Map<String, Object>> twoList = new ArrayList<>();
        List<Map<String, Object>> threeList = new ArrayList<>();
        List<List<Map<String, Object>>> finalList = new ArrayList<>();
        //添加一级标题
        addTitleMap(oneList, "序号", "index", 3, 100);
        addTitleMap(oneList, "施工业务外包商", "subName", 3, 180);
        addTitleMap(oneList, "工程名称", "proName", 3, 180);

        String parentId = "";
        int childNum = 0;
        int twoNum = 0;
        for (SetTemplateBean setTemplateBean : templateList) {
            //判断是否是一级标题
            if ("0".equals(setTemplateBean.getParentId())) {
                //获取当前一级标题的id
                parentId = setTemplateBean.getId();
                //获取当前一级标题下的二级标题数量
                childNum = getChildNum(templateList, parentId);
                //初始化二级标题数量
                twoNum = 0;
            }
            //判断当前二级标题下是否有部门
            if (!StringUtils.isBlank(setTemplateBean.getResponsibleDepartment())) {
                //初始化二级标题下部门数量
                int twoLevelNum = 0;
                //对部门进行循环
                for (String deptId : setTemplateBean.getResponsibleDepartment().split(",")) {
                    //获取部门名称
                    String deptName = dao.getDeptNameById(deptId);
                    //二级标题下部门数量+1
                    twoLevelNum++;
                    //如果部门id为0，则部门名称为项目部
                    if ("0".equals(deptId)) {
                        deptName = "项目部";
                    }
                    String parentIdStr = setTemplateBean.getParentId() + "-" + setTemplateBean.getId();
                    if ("-1".equals(deptId)) {
                        EvaluatePersonBean personBean = new EvaluatePersonBean();
                        personBean = dao.getDeptName(o);
                        deptName = personBean.getDeptName();
                        deptId = personBean.getDeptId();
                        parentIdStr =
                                setTemplateBean.getParentId() + "-" + setTemplateBean.getId();
                    }
                    //添加三级标题
                    addChildMap(threeList, setTemplateBean, 1, deptName, deptId, parentIdStr);
                }
                //二级标题数量+1
                twoNum++;
                //添加二级标题
                String parentIdStr = setTemplateBean.getParentId() + "-" + setTemplateBean.getId();
                addChildMap(twoList, setTemplateBean, twoLevelNum, 1, parentIdStr);
                //添加小计、合计
                addSummaryMap(twoList, setTemplateBean, childNum, twoNum, parentIdStr);
            }
        }
        //添加一级标题
        addParentTitleMap(oneList, twoList, templateList);

        List<Map<String, Object>> childDataList = new ArrayList<>();
        //获取三级标题的field
        Set<String> titleSet = getTitleSet(threeList);
        //获取公共数据 将数据汇总成分包商-工程的行数据
        List<EvaluateDataDetailsBean> commonList = getCommonList(childList);
        //对公共数据进行循环
        for (EvaluateDataDetailsBean dataBean : commonList) {
            Map<String, Object> childMap = new LinkedHashMap<>();
            //添加分包商
            childMap.put("subName", dataBean.getSubName());
            //添加工程名称
            childMap.put("proName", dataBean.getProName());
            //添加分包商
            childMap.put("subId", dataBean.getSubId());
            //添加工程名称
            childMap.put("proId", dataBean.getProId());
            //对部门下的数据进行循环赋值
            for (String title : titleSet) {
                System.out.println(title);
                //赋值  getScore 获取分值
                childMap.put(title, getScore(childList, dataBean, title));
            }
            childMap.put("totalScore", "");
            childDataList.add(childMap);
//            childMap = new LinkedHashMap<>();
//            //添加分包商
//            childMap.put("subName", dataBean.getSubName());
//            //添加工程名称
//            childMap.put("proName", "汇总：");
//            for (String title : titleSet) {
//                //赋值  getScore 获取分值
//                childMap.put(title, "");
//            }
//            childDataList.add(childMap);
        }
        //一级标题添加得分
        addTitleMap(oneList, "得分", "totalScore", 3, 180);

//        //将中间的汇总删除  仅保留同名承包商下面的最后一个汇总
//        List<Map<String, Object>> finalChildDataList = new ArrayList<>();
//        for (int i = 0; i < childDataList.size(); i++) {
//            if (!"汇总：".equals(childDataList.get(i).get("proName"))) {
//                finalChildDataList.add(childDataList.get(i));
//            }
//            if (i == childDataList.size() - 1) {
//                finalChildDataList.add(childDataList.get(i));
//            } else {
//                if (!childDataList.get(i).get("subName").equals(childDataList.get(i + 1).get("subName"))) {
//                    finalChildDataList.add(childDataList.get(i));
//                }
//            }
//        }

        finalList.add(oneList);
        finalList.add(twoList);
        finalList.add(threeList);
        String resParams = JSONArray.toJSON(finalList).toString();
        String childParams = JSONArray.toJSON(childDataList).toString();
        ar.setSucceed(resParams, childParams);
        return ar;
    }

    @Override
    public List<OutSourceBean> getEvaluateAuditList(OutSourceBean o) {
        o.setUserId(UserUtil.getLoginUser().getId().toString());
        return dao.getEvaluateAuditList(o);
    }

    @Override
    public AjaxRes getAuditTitleData(EvaluateSubBean o) {
        AjaxRes ar = new AjaxRes();
        String deptId = o.getDeptId();
        String deptName = dao.getDeptNameById(deptId);
        if ("-1".equals(deptId)) {
            deptId = UserUtil.getLoginUser().getDeptId();
            deptName = dao.getDeptNameById(UserUtil.getLoginUser().getDeptId());
        } else if ("0".equals(deptId)) {
            deptId = "0";
            deptName = "项目部";
        }
        List<SetTemplateBean> list = outsourcerEvaluateDao.getTemplateDeatailsList(o);
        int isBusinessDivision = 0;
        String orgType = dao.getIsBusinessDivision(deptId);
        if (StringUtils.isNotBlank(orgType)) {
            isBusinessDivision = Integer.parseInt(orgType);
        }
        List<Map<String, Object>> oneList = new ArrayList<>();
        List<Map<String, Object>> twoList = new ArrayList<>();
        List<Map<String, Object>> threeList = new ArrayList<>();
        List<List<Map<String, Object>>> finalList = new ArrayList<>();

        oneList.add(createMap("序号", "rowspan", 3, 100, "index"));
        oneList.add(createMap("施工业务外包商", "rowspan", 3, 100, "subName"));
        oneList.add(createMap("工程名称", "rowspan", 3, 100, "proName"));

//添加二级标题、三级标题
        for (SetTemplateBean setTemplateBean : list) {
            if (!StringUtils.isBlank(setTemplateBean.getResponsibleDepartment()) &&
                    Arrays.asList(setTemplateBean.getResponsibleDepartment().split(",")).contains(deptId)) {
                addEvaChildMap(twoList, setTemplateBean, 1);
                addAuditChildMap(threeList, setTemplateBean, 1, deptName, deptId, "evaluate".equals(o.getType()));
            } else if (!StringUtils.isBlank(setTemplateBean.getResponsibleDepartment()) && isBusinessDivision == 1) {
                if (Arrays.asList(setTemplateBean.getResponsibleDepartment().split(",")).contains("-1")) {
                    addEvaChildMap(twoList, setTemplateBean, 1);
                    addEvaChildMap(threeList, setTemplateBean, 1, deptName, deptId, o.getType());
                }
            }
        }

//获取二级标题的field
        Set<String> parentIdArr = twoList.stream()
                .map(map -> map.get("field").toString())
                .collect(Collectors.toCollection(TreeSet::new));
//添加一级标题
        for (String parentId : parentIdArr) {
            for (SetTemplateBean setTemplateBean : list) {
                if (parentId.equals(setTemplateBean.getId())) {
                    long num = twoList.stream()
                            .filter(map -> map.get("field").equals(setTemplateBean.getId()))
                            .count();
                    setTemplateBean.setParentId(setTemplateBean.getId() + "-");
                    addEvaChildMap(oneList, setTemplateBean, (int) num);
                }
            }
        }

        oneList.add(createMap("评价人", "rowspan", 3, 100, "appraiser"));
        oneList.add(createMap("审批", "rowspan", 3, 100, "examineAndApprove"));

        //添加数据
        o.setDeptId("-1".equals(deptId) ? UserUtil.getLoginUser().getDeptId() : "0".equals(deptId) ? "0" : deptId);
        if ("0".equals(o.getDeptId())) {
            if (!"audit".equals(o.getType()) && !"auditAll".equals(o.getType())) {
                o.setUserId(UserUtil.getLoginUser().getId().toString());
            }
        }
        List<EvaluateDataBean> childData = outsourcerEvaluateDao.getChildData(o);
        List<Map<String, Object>> childList = new ArrayList<>();
        for (EvaluateDataBean bean : childData) {
            JSONObject jsonObject = JSONObject.parseObject(bean.getJsonData());
            Map<String, Object> map = new LinkedHashMap<>();
            for (String key : jsonObject.keySet()) {
                map.put(key, jsonObject.get(key));
            }
            map.put("appraiser", bean.getUserName());
            map.put("appraiserId", bean.getUserId());
            map.put("examineAndApprove", "");
            map.put("evaluateId", bean.getEvaluateId());
            map.put("templateId", bean.getTemplateId());
            map.put("deptId", bean.getDeptId());
            map.put("id", bean.getId());
            map.put("isApprove", bean.getIsApprove());
            map.put("isTwoApprove", bean.getIsTwoApprove());
            map.put("isThreeApprove", bean.getIsThreeApprove());
            map.put("detailsId", bean.getParentId());
            childList.add(map);
        }
        finalList.add(oneList);
        finalList.add(twoList);
        finalList.add(threeList);
        //childList根据subName进行排序
        childList.sort(Comparator.comparing(map -> map.get("subName").toString()));
        String resParams = JSONArray.toJSON(finalList).toString();
        String childParams = JSONArray.toJSON(childList).toString();
        ar.setSucceed(resParams, childParams);
        return ar;
    }

    private Map<String, Object> createMap(String title, String mergeType, int num, int minWidth, String field) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("title", title);
        map.put("mergeType", mergeType);
        map.put("num", num);
        map.put("minWidth", minWidth);
        map.put("field", field);
        return map;
    }

    /**
     * 添加一级标题
     *
     * @param list
     * @param title
     * @param field
     * @param num
     * @param minWidth
     */
    private void addTitleMap(List<Map<String, Object>> list, String title, String field, int num, int minWidth) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("title", title);
        map.put("mergeType", "rowspan");
        map.put("num", num);
        map.put("minWidth", minWidth);
        map.put("field", field);
        if ("序号".equals(title)) {
            map.put("type", "numbers");
        }
        list.add(map);
    }

    private void addCollectTitleMap(List<Map<String, Object>> list, String title, String field, int num, int minWidth
            , String countType, String standardScore) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("title", title);
        map.put("mergeType", "rowspan");
        map.put("num", num);
        map.put("minWidth", minWidth);
        map.put("countType", countType);
        map.put("standardScore", standardScore);
        map.put("field", field);
        if ("序号".equals(title)) {
            map.put("type", "numbers");
        }
        list.add(map);
    }

    /**
     * 获取当前一级标题下的二级标题数量
     *
     * @param templateList
     * @param parentId
     * @return
     */
    private int getChildNum(List<SetTemplateBean> templateList, String parentId) {
        for (SetTemplateBean bean : templateList) {
            if (bean.getId().equals(parentId)) {
                return Integer.parseInt(bean.getChildNum());
            }
        }
        return 0;
    }

    /**
     * 添加小计、合计
     *
     * @param twoList
     * @param setTemplateBean
     * @param childNum
     * @param twoNum
     */
    private void addSummaryMap(List<Map<String, Object>> twoList, SetTemplateBean setTemplateBean, int childNum,
                               int twoNum, String parentId) {
        //判断当前二级标题下是否有部门 且二级标题大于1
        if (childNum > 1 && setTemplateBean.getResponsibleDepartment().split(",").length > 0) {
            //添加小计
            addChildMap(twoList, createTemplateBean("小计", setTemplateBean.getParentId(), setTemplateBean.getId()), 2,
                    2, parentId);
            //判断当前二级标题是否是最后一个二级标题
            if (twoNum == childNum) {
                //添加合计
                addChildMap(twoList, createTemplateBean("合计", setTemplateBean.getParentId(), setTemplateBean.getId()),
                        2, 2, parentId);
            }
        } else {
            //添加合计
            addChildMap(twoList, createTemplateBean("合计", setTemplateBean.getParentId(), setTemplateBean.getId()), 2,
                    2, parentId);
        }
    }

    /**
     * 创建模板bean
     *
     * @param indexName
     * @param parentId
     * @return
     */
    private SetTemplateBean createTemplateBean(String indexName, String parentId, String id) {
        SetTemplateBean bean = new SetTemplateBean();
        bean.setIndexName(indexName);
        bean.setParentId(parentId);
        bean.setId(id);
        return bean;
    }

    /**
     * 添加一级标题
     *
     * @param oneList
     * @param twoList
     * @param templateList
     */
    private void addParentTitleMap(List<Map<String, Object>> oneList, List<Map<String, Object>> twoList, List<SetTemplateBean> templateList) {
        Set<String> parentIdArr = new HashSet<>();
        //获取parentId
        for (Map<String, Object> stringObjectMap : twoList) {
            parentIdArr.add(stringObjectMap.get("field").toString().split("-")[0]);
        }
        //对parentIdArr进行排序
        Set<String> parentIdSortArr = new TreeSet<>(parentIdArr);
        //添加一级标题
        for (String parentId : parentIdSortArr) {
            for (SetTemplateBean setTemplateBean : templateList) {
                //当id等于parentId时
                if (parentId.equals(setTemplateBean.getId())) {
                    //获取当前一级标题对应的colNum
                    int num = getNum(twoList, setTemplateBean);
                    String parentIds = setTemplateBean.getId();
                    //添加一级标题
                    addChildMap(oneList, setTemplateBean, num, 1, parentIds);
                }
            }
        }
    }

    /**
     * 获取当前一级标题对应的colNum
     *
     * @param twoList
     * @param setTemplateBean
     * @return
     */
    private int getNum(List<Map<String, Object>> twoList, SetTemplateBean setTemplateBean) {
        int num = 0;
        for (Map<String, Object> stringObjectMap : twoList) {
            if (stringObjectMap.get("field").toString().split("-")[0].equals(setTemplateBean.getId())) {
                if (stringObjectMap.get("mergeType").equals("colspan")) {
                    num += Integer.parseInt(stringObjectMap.get("num").toString());
                } else {
                    num++;
                }
            }
        }
        return num;
    }

    /**
     * 获取三级标题的field
     */
    private Set<String> getTitleSet(List<Map<String, Object>> threeList) {
        Set<String> titleSet = new HashSet<>();
        for (Map<String, Object> map : threeList) {
            titleSet.add(map.get("field").toString());
        }
        return titleSet;
    }

    /**
     * 获取公共数据 将数据汇总成分包商-工程的行数据
     *
     * @param childList
     * @return
     */
    private List<EvaluateDataDetailsBean> getCommonList(List<EvaluateDataDetailsBean> childList) {
        List<EvaluateDataDetailsBean> commonList = new ArrayList<>();
        for (EvaluateDataDetailsBean bean : childList) {
            boolean flag = true;
            for (EvaluateDataDetailsBean detailsBean : commonList) {
                if (bean.getSubId().equals(detailsBean.getSubId()) && bean.getProId().equals(detailsBean.getProId())) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                commonList.add(bean);
            }
        }
        return commonList;
    }

    /**
     * 获取分值
     *
     * @param childList
     * @param dataBean
     * @param title
     * @return
     */
    private String getScore(List<EvaluateDataDetailsBean> childList, EvaluateDataDetailsBean dataBean, String title) {
        for (EvaluateDataDetailsBean detailsBean : childList) {
            if (dataBean.getSubId().equals(detailsBean.getSubId()) && dataBean.getProId().equals(detailsBean.getProId()) && title.equals(detailsBean.getTitleId())) {
                return detailsBean.getScore();
            }
        }
        return "";
    }

    /**
     * 外包商评价列表
     *
     * @param o OutsourceBean
     * @return AjaxRes
     */
    @Override
    public List<OutSourceBean> getTeamEvaluateList(OutSourceBean o) {
        o.setUserId(UserUtil.getLoginUser().getId().toString());
        o.setDeptId(UserUtil.getLoginUser().getDeptId());
        return dao.getTeamEvaluateList(o);
    }


    @Override
    public int isWait(String evaluateId) {
        //项目部已评价人
        int evaluatedNum = dao.getEvaluatedNum(evaluateId);
        System.err.println("已评价人evaluatedNum=" + evaluatedNum);
        //判断事业部是否需要评价
        int proNum = dao.getProEvaluateNum(evaluateId);
        System.err.println("判断事业部是否需要评价proNum=" + proNum);
        //项目部未评价人
        int unEvaluateNum = dao.getUnEvaluateNum(evaluateId) + proNum;
        System.err.println("项目部未评价人unEvaluateNum=" + unEvaluateNum);
        return unEvaluateNum - evaluatedNum;
    }

    @Override
    public int addExaminePerson(ExamineBean o) {
        String postId = o.getPostId();
        //如果是项目部,则获取事业部orgId  插入
        if (postId != null && "0".equals(postId)) {
            String orgId = dao.getOrgIddByEvaluateId(o.getEvaluateId());
            o.setPostId(orgId);
        }
        List<String> stringList = dao.getExaminePersonByDeptAndRoleName(o.getPostId(), "审批人");
        o.setUserList(String.join(",", stringList));
        return dao.addExaminePerson(o);
    }

    @Override
    public int examineNumByEvaluateId(String evaluateId) {
        Set<String> setList = new HashSet<>();
        List<SetTemplateBean> getTemplateDeatailsList = outsourcerEvaluateDao.getThisTemplateByEvaluateId(evaluateId);
        for (SetTemplateBean setTemplateBean : getTemplateDeatailsList) {
            for (String deptId : setTemplateBean.getDutyDept().split(",")) {
                setList.add(deptId);
            }
        }
        return setList.size();
    }

    @Override
    public int getExamineNumByEvaluateId(String evaluateId, String evaluateNode) {
        return dao.getExamineNumByEvaluateId(evaluateId, evaluateNode);
    }


    @Override
    public int startCollectExamineByEvaluateId(EvaluateDataBean o) {
        return dao.startCollectExamineByEvaluateId(o);
    }

    @Override
    public AjaxRes fullApproval(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        try {
            o.setUserId(String.valueOf(UserUtil.getLoginUser().getId()));
            if (StringUtils.isBlank(o.getRejectReason())) {
                o.setRejectReason("");
            } else {
                o.setIsApprove("2");
                //修改pj_evaluate_details状态
                outsourcerEvaluateDao.updateCheckTwoStatus(o);
            }
            int code = outsourcerEvaluateDao.fullApproval(o);
            if (code > 0) {
                ar.setSucceedMsg("审核成功");
            } else {
                ar.setFailMsg("审核失败");
            }
            //查询当前的审核状态
            int count = outsourcerEvaluateDao.getCurrentTwoIsApprove(o);
            if (count == 0) {
                //修改pj_evaluate状态
                o.setIsApprove("3");
//                outsourcerEvaluateDao.updateCheckTwoStatus(o);
                outsourcerEvaluateDao.updateRecordStatus(o);
            }
        } catch (Exception e) {
            ar.setFailMsg("审核失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ar;
    }

    @Override
    public AjaxRes getSummaryCompareList(EvaluateSubBean o) {
        AjaxRes ar = new AjaxRes();
        String[] evaluateDate = o.getEvaluateDate().split(",");
        List<SummaryCompareBean> list = outsourcerEvaluateDao.getSummaryCompareList(o, evaluateDate);
        //获取所有的承包商
        Set<String> subNameSet = new HashSet<>();
        for (SummaryCompareBean bean : list) {
            subNameSet.add(bean.getSubName());
        }
        Set<String> evaluateDateSet = new LinkedHashSet<>(Arrays.asList(evaluateDate));
        //evaluateDateSet根据年月排序

        List<SummaryCompareBean> finalList = new ArrayList<>();
        for (String subName : subNameSet) {
            SummaryCompareBean subBean = new SummaryCompareBean();
            subBean.setSubName(subName);
            finalList.add(subBean);
        }
        List<Map<String, Object>> childDataList = new ArrayList<>();
        List<Map<String, Object>> titleList = new ArrayList<>();
        titleList.add(createMap("序号", "rowspan", 1, 100, "index"));
        for (SummaryCompareBean bean : finalList) {
            Map<String, Object> childMap = new LinkedHashMap<>();
            childMap.put("subName", bean.getSubName());
            titleList.add(createMap("分包商名称", "rowspan", 1, 100, "subName"));
            for (String date : evaluateDateSet) {
                titleList.add(createMap(date, "rowspan", 1, 100, date.replace("年", "-").replace("月", "")));
            }
            for (SummaryCompareBean compareBean : list) {
                if (bean.getSubName().equals(compareBean.getSubName())) {
                    childMap.put(compareBean.getEvaluateDate().replace("年", "-").replace("月", ""), compareBean.getScore());
                }
            }
            childDataList.add(childMap);
        }
        titleList.add(createMap("月度对标平均得分", "rowspan", 1, 100, "avgScore"));
        //titleList去除重复
        List<Map<String, Object>> finalTitleList = new ArrayList<>();
        for (Map<String, Object> map : titleList) {
            if (!finalTitleList.contains(map)) {
                finalTitleList.add(map);
            }
        }
        String resParams = JSONArray.toJSON(finalTitleList).toString();
        String childParams = JSONArray.toJSON(childDataList).toString();
        ar.setSucceed(resParams, childParams);
        return ar;
    }

    @Override
    public AjaxRes isCheckOneIsAudit(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        int count = outsourcerEvaluateDao.isCheckOneIsAudit(o);
        if (count > 0) {
            ar.setSucceed("1");
        } else {
            ar.setFailMsg("0");
        }
        return ar;
    }

    @Override
    public AjaxRes isCheckTwoIsAudit(EvaluateDataBean o) {
        AjaxRes ar = new AjaxRes();
        int count = outsourcerEvaluateDao.isCheckTwoIsAudit(o);
        if (count > 0) {
            ar.setSucceed("1");
        } else {
            ar.setFailMsg("0");
        }
        return ar;
    }
}
