package com.artfess.cqxy.projectManagement.manager.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.artfess.base.context.BaseContext;
import com.artfess.base.feign.UCFeignService;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.*;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.cqxy.bidManagement.manager.BiddingManagementManager;
import com.artfess.cqxy.bidManagement.manager.BiddingPriceExamineManager;
import com.artfess.cqxy.bidManagement.manager.BiddingPriceLimitManager;
import com.artfess.cqxy.completionAcceptance.manager.*;
import com.artfess.cqxy.constructionPermit.manager.ConstructionPermitManager;
import com.artfess.cqxy.contract.manager.ContractManager;
import com.artfess.cqxy.designEstimate.manager.ConstructionDrawingDesignManager;
import com.artfess.cqxy.designEstimate.manager.ConstructionDrawingManager;
import com.artfess.cqxy.designEstimate.manager.EstimateManager;
import com.artfess.cqxy.designEstimate.manager.PreliminaryDesignManager;
import com.artfess.cqxy.feasiblePlan.manager.*;
import com.artfess.cqxy.processManagermant.manager.*;
import com.artfess.cqxy.processManagermant.model.ProgressManageReport;
import com.artfess.cqxy.projectApproval.manager.DecisionBasisManager;
import com.artfess.cqxy.projectApproval.manager.ProjectEstablishmentManager;
import com.artfess.cqxy.projectApproval.model.ProjectEstablishment;
import com.artfess.cqxy.projectManagement.dao.ProjectManagementDao;
import com.artfess.cqxy.projectManagement.manager.ProjectManagementManager;
import com.artfess.cqxy.projectManagement.manager.ProjectPersonnelManager;
import com.artfess.cqxy.projectManagement.model.ProjectManagement;
import com.artfess.cqxy.projectManagement.vo.MergeItemsVo;
import com.artfess.cqxy.projectManagement.vo.ProjectLandCostVo;
import com.artfess.cqxy.universal.manager.AccessoryManager;
import com.artfess.cqxy.utils.BizUtils;
import com.artfess.i18n.util.I18nUtil;
import com.artfess.poi.util.ExcelUtil;
import com.artfess.sysConfig.persistence.manager.SysDictionaryManager;
import com.artfess.sysConfig.persistence.manager.SysMenuManager;
import com.artfess.sysConfig.persistence.model.SysMenu;
import com.artfess.sysConfig.persistence.param.DictModel;
import com.artfess.uc.api.impl.util.ContextUtil;
import com.artfess.uc.api.model.IUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.api.client.util.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目管理表(BizProjectManagement)表服务实现类
 * @author 黎沐华
 * @since 2022-02-10 15:43:45
 */
@Service
public class ProjectManagementManagerImpl extends BaseManagerImpl<ProjectManagementDao, ProjectManagement> implements ProjectManagementManager {

    @Autowired
    ProjectPersonnelManager ppm;

    @Autowired
    private SysDictionaryManager sdm;

    @Autowired
    private ProjectManagementDao projectManagementDao;

    @Autowired
    private ProjectPersonnelManager projectPersonnelManager;

    @Override
    public Integer createSnNum() {
        return projectManagementDao.createSnNum()+1;
    }

    @Autowired
    private BaseContext baseContext;

    @Resource
    private UCFeignService ucFeignService;

    @Resource
    private DecisionBasisManager decisionBasisManager;

    @Resource
    private ProjectEstablishmentManager projectEstablishmentManager;

    @Resource
    private FeasibilityStudyReplyManager feasibilityStudyReplyManager;

    @Resource
    private PlanningSelectionSiteManager planningSelectionSiteManager;

    @Resource
    private PlanningSelectionLandManager planningSelectionLandManager;

    @Resource
    private PlanningUseLandManager planningUseLandManager;

    @Resource
    private PlanningEngineeringManager planningEngineeringManager;

    @Resource
    private PreliminaryDesignManager preliminaryDesignManager;

    @Resource
    private EstimateManager estimateManager;

    @Resource
    private ConstructionDrawingManager constructionDrawingManager;

    @Resource
    private ConstructionDrawingDesignManager constructionDrawingDesignManager;

    @Resource
    private BiddingPriceLimitManager biddingPriceLimitManager;

    @Resource
    private BiddingPriceExamineManager biddingPriceExamineManager;

    @Resource
    private BiddingManagementManager biddingManagementManager;

    @Resource
    private ContractManager contractManager;

    @Resource
    private ConstructionPermitManager constructionPermitManager;

    @Resource
    private SecurityManageManager securityManageManager;

    @Resource
    private AccessoryManager accessoryManager;

    @Resource
    private ProgressManageEpidemicControlManager progressManageEpidemicControlManager;

    @Resource
    private QualityInspectionManager qualityInspectionManager;

    @Resource
    private QualityRectificationManager qualityRectificationManager;

    @Resource
    private ProgressManageReportManager progressManageReportManager;

    @Resource
    private ProgressManageManager progressManageManager;

    @Resource
    private ChangeManagementManager changeManagementManager;

    @Resource
    private TechnicalInformationManager technicalInformationManager;

    @Resource
    private UnitProjectAcceptanceManager unitProjectAcceptanceManager;

    @Resource
    private PreAcceptanceManager preAcceptanceManager;

    @Resource
    private RecordAcceptanceSpecialManager recordAcceptanceSpecialManager;

    @Resource
    private RecordAcceptanceManager recordAcceptanceManager;

    @Resource
    private AcceptanceFinalTransferManager acceptanceFinalTransferManager;

    @Resource
    private AcceptanceSettlementManager acceptanceSettlementManager;

    @Resource
    private AcceptanceFinalAccountsManager acceptanceFinalAccountsManager;

    @Resource
    SysMenuManager sysMenuManager;

    @Override
    public boolean savePm(ProjectManagement pm) {
//        NumberFormat nf  =  NumberFormat.getPercentInstance();
//        nf.setMinimumFractionDigits( 2 );
//        try{
//            pm.setProportionContractAmount(String.valueOf(nf.format(Double.valueOf(pm.getAccumulatedProjectPayment()) / pm.getContractAmount().doubleValue())));
//        }catch(Exception e){
//            pm.setProportionContractAmount("0");
//        }
//        try{
//            pm.setProportionContractAmount(String.valueOf(Double.valueOf(pm.getAccumulatedProjectPayment()) / Double.valueOf(pm.getSocialAuditMoney())));
//        }catch(Exception e){
//            pm.setSocialAuditMoneyAmount("0");
//        }
        // 新增建设规模，如果项目类型是房建工程、装修改造工程、市政配套工程、生态环保工程、新基建就调取【项目管理-编制-立项备案】中建筑面积字段、如果项目类型是市政道路就调取【项目管理-编制-立项备案】中建筑长度字段
        ProjectEstablishment pe = projectEstablishmentManager.getOne(new QueryWrapper<ProjectEstablishment>().eq("IS_DELE_","0").eq("PROJECT_ID_", pm.getId()).last("limit 1"));
        if(pe != null){
            if ("3".equals(pm.getProjectType())){
                String length = pe.getConstructionLength();
                pm.setProjectScale(length);
            }else if("123457".contains(pm.getProjectType())){
                String area = pe.getConstructionHeight();
                pm.setProjectScale(area);
            }
        }
        return projectManagementDao.insert(pm)==1;
    }

    @Override
    public boolean updateById(ProjectManagement entity) {
        // 新增建设规模，如果项目类型是房建工程、装修改造工程、市政配套工程、生态环保工程、新基建就调取【项目管理-编制-立项备案】中建筑面积字段、如果项目类型是市政道路就调取【项目管理-编制-立项备案】中建筑长度字段
        ProjectEstablishment pe = projectEstablishmentManager.getOne(new QueryWrapper<ProjectEstablishment>().eq("IS_DELE_","0").eq("PROJECT_ID_", entity.getId()).last("limit 1"));
        if(pe != null){
            if ("3".equals(entity.getProjectType())){
                String length = pe.getConstructionLength();
                entity.setProjectScale(length);
            }else if("123457".contains(entity.getProjectType())){
                String area = pe.getConstructionHeight();
                entity.setProjectScale(area);
            }
        }
        return super.updateById(entity);
    }

    @Override
    public void updateStatusById(String id, Integer status) {
        ProjectManagement projectManagement = baseMapper.selectById(id);
        if(null == status){
            status = 1;
        }
        // 项目状态为施工许可之前的状态并且不为合同状态时自动显示下一个状态
        if(status < 11 && status != 9){
            status += 1;
        }
        if(null != projectManagement){
            String projectStatus = projectManagement.getProjectStatus();
            if(StringUtils.isBlank(projectStatus)){
                update(new UpdateWrapper<ProjectManagement>().eq("ID_", id).set("PROJECT_STATUS_", status));
            }else {
                Integer oldStatus = Integer.valueOf(projectStatus);
                if(oldStatus < status){
                    update(new UpdateWrapper<ProjectManagement>().eq("ID_", id).set("PROJECT_STATUS_", status));
                }
            }
        }

    }

    @Override
    public PageList<ProjectManagement> queryAllByPage(QueryFilter<ProjectManagement> queryFilter) {
        // 如果表中没有【当前项目】，则设置第一个可用的且排序号最小的项目为当前项目，这个判断其实不应该放在这里的，找不着地方了
//        if (!hasCurrentProject()){
//            projectManagementDao.defaultCurrentProject();
//        }

//        List<QueryField> querys = queryFilter.getQuerys();
//        for(QueryField queryField : querys){
//            if(queryField.getProperty().equalsIgnoreCase("max_money") || queryField.getProperty().equalsIgnoreCase("min_money")){
//                queryField.setProperty("project_money_");
//            }
//        }

        List<QueryField> queryFields = queryFilter.getQuerys();
        boolean isParentId = true;
        boolean isDele = true;
        for (QueryField ele : queryFields) {
            if ("parent_id_".equalsIgnoreCase(ele.getProperty()) || "parentId".equalsIgnoreCase(ele.getProperty())) {
                isParentId = false;
            }
            if ("IS_DELE_".equalsIgnoreCase(ele.getProperty()) || "ISDELE".equalsIgnoreCase(ele.getProperty())) {
                isDele = false;
            }
        }
        if(isParentId){
            queryFilter.addFilter("parent_id_","root", QueryOP.EQUAL);
        }
        if(isDele){
            queryFilter.addFilter("IS_DELE_","0", QueryOP.EQUAL);
        }
        //查询项目时通过项目人员增加查询条件，只有管理员或者可以管理此项目的人员才能查询到此项目
        IUser user= ContextUtil.getCurrentUser();
        // 如果是管理员或者没有项目权限
        if(null != user){
//            String currentUserId = baseContext.getCurrentUserId();
            boolean disableAll = false;
            Integer userType = user.getUserType();
            String userId = user.getUserId();
            CommonResult<JsonNode> userNode = ucFeignService.getUserById(userId);
            if (userNode.getState()) {
                JsonNode userJsonNode = userNode.getValue();
                if(null != userJsonNode){
                    userType = userJsonNode.get("userType").asInt();
                }
            }
            // 1.先通过用户类型判断，过滤掉超级管理员之类的用户
            if(userType != null && userType !=0 && userType != 1){
                // 2.再通过角色判断，过滤掉没有对应角色权限的人员
                // 获取当前用户拥有的所有角色
                Set<String> set = new HashSet<String>();
                List<ObjectNode> list = ucFeignService.getRoleListByAccount(user.getAccount());
                if(BeanUtils.isNotEmpty(list)){
                    for (ObjectNode objectNode : list) {
                        set.add(objectNode.get("code").asText());
                    }
                }
                if(!set.contains("sysRole") && !set.contains("bld") && !set.contains("xmgl") && !set.contains("zdzh")){
                    disableAll = true;
                }
            }
            if(disableAll){
                List<String> projectIds = projectPersonnelManager.getProjectByPersonnelId(userId);
                List<String> projectIdsByuserIdList = baseMapper.queryProjectIdsByUserId(userId);
                if(null == projectIds){
                    projectIds = new ArrayList<>();
                }
                projectIds.addAll(projectIdsByuserIdList);
                // 去重
                List projectIdList=(List) projectIds.stream().distinct().collect(Collectors.toList());
                queryFilter.addFilter("ID_", projectIdList, QueryOP.IN);
            }
        }
        IPage<ProjectManagement> result =
                projectManagementDao.queryAllByPage(
                        convert2IPage(queryFilter.getPageBean()),
                        convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result);
    }


    @Override
    public List<Map<String, Object>> queryProjectMoneyGroupByType(QueryFilter<ProjectManagement> queryFilter) {
        List<QueryField> queryFields = queryFilter.getQuerys();
        boolean isParentId = true;
        boolean isDele = true;
        for (QueryField ele : queryFields) {
            if ("parent_id_".equalsIgnoreCase(ele.getProperty()) || "parentId".equalsIgnoreCase(ele.getProperty())) {
                isParentId = false;
            }
            if ("IS_DELE_".equalsIgnoreCase(ele.getProperty()) || "ISDELE".equalsIgnoreCase(ele.getProperty())) {
                isDele = false;
            }
        }
        if(isParentId){
            queryFilter.addFilter("parent_id_","root", QueryOP.EQUAL);
        }
        if(isDele){
            queryFilter.addFilter("IS_DELE_","0", QueryOP.EQUAL);
        }
        //查询项目时通过项目人员增加查询条件，只有管理员或者可以管理此项目的人员才能查询到此项目
        IUser user= ContextUtil.getCurrentUser();
        // 如果是管理员或者没有项目权限
        if(null != user){
//            String currentUserId = baseContext.getCurrentUserId();
            boolean disableAll = false;
            Integer userType = user.getUserType();
            String userId = user.getUserId();
            CommonResult<JsonNode> userNode = ucFeignService.getUserById(userId);
            if (userNode.getState()) {
                JsonNode userJsonNode = userNode.getValue();
                if(null != userJsonNode){
                    userType = userJsonNode.get("userType").asInt();
                }
            }
            // 1.先通过用户类型判断，过滤掉超级管理员之类的用户
            if(userType != null && userType !=0 && userType != 1){
                // 2.再通过角色判断，过滤掉没有对应角色权限的人员
                // 获取当前用户拥有的所有角色
                Set<String> set = new HashSet<String>();
                List<ObjectNode> list = ucFeignService.getRoleListByAccount(user.getAccount());
                if(BeanUtils.isNotEmpty(list)){
                    for (ObjectNode objectNode : list) {
                        set.add(objectNode.get("code").asText());
                    }
                }
                if(!set.contains("sysRole") && !set.contains("bld") && !set.contains("xmgl") && !set.contains("zdzh")){
                    disableAll = true;
                }
            }
            if(disableAll){
                List<String> projectIds = projectPersonnelManager.getProjectByPersonnelId(userId);
                List<String> projectIdsByuserIdList = baseMapper.queryProjectIdsByUserId(userId);
                if(null == projectIds){
                    projectIds = new ArrayList<>();
                }
                projectIds.addAll(projectIdsByuserIdList);
                // 去重
                List projectIdList=(List) projectIds.stream().distinct().collect(Collectors.toList());
                queryFilter.addFilter("ID_", projectIdList, QueryOP.IN);
            }
        }
        List<Map<String, Object>> result = projectManagementDao.queryProjectMoneyGroupByType(convert2Wrapper(queryFilter, currentModelClass()));
        return result;
    }

    @Override
    public PageList<ProjectManagement> noFilterPage(QueryFilter<ProjectManagement> queryFilter) {
        List<QueryField> queryFields = queryFilter.getQuerys();
        boolean isParentId = true;
        boolean isDele = true;
        for (QueryField ele : queryFields) {
            if ("parent_id_".equalsIgnoreCase(ele.getProperty()) || "parentId".equalsIgnoreCase(ele.getProperty())) {
                isParentId = false;
            }
            if ("IS_DELE_".equalsIgnoreCase(ele.getProperty()) || "ISDELE".equalsIgnoreCase(ele.getProperty())) {
                isDele = false;
            }
        }
        if(isParentId){
            queryFilter.addFilter("parent_id_","root", QueryOP.EQUAL);
        }
        if(isDele){
            queryFilter.addFilter("IS_DELE_","0", QueryOP.EQUAL);
        }
        IPage<ProjectManagement> result =
                projectManagementDao.queryAllByPage(
                        convert2IPage(queryFilter.getPageBean()),
                        convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result);
    }

    @Override
    public List<ProjectManagement> queryList(QueryFilter<ProjectManagement> queryFilter) {
        queryFilter.getPageBean().setPageSize(-1);
        List<QueryField> queryFields = queryFilter.getQuerys();
        boolean isParentId = true;
        boolean isDele = true;
        for (QueryField ele : queryFields) {
            if ("parent_id_".equalsIgnoreCase(ele.getProperty()) || "parentId".equalsIgnoreCase(ele.getProperty())) {
                isParentId = false;
            }
            if ("IS_DELE_".equalsIgnoreCase(ele.getProperty()) || "ISDELE".equalsIgnoreCase(ele.getProperty())) {
                isDele = false;
            }
        }
        if(isParentId){
            queryFilter.addFilter("parent_id_","root", QueryOP.EQUAL);
        }
        if(isDele){
            queryFilter.addFilter("IS_DELE_","0", QueryOP.EQUAL);
        }
        IPage<ProjectManagement> result =
                projectManagementDao.queryAllByPage(
                        convert2IPage(queryFilter.getPageBean()),
                        convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result).getRows();
    }

    @Override
    public int setCurrentProject(String id) {
        projectManagementDao.resetCurrentProject();// 重置所有当前项目标记为0
        ProjectManagement recoded = projectManagementDao.selectById(id);
        recoded.setCurrentProject(1);// 标记当前记录为当前对象
        return projectManagementDao.updateById(recoded);
    }

    @Override
    public boolean hasCurrentProject() {
        QueryWrapper<ProjectManagement> wrapper = new QueryWrapper<>();
        wrapper.eq("CURRENT_PROJECT_",1).eq("IS_DELE_","0");
        return projectManagementDao.selectCount(wrapper)==1;
    }

    @Override
    public void importExcelData(MultipartFile file) {
        // 获取字典
        List<DictModel> projectModel = sdm.queryDictListItemsByCode("xmgl-jsms");
        List<DictModel> projectType = sdm.queryDictListItemsByCode("xmgl-xmlx");
        List<DictModel> projectNature = sdm.queryDictListItemsByCode("xmgl-gcsx");
        List<DictModel> projectApprovalAuthority = sdm.queryDictListItemsByCode("xmgl-lxspjg");
        List<DictModel> socialAuditType = sdm.queryDictListItemsByCode("xmgl-shsjfs");
        List<DictModel> stateAuditOffice = sdm.queryDictListItemsByCode("xmgl-gjsjjg");

        try {
            //1、获取文件输入流
            InputStream inputStream = file.getInputStream();
            //2、获取Excel工作簿对象
            Workbook workbook = WorkbookFactory.create(inputStream);
            //3、得到Excel工作表对象
            Sheet sheetAt = workbook.getSheetAt(0);
            //4、循环读取表格数据
            for (Row row : sheetAt) {
                //首行（表头）不读取
                if (row.getRowNum() == 0) {
                    continue;
                }
                //读取当前行中单元格数据并赋值到对象，索引从0开始
                ProjectManagement data = new ProjectManagement();
                //处理单元格数据可能为空 getCell将会抛出空指针的问题
                Cell cell = row.createCell(0);
                String s = cell.getStringCellValue();
                data.setProjectName(null==row.getCell(0)?row.createCell(0).getStringCellValue():row.getCell(0).getStringCellValue());
                data.setProjectCode(null==row.getCell(1)?row.createCell(1).getStringCellValue():row.getCell(1).getStringCellValue());

                data.setProjectMoney(null==row.getCell(2)?BigDecimal.valueOf(row.createCell(2).getNumericCellValue()):BigDecimal.valueOf(row.getCell(2).getNumericCellValue()));
                data.setProjectModel(BizUtils.getDicCodeByValue(projectModel,null==row.getCell(3)?row.createCell(3).getStringCellValue() :row.getCell(3).getStringCellValue()));
                String a = null==row.getCell(4)? row.createCell(4).getStringCellValue():row.getCell(4).getStringCellValue();
//                data.setProjectType(BizUtils.getDicCodeByValue_Int(projectType,a));
//                data.setProjectNature(BizUtils.getDicCodeByValue_Int(projectNature,null==row.getCell(6)? row.createCell(5).getStringCellValue(): row.getCell(5).getStringCellValue()));
                data.setProjectManager(null==row.getCell(6)?row.createCell(6).getStringCellValue():row.getCell(6).getStringCellValue());
                data.setProjectAddress(null==row.getCell(7)?row.createCell(7).getStringCellValue():row.getCell(7).getStringCellValue());
                data.setProjectContent(null==row.getCell(8)?row.createCell(8).getStringCellValue():row.getCell(8).getStringCellValue());
//                data.setProjectApprovalAuthority(BizUtils.getDicCodeByValue_Int(projectApprovalAuthority,null==row.getCell(9)? row.createCell(9).getStringCellValue(): row.getCell(9).getStringCellValue()));
                data.setFeasibilityStudyEstimate(null==row.getCell(10)?BigDecimal.valueOf(row.createCell(10).getNumericCellValue()):BigDecimal.valueOf(row.getCell(10).getNumericCellValue()));
                data.setPreliminaryEstimate(null==row.getCell(11)?BigDecimal.valueOf(row.createCell(11).getNumericCellValue()):BigDecimal.valueOf(row.getCell(11).getNumericCellValue()));
                data.setCommencementTime(null==row.getCell(12)?row.createCell(12).getDateCellValue():row.getCell(12).getDateCellValue());
                data.setCompletionTime(null==row.getCell(13)?row.createCell(13).getDateCellValue():row.getCell(13).getDateCellValue());
                data.setCompletionAcceptanceTime(null==row.getCell(14)?row.createCell(14).getDateCellValue():row.getCell(14).getDateCellValue());
                data.setWarrantyExpirationTime(null==row.getCell(15)?row.createCell(15).getDateCellValue():row.getCell(15).getDateCellValue());
                data.setOwnerUnit(null==row.getCell(16)?row.createCell(16).getStringCellValue():row.getCell(16).getStringCellValue());
                data.setResponsibleUnit(null==row.getCell(17)?row.createCell(17).getStringCellValue():row.getCell(17).getStringCellValue());
                data.setGeologicalProspectingUnit(null==row.getCell(18)?row.createCell(18).getStringCellValue():row.getCell(18).getStringCellValue());
                data.setDesignUnit(null==row.getCell(19)?row.createCell(19).getStringCellValue():row.getCell(19).getStringCellValue());
                data.setSupervisorUnit(null==row.getCell(20)?row.createCell(20).getStringCellValue():row.getCell(20).getStringCellValue());
                data.setConstructUnit(null==row.getCell(21)?row.createCell(21).getStringCellValue():row.getCell(21).getStringCellValue());
                data.setSubmittedSettlementAmount(null==row.getCell(22)?row.createCell(22).getStringCellValue():row.getCell(22).getStringCellValue());
                data.setInternalApprovedSettlementAmount(null==row.getCell(23)?row.createCell(23).getStringCellValue():row.getCell(23).getStringCellValue());
//                data.setSocialAuditType(BizUtils.getDicCodeByValue_Int(socialAuditType,null==row.getCell(24)? row.createCell(24).getStringCellValue(): row.getCell(24).getStringCellValue()));
                data.setSocialAuditIntermediary(null==row.getCell(25)?row.createCell(25).getStringCellValue():row.getCell(25).getStringCellValue());
                data.setSocialAuditMoney(null==row.getCell(26)?row.createCell(26).getStringCellValue():row.getCell(26).getStringCellValue());
                data.setStateAuditOffice(BizUtils.getDicCodeByValue(stateAuditOffice,null==row.getCell(27)? row.createCell(27).getStringCellValue(): row.getCell(27).getStringCellValue()));
                data.setStateAuditMoney(null==row.getCell(28)?row.createCell(28).getStringCellValue():row.getCell(28).getStringCellValue());
                data.setFinalAccountAuditMechanism(null==row.getCell(29)?row.createCell(29).getStringCellValue():row.getCell(29).getStringCellValue());
                data.setFinalAccountAuditMoney(null==row.getCell(30)?row.createCell(30).getStringCellValue():row.getCell(30).getStringCellValue());
                data.setAccumulatedProjectPayment(null==row.getCell(31)?BigDecimal.valueOf(row.createCell(31).getNumericCellValue()):BigDecimal.valueOf(row.getCell(31).getNumericCellValue()));
                data.setProjectStatusValue(null==row.getCell(32)?row.createCell(32).getStringCellValue():row.getCell(32).getStringCellValue());
                data.setContractSigning(null==row.getCell(33)?row.createCell(33).getStringCellValue():row.getCell(33).getStringCellValue());
                data.setContractAmount(null==row.getCell(34)? BigDecimal.valueOf(row.createCell(34).getNumericCellValue()):BigDecimal.valueOf(row.getCell(34).getNumericCellValue()));
                data.setConstructionProgress(null==row.getCell(35)?row.createCell(35).getStringCellValue():row.getCell(35).getStringCellValue());
                data.setSettlementInfo(null==row.getCell(36)?row.createCell(36).getStringCellValue():row.getCell(36).getStringCellValue());
                data.setRemarks(null==row.getCell(37)?row.createCell(37).getStringCellValue():row.getCell(37).getStringCellValue());
                NumberFormat nf  =  NumberFormat.getPercentInstance();
                nf.setMinimumFractionDigits( 2 );
//                try{
//                    data.setProportionContractAmount(String.valueOf(nf.format(Double.valueOf(data.getAccumulatedProjectPayment()) / data.getContractAmount().doubleValue())));
//                }catch(Exception e){
//                    data.setProportionContractAmount("0");
//                }
//                try{
//                    data.setProportionContractAmount(String.valueOf(Double.valueOf(data.getAccumulatedProjectPayment()) / Double.valueOf(data.getSocialAuditMoney())));
//                }catch(Exception e){
//                    data.setSocialAuditMoneyAmount("0");
//                }
                savePm(data);
                // 在这里关联所有用户到人员表，将会执行大量SQl语句，包括自动填充字段的查询SQL，取消？
                 ppm.linkUsers(data.getId());
            }
            //5、关闭流
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportDatatoExcel(QueryFilter<ProjectManagement> queryFilter, HttpServletResponse response) throws IOException {
        String fileName = "项目信息-导出结果";
        // 条件中去掉分页
        PageBean pageBean = queryFilter.getPageBean();
        pageBean.setPageSize(-1);
        pageBean.setShowTotal(false);
        // 按建立时间倒序
        List<FieldSort> sorts = Lists.newArrayList();
        sorts.add(new FieldSort("PROJECT_TYPE_",Direction.ASC));
        sorts.add(new FieldSort("PROJECT_MONEY_",Direction.DESC));
        queryFilter.setSorter(sorts);
        // 获取字典
        List<DictModel> projectModel = sdm.queryDictListItemsByCode("xmgl-jsms");
        List<DictModel> projectType = sdm.queryDictListItemsByCode("xmgl-xmlx");
        List<DictModel> projectNature = sdm.queryDictListItemsByCode("xmgl-gcsx");
        List<DictModel> projectApprovalAuthority = sdm.queryDictListItemsByCode("xmgl-lxspjg");
        List<DictModel> socialAuditType = sdm.queryDictListItemsByCode("xmgl-shsjfs");
        List<DictModel> stateAuditOffice = sdm.queryDictListItemsByCode("xmgl-gjsjjg");
        List<DictModel> projectStatus = sdm.queryDictListItemsByCode("xmgl-xmzt");

        queryFilter.addFilter("IS_DELE_","0", QueryOP.EQUAL);
        List<ProjectManagement> data = queryAllByPage(queryFilter).getRows();
        if(null==data||data.size()==0){
            throw new RuntimeException("没有要导出的的数据！");
        }

        // 翻译字典
        for(ProjectManagement ele : data){
            ele.setProjectModel(BizUtils.getDicValueByCode(projectModel, ele.getProjectModel()));
            ele.setProjectType(BizUtils.getDicValueByCode(projectType, ele.getProjectType()));
            ele.setProjectNature(BizUtils.getDicValueByCode(projectNature, ele.getProjectNature()));
            ele.setProjectApprovalAuthority(BizUtils.getDicValueByCode(projectApprovalAuthority, ele.getProjectApprovalAuthority()));
            ele.setSocialAuditType(BizUtils.getDicValueByCode(socialAuditType, ele.getSocialAuditType()));
            ele.setStateAuditOffice(BizUtils.getDicValueByCode(stateAuditOffice, ele.getStateAuditOffice()));
            ele.setProjectStatus(BizUtils.getDicValueByCode(projectStatus, ele.getProjectStatus()));
            // 这是原来的，是从月报中统计的进度以及累计总投资，新的总投资将从工程支付中统计
            ProgressManageReport overvieByProjectId = progressManageReportManager.getProjectOvervieByProjectId(ele.getId());
            if(overvieByProjectId != null){
                // 形象进度 weeklyMouthlyWork
                ele.setConstructionProgress(overvieByProjectId.getWeeklyMouthlyWork());
            }
            // 从工程支付中查询累计总投资
            BigDecimal projectOvervie = progressManageManager.geTamountAppropriatedTotalByProjectId(ele.getId());
            if (projectOvervie!=null){
                BigDecimal bigDecimal = projectOvervie.divide(new BigDecimal(10000)).stripTrailingZeros().setScale(0, BigDecimal.ROUND_HALF_DOWN);
                ele.setAccumulatedProjectPayment(bigDecimal);
            }
            if(null != ele.getProjectMoney()){
                ele.setProjectMoney(new BigDecimal(ele.getProjectMoney().stripTrailingZeros().toPlainString()));
            }
            ProjectEstablishment projectEstablishment = projectEstablishmentManager.getOne(new QueryWrapper<ProjectEstablishment>().eq("IS_DELE_","0").eq("PROJECT_ID_", ele.getId()).last("limit 1"));
            if(projectEstablishment!=null){
                ele.setConstructionProgress(projectEstablishment.getEstablishmentScale());
            }
        }
        // EasyPoi 导出参数、样式、表格格式设置
        ExportParams exportParams = BizUtils.getExportParams(fileName);
        fileName += ".xlsx";

        // 导出下载excel文件
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ProjectManagement.class, data);
        ExcelUtil.downloadExcel(workbook, fileName, response);
    }

    @Override
    public void updateHasChildrenByParentId(String pid) {
        if(StringUtils.isBlank(pid)){
            return;
        }
        QueryWrapper<ProjectManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PARENT_ID_",pid);
        queryWrapper.eq("IS_DELE_","0");
        Integer count = this.projectManagementDao.selectCount(queryWrapper);
        if (count > 0){
            UpdateWrapper<ProjectManagement> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("ID_",pid);
            updateWrapper.set("HAS_CHILDREN_","true");
            this.projectManagementDao.update(null,updateWrapper);
        }else {
            UpdateWrapper<ProjectManagement> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("ID_",pid);
            updateWrapper.set("HAS_CHILDREN_","false");
            this.projectManagementDao.update(null,updateWrapper);
        }


    }

    @Override
    public void updateParentIdByIds(String parentId, String ids) {
        if(StringUtils.isBlank(ids)){
            return;
        }
        UpdateWrapper<ProjectManagement> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("ID_", Arrays.asList(ids.split(",")));
        updateWrapper.set("PARENT_ID_",parentId);
        this.projectManagementDao.update(null,updateWrapper);

    }

    @Override
    public void splitItems(String ids) {
        if(StringUtils.isNotBlank(ids)){
            List<String> list = Arrays.asList(ids.split(","));
            for(String id : list){
                ProjectManagement projectManagement = baseMapper.selectById(id);
                String parentId = projectManagement.getParentId();
                if(!"root".equalsIgnoreCase(parentId)){
                    // 修改项目父id为root
                    updateParentIdByIds("root", ids);
                    // x修改是hasChildren属性
                    updateHasChildrenByParentId(parentId);
                }
            }
        }

    }

    @Override
    public void updateCostConsultationById(String id, String costConsultation) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.set("COST_CONSULTATION_", costConsultation);
        updateWrapper.eq("ID_", id);
        this.update(updateWrapper);
    }

    @Override
    public void updateLandCostById(ProjectLandCostVo projectLandCostVo) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.set("LAND_AREA_", projectLandCostVo.getLandArea());
        updateWrapper.set("LAND_UNIT_", projectLandCostVo.getLandUnit());
        updateWrapper.set("LAND_PRICE_", projectLandCostVo.getLandPrice());
        updateWrapper.set("LAND_TOTAL_PRICE_", projectLandCostVo.getLandTotalPrice());
        updateWrapper.eq("ID_", projectLandCostVo.getId());
        this.update(updateWrapper);
    }

    @Override
    public void mergeItems(MergeItemsVo mergeItemsVo){
        ProjectManagement projectManagement = mergeItemsVo.getProjectManagement();
        String projectIds = mergeItemsVo.getProjectIds();
        Assert.notNull(projectIds, "合并项目ID不能为空！");
        String parentId = mergeItemsVo.getParentId();
        if(StringUtils.isNotBlank(parentId) ){
            List<String> list = new ArrayList<>(Arrays.asList(projectIds.split(",")));
//            list.remove(parentId);
            List parentList = new ArrayList<>(1);
            parentList.add(parentId);
            list.removeAll(parentList);
            projectIds = StringUtils.join(list, ",");
            updateParentIdByIds(parentId, projectIds);
            // 合并项目资料
            mergeItemsDocment(projectIds, parentId);
        }else {
            Assert.notNull(projectManagement, "合并为新项目时项目信息不能为空");
            projectManagement.setParentId("root");
            projectManagement.setIsDele("0");
            projectManagement.setValidFlag(1);
            List<ProjectManagement> subProjectManagementList = this.listByIds(Arrays.asList(projectIds.split(",")));
            if(null != subProjectManagementList && subProjectManagementList.size() > 0){
                ProjectManagement subManagement = subProjectManagementList.get(0);
                //管理者
                String projectManager = projectManagement.getProjectManager();
                if(StringUtils.isBlank(projectManager) || "管理员".equalsIgnoreCase(projectManager)){
                    projectManagement.setProjectManager(subManagement.getProjectManager());
                }
                String projectManagerId1 = projectManagement.getProjectManagerId();
                if(StringUtils.isBlank(projectManagerId1) || "1".equalsIgnoreCase(projectManagerId1)){
                    projectManagement.setProjectManagerId(subManagement.getProjectManagerId());
                }
                //建设时间
                Date commencementTime = projectManagement.getCommencementTime();
                if(null == commencementTime){
                    projectManagement.setCommencementTime(subManagement.getCommencementTime());
                }
                // 总投资
                BigDecimal projectMoney = projectManagement.getProjectMoney();
                if(null != projectMoney){
                    BigDecimal total = BigDecimal.ZERO;
                    for (ProjectManagement p : subProjectManagementList){
                        if (null != p && null != p.getProjectMoney()){
                            total = total.add(p.getProjectMoney());
                        }
                    }
                    projectManagement.setProjectMoney(total.stripTrailingZeros());
                }
            }

            projectManagementDao.insert(projectManagement);
            String projectManagerId = projectManagement.getProjectManagerId();
            //新建项目时将管理者放入到人员中去
            projectPersonnelManager.linkUsersByProjectManager(projectManagement.getId(), projectManagerId);
            updateParentIdByIds(projectManagement.getId(), projectIds);
            // 合并项目资料，并更新项目状态
            mergeItemsDocment(projectIds, projectManagement.getId());
        }
        updateHasChildrenByParentId(parentId);
    }

    /**
     * 将多个项目资料合并至新项目
     * @param oldProjectIds 需要合并的项目id，多个使用逗号隔开
     * @param newProjectId 合并后的项目id
     */
    public void mergeItemsDocment(String oldProjectIds, String newProjectId){
        // 合并所有资料
        // 1.决策依据合并
        decisionBasisManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 2.立项备案合并
        projectEstablishmentManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 3.可研批复合并
        feasibilityStudyReplyManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 4.土地手续-选址合并
        planningSelectionSiteManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 5.土地手续-土地合并
        planningSelectionLandManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 6.土地手续-用地合并
        planningUseLandManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 7.规划合并（包括，专项和规划）
        planningEngineeringManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 8.初步设计合并
        preliminaryDesignManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 9.概算批复合并
        estimateManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 10.施工图设计合并
        constructionDrawingManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 11.施工图审查合并
        constructionDrawingDesignManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 12.清单限价-编制合并
        biddingPriceLimitManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 13.施清单限价-审核合并
        biddingPriceExamineManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 14.招投标合并
        biddingManagementManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 15.合同合并
        contractManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 16.施工许可合并
        constructionPermitManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 17.施工管理-安全文明施工-安全合并
        securityManageManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 18.施工管理-安全文明施工-环保合并
        accessoryManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 19.施工管理-安全文明施工-其他合并
        progressManageEpidemicControlManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 20.施工管理-质量管理-质量巡检合并
        qualityInspectionManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 21.施工管理-质量管理-质量整改合并
        qualityRectificationManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 22.施工管理-进度管理-工程月报合并
        progressManageReportManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 22.施工管理-进度管理-工程支付合并
        progressManageManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 22.施工管理-变更合并
        changeManagementManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 22.施工管理-技术资料合并
        technicalInformationManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 22.施工管理-经济资料合并（为文件，只有有文件的地方合并过一次就不再需要合并）
        // 23.单位工程验收合并
        unitProjectAcceptanceManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 22.预验收合并
        preAcceptanceManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 22.竣工验收-专项验收合并
        recordAcceptanceSpecialManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 22.竣工验收-联合竣工备案合并
        recordAcceptanceManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 22.移交合并
        acceptanceFinalTransferManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 22.结算合并
        acceptanceSettlementManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 22.决算合并
        acceptanceFinalAccountsManager.updateProjectIdByProiectId(oldProjectIds, newProjectId);
        // 更新项目状态
        List<ProjectManagement> projectManagementList = this.baseMapper.selectBatchIds(Arrays.asList(oldProjectIds.split(",")));
        if(null != projectManagementList && projectManagementList.size() > 0){
            for (ProjectManagement pm : projectManagementList){
                updateStatusById(newProjectId, Integer.valueOf(pm.getProjectStatus()));
            }
        }
    }

    //  菜单资源国际化
    private List<SysMenu> i18nSysMenu(List<SysMenu> lists) {
        List<String> i18nKey = new ArrayList<String>();
        for (SysMenu sysMenu : lists) {
            i18nKey.add(sysMenu.getAlias());
        }
        Map<String, String> messages = I18nUtil.getMessages(i18nKey, LocaleContextHolder.getLocale());
        for (SysMenu sysMenu : lists) {
            String key = sysMenu.getAlias();
            if (messages.containsKey(key) && StringUtil.isNotEmpty(messages.get(key)) && !key.equals(messages.get(key))) {
                sysMenu.setName(messages.get(key));
            }
        }
        return lists;
    }
}

