package com.ozs.plan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ozs.base.domain.BaseAgency;
import com.ozs.base.service.BaseAgencyService;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.entity.SysDept;
import com.ozs.common.core.domain.entity.SysDictData;
import com.ozs.common.core.domain.entity.SysRole;
import com.ozs.common.core.domain.entity.SysUser;
import com.ozs.common.core.domain.model.LoginUser;
import com.ozs.common.enums.*;
import com.ozs.common.exception.ServiceException;
import com.ozs.common.utils.SecurityUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.bean.BeanUtils;
import com.ozs.home.domain.vo.HomeToDoQueryResVo;
import com.ozs.plan.doman.PlanQuarter;
import com.ozs.plan.doman.PlanYears;
import com.ozs.plan.doman.ProvisionalPlan;
import com.ozs.plan.doman.vo.requestVo.PlanYearsStandardVo;
import com.ozs.plan.doman.vo.responseVo.PlanQuarterResponseVo;
import com.ozs.plan.doman.vo.responseVo.PlanYearsResponseVo;
import com.ozs.plan.mapper.PlanQuarterMapper;
import com.ozs.plan.mapper.PlanYearsMapper;
import com.ozs.plan.mapper.ProvisionalPlanMapper;
import com.ozs.plan.service.PlanYearsService;
import com.ozs.pm.doman.*;
import com.ozs.pm.doman.vo.requestVo.PmDemandReqVo;
import com.ozs.pm.doman.vo.responseVo.*;
import com.ozs.pm.mapper.PmDemandMapper;
import com.ozs.pm.service.*;
import com.ozs.system.domain.SysFileInfo;
import com.ozs.system.domain.SysFileRef;
import com.ozs.system.domain.vo.responseVo.SysDeptResponseVo;
import com.ozs.system.mapper.SysDeptMapper;
import com.ozs.system.mapper.SysFileRefMapper;
import com.ozs.system.mapper.SysRoleMapper;
import com.ozs.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author buzhanyi
 */
@Service
@Slf4j
public class PlanYearsServiceImpl extends ServiceImpl<PlanYearsMapper, PlanYears> implements PlanYearsService {

    @Autowired
    PlanYearsMapper planYearsMapper;
    @Autowired
    private PlanQuarterMapper planQuarterMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private SysFileRefMapper sysFileRefMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private SysFileService fileService;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private PmDemandMapper pmDemandMapper;
    @Autowired
    private PlanQuarterServiceImpl quartzServiceImpl;
    @Autowired
    private IPmDemandService demandService;
    @Autowired
    private ProvisionalPlanMapper provisionalPlanMapper;
    @Autowired
    private IPmDemandService pmDemandService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private BaseAgencyService baseAgencyService;
    @Autowired
    private PmBookBuildingService pmBookBuildingService;
    @Autowired
    private PmReleaseAnnouncementService pmReleaseAnnouncementService;
    @Autowired
    private PmDemandExpertRefService pmDemandExpertRefService;
    @Autowired
    private PmBidOpeningService pmBidOpeningService;
    @Autowired
    private PmBidWinningService pmBidWinningService;
    @Autowired
    private PmBidFailureService pmBidFailureService;
    @Autowired
    private PmContractInfoService pmContractInfoService;
    @Autowired
    private PmProjectConstructionService pmProjectConstructionService;
    @Autowired
    private SysFileRefService sysFileRefService;
    @Autowired
    private PmAuditDeptRefService pmAuditDeptRefService;

    @Override
    public List<PlanYearsResponseVo> selectPlanYearsListEXP(PlanYearsStandardVo vo, LoginUser loginUser) {
        List<PlanYears> list = new ArrayList<>();
        List<PlanYearsResponseVo> planYearsList = new ArrayList<>();
        try {
            int num = 1;
            int size = 200;
            while (size == 200) {
                LambdaQueryWrapper<PlanYears> lw = new LambdaQueryWrapper<PlanYears>();
                if (!loginUser.getUserId().equals(Long.valueOf("1"))) {
                    lw.eq(PlanYears::getPurchaseDeptId, loginUser.getDeptId());
                }
                if (!ObjectUtils.isEmpty(vo.getProjectName())) {
                    lw.like(PlanYears::getProjectName, vo.getProjectName());
                }
                if (!ObjectUtils.isEmpty(vo.getPurchaseServices())) {
                    lw.eq(PlanYears::getPurchaseServices, vo.getPurchaseServices());
                }
                if (!ObjectUtils.isEmpty(vo.getIsExcess())) {
                    lw.eq(PlanYears::getIsExcess, vo.getIsExcess());
                }
                if (!ObjectUtils.isEmpty(vo.getProjectStatus())) {
                    lw.eq(PlanYears::getProjectStatus, vo.getProjectStatus());
                }
                if (!ObjectUtils.isEmpty(vo.getBeginTime())) {
                    lw.ge(PlanYears::getPlanDemandSubTime, vo.getBeginTime());
                }
                if (!ObjectUtils.isEmpty(vo.getEndTime())) {
                    lw.le(PlanYears::getPlanDemandSubTime, vo.getEndTime());
                }
                lw.eq(PlanYears::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
                Page<PlanYears> page = planYearsMapper.selectPage(new Page<PlanYears>(num, size, false), lw);
                list.addAll(page.getRecords());
                size = page.getRecords().size();
                num++;
            }
            planYearsList = changeTo(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return planYearsList;
    }

    @Override
    public List<PlanYearsResponseVo> selectPlanYearsExamineListEXP(PlanYearsStandardVo vo, LoginUser loginUser) {
        List<PlanYears> list = new ArrayList<>();
        List<PlanYearsResponseVo> planYearsList = new ArrayList<>();
        try {
            int num = 1;
            int size = 200;
            while (size == 200) {
                LambdaQueryWrapper<PlanYears> lw = new LambdaQueryWrapper<PlanYears>();
                if (!loginUser.getUserId().equals(Long.valueOf("1"))) {
                    lw.eq(PlanYears::getPurchaseDeptId, loginUser.getDeptId());
                }
                if (!ObjectUtils.isEmpty(vo.getProjectName())) {
                    lw.like(PlanYears::getProjectName, vo.getProjectName());
                }
                if (!ObjectUtils.isEmpty(vo.getPurchaseServices())) {
                    lw.eq(PlanYears::getPurchaseServices, vo.getPurchaseServices());
                }
                if (!ObjectUtils.isEmpty(vo.getIsExcess())) {
                    lw.eq(PlanYears::getIsExcess, vo.getIsExcess());
                }
                if (!ObjectUtils.isEmpty(vo.getProjectStatus())) {
                    lw.eq(PlanYears::getProjectStatus, vo.getProjectStatus());
                } else {
                    lw.in(PlanYears::getProjectStatus, "1,3");
                }
                if (!ObjectUtils.isEmpty(vo.getBeginTime())) {
                    lw.ge(PlanYears::getPlanDemandSubTime, vo.getBeginTime());
                }
                if (!ObjectUtils.isEmpty(vo.getEndTime())) {
                    lw.le(PlanYears::getPlanDemandSubTime, vo.getEndTime());
                }
                lw.eq(PlanYears::getDelFlay, DataIsDelete.DataNOTDelete);
                Page<PlanYears> page = planYearsMapper.selectPage(new Page<PlanYears>(num, size, false), lw);
                list.addAll(page.getRecords());
                size = page.getRecords().size();
                num++;
            }
            planYearsList = changeTo(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return planYearsList;
    }

    @Transactional
    @Override
    public AjaxResult insertPlanYears(PlanYearsStandardVo yearsStandardVo) {
        if (planYearsMapper.countProjectName(yearsStandardVo.getProjectName()) > 0) {
            return AjaxResult.error("该项目名称已经存在");
        }
        //默认未超额
        if (ObjectUtils.isEmpty(yearsStandardVo.getIsExcess())) {
            yearsStandardVo.setIsExcess("0");
        }
        PlanYears ofYears = new PlanYears();
        try {
            BeanUtils.copyProperties(yearsStandardVo, ofYears);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断是否为超额计划
        //ofYears.setIsExcess(deptService.isExcessOrNo(ofYears.getProjectType(), ofYears.getEvaluation(), Long.valueOf(ofYears.getPurchaseDeptId())));
        ofYears.setProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
        ofYears.setCreateTime(new Date());
        planYearsMapper.insertPlanYears(ofYears);
        log.info("id:{}", ofYears.getPlanYearId());
        List<SysFileRef> sysFileRefs = yearsStandardVo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefs)) {
            for (SysFileRef ref : sysFileRefs) {
                ref.setRedId(ofYears.getPlanYearId());
                ref.setType(SysFileRefEnum.PLAN_YEAR.getType());
                ref.setCreated(ofYears.getCreated());
                ref.setCreateTime(new Date());
                ref.setUpdated(ofYears.getCreated());
                ref.setUpdateTime(new Date());
                sysFileRefMapper.insert(ref);
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deletePlanYearsByIds(Long[] planIds) {
        planYearsMapper.deletePlanYearsByIds(planIds);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deletePlanYearsById(Long planId) {
        planYearsMapper.deletePlanYearsById(planId);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult view(PlanYearsStandardVo yearsStandardVo) {

        PlanYearsResponseVo responseVo = new PlanYearsResponseVo();
        PlanYears byId = planYearsMapper.getById(yearsStandardVo.getPlanYearId());
        byId.getPlanYearId();
        if (byId == null) {
            return AjaxResult.error("数据查询失败");
        }
        SysDeptResponseVo sysDeptResponseVo = (SysDeptResponseVo) deptService.selectDeptById(Long.valueOf(byId.getPurchaseDeptId())).get("sysDept");
        byId.setPurchaseDeptName(sysDeptResponseVo.getDeptName());
        LambdaQueryWrapper<SysFileRef> lw = new LambdaQueryWrapper<>();
        lw.eq(SysFileRef::getRedId, yearsStandardVo.getPlanYearId());
        lw.in(SysFileRef::getType, Arrays.asList(SysFileRefEnum.PLAN_YEAR.getType(), SysFileRefEnum.PLAN_YEAR_EXAMINE.getType()));
        List<SysFileRef> fileRefs = sysFileRefMapper.selectList(lw);
        List<SysFileInfo> fileInfos = new ArrayList<>();
        BeanUtils.copyProperties(byId, responseVo);
        if (!ObjectUtils.isEmpty(fileRefs)) {
            for (SysFileRef ref : fileRefs) {
                SysFileInfo fileInfo = fileService.getById(ref.getFileId());
                fileInfos.add(fileInfo);
            }
            responseVo.setFileInfos(fileInfos);
        }
        return AjaxResult.success(responseVo);
    }

    @Transactional
    @Override
    public AjaxResult update(PlanYearsStandardVo yearsStandardVo) {
        if (planYearsMapper.countProjectNameOther(yearsStandardVo.getProjectName(), String.valueOf(yearsStandardVo.getPlanYearId())) > 0) {
            return AjaxResult.error("该项目名称已经存在");
        }
        //默认未超额
        if (ObjectUtils.isEmpty(yearsStandardVo.getIsExcess())) {
            yearsStandardVo.setIsExcess("0");
        }
        PlanYears ofYears = new PlanYears();
        try {
            BeanUtils.copyProperties(yearsStandardVo, ofYears);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //ofYears.setIsExcess(deptService.isExcessOrNo(ofYears.getProjectType(), ofYears.getEvaluation(), Long.valueOf(ofYears.getPurchaseDeptId())));
        ofYears.setUpdateTime(new Date());
        planYearsMapper.updateInfoById(ofYears);
        List<SysFileRef> sysFileRefs = yearsStandardVo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefs)) {
            // 删关联
            LambdaQueryWrapper<SysFileRef> lw = new LambdaQueryWrapper<>();
            lw.eq(SysFileRef::getRedId, ofYears.getPlanYearId());
            lw.eq(SysFileRef::getType, SysFileRefEnum.PLAN_YEAR.getType());
            sysFileRefMapper.delete(lw);
            for (SysFileRef ref : sysFileRefs) {
                ref.setRedId(ofYears.getPlanYearId());
                ref.setType(SysFileRefEnum.PLAN_YEAR.getType());
                ref.setCreated(yearsStandardVo.getUpdated());
                ref.setCreateTime(new Date());
                ref.setUpdated(yearsStandardVo.getUpdated());
                ref.setUpdateTime(new Date());
                sysFileRefMapper.insert(ref);
            }
        }
        return AjaxResult.success();
    }

    //是否在提报时间内
    public Boolean isBetweenValue(PlanYears planYear) {
        //获取年度计划提报时间的阈值
        List<SysDictData> supTime = dictTypeService.selectDictDataByType("sys_annual_plan");
        HashMap<String, String> thresholdMap = new LinkedHashMap<>();
        //年度提报时间的阈值
        for (SysDictData dictData : supTime) {
            //    字段名称----阈值
            thresholdMap.put(dictData.getDictLabel(), dictData.getDictValue());
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date subTime = planYear.getPlanDemandSubTime();
        try {
            Date thresholdTimeStart = dateFormat.parse(thresholdMap.get("起止时间开始"));
            Date thresholdTimeEnd = dateFormat.parse(thresholdMap.get("起止时间结束"));
            ;
            if (!ObjectUtils.isEmpty(thresholdTimeStart) && !ObjectUtils.isEmpty(thresholdTimeEnd)) {
                if (subTime.before(thresholdTimeStart) || subTime.after(thresholdTimeEnd)) {
                    return false;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return true;
    }

    @Transactional
    @Override
    public String importPlanYears(List<PlanYearsStandardVo> planYears, boolean isUpdateSupport, LoginUser loginUser) {
        if (StringUtils.isNull(planYears) || planYears.size() == 0) {
            throw new ServiceException("导入年度计划数据不能为空！");
        }
        List<PlanYears> plans = new ArrayList<>();
        for (PlanYearsStandardVo yearsStandardVo : planYears) {
            PlanYears ofYears = new PlanYears();
            BeanUtils.copyProperties(yearsStandardVo, ofYears);
            ofYears.setPurchaseDeptName(yearsStandardVo.getPurchaseDeptId());
            plans.add(ofYears);
        }
        HashMap<String, HashMap<String, String>> planEnums = dictTypeService.getAboutEnums();
        HashMap<String, String> projectTypesMap = planEnums.get("projectTypes");
        HashMap<String, String> planPurchaseModesMap = planEnums.get("planPurchaseModes");
        HashMap<String, String> projectAttributes = planEnums.get("projectAttributes");

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //deptService
        for (PlanYears ofYear : plans) {
            try {
                //验证项目名称是否重复导入
                //将录入信息中的值更改为要保存的数据
                if (planYearsMapper.countProjectName(ofYear.getProjectName()) == 0) {
                    //采购单位
                    SysDept info = deptMapper.checkDeptNameOnlyOne(ofYear.getPurchaseDeptName());
                    if (!ObjectUtils.isEmpty(info)) {
                        ofYear.setPurchaseDeptId(String.valueOf(info.getDeptId()));
                    } else {
                        ++failureNum;
                        failureMsg.append("*" + failureNum + "*采购单位“" + ofYear.getPurchaseDeptName() + "”不存在");
                    }
                    ofYear.setProjectType(projectTypesMap.get(ofYear.getProjectType()));
                    ofYear.setProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
                    ofYear.setPurchaseMode(planPurchaseModesMap.get(ofYear.getPurchaseMode()));
                    //项目属性是多选字段
                    StringBuilder builder = new StringBuilder();
                    if (ofYear.getProjectAttr().contains(",")) {
                        String[] split = ofYear.getProjectAttr().split(",");
                        for (String s : split) {
                            if (!ofYear.getProjectAttr().endsWith(s)) {
                                builder.append(projectAttributes.get(s) + ",");
                            } else {
                                builder.append(projectAttributes.get(s));
                            }
                        }
                    } else {
                        builder.append(projectAttributes.get(ofYear.getProjectAttr()));
                    }
                    ofYear.setProjectAttr(builder.toString());
                    ofYear.setIsExcess(deptService.isExcessOrNo(ofYear.getProjectType(), ofYear.getEvaluation(), Long.valueOf(ofYear.getPurchaseDeptId())));
                    ofYear.setCreated(String.valueOf(loginUser.getUserId()));
                    ofYear.setCreateTime(new Date());
                    planYearsMapper.insertPlanYears(ofYear);
                    successNum++;
                    successMsg.append("*" + successNum + "、项目 " + ofYear.getProjectName() + " 导入成功!");
                } else {
                    failureNum++;
                    failureMsg.append(failureNum + "*项目 " + ofYear.getProjectName() + " 已存在！/n");
                }
            } catch (Exception exc) {
                failureNum++;
                String msg = "*" + successNum + "*项目 " + ofYear.getProjectName() + " 导入失败";
                failureMsg.append(msg + exc.getMessage());
                log.error(msg, exc);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "导入失败！共 " + failureNum + " 条数据格式不正确：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "导入成功！共 " + successNum + " 条。");
        }
        return successMsg.toString();
    }

    @Override
    @Transactional
    public AjaxResult commit(PlanYearsStandardVo yearsStandardVo) {
        PlanYears byId = planYearsMapper.getById(yearsStandardVo.getPlanYearId());
        if (!isBetweenValue(byId)) {
            return AjaxResult.error("所创计划不在提报日期内!");
        }
        BigDecimal evaluation = byId.getEvaluation();
        SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
        Long deptId = sysUser.getDeptId();
        if (!pmAuditDeptRefService.insertPmAuditDeptRefs(byId.getPlanYearId(),
                "0",
                deptId,
                evaluation,
                sysUser.getUserId(),
                byId.getProjectType())) {
            throw new ServiceException("审核关联数据插入失败");
        }

        int commit = planYearsMapper.commit(yearsStandardVo.getPlanYearId());
        if (commit != 1) {
            return AjaxResult.error("项目状态数据异常");
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult reviewTo(PlanYearsStandardVo vo) {
        SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
        Long deptId = sysUser.getDeptId();
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        String[] ancestors = sysDept.getAncestors().split(",");
        String deptLevel = null;
        if (ancestors.length == 2) { //C级
            deptLevel = "C";
        } else if (ancestors.length == 3) { //B级
            deptLevel = "B";
        } else if (ancestors.length == 4) { //A级
            deptLevel = "A";
        }
        LambdaQueryWrapper<PmAuditDeptRef> lw = new LambdaQueryWrapper();
        lw.eq(PmAuditDeptRef::getRefId, vo.getPlanYearId());
        lw.eq(PmAuditDeptRef::getRefType, "0");
        List<PmAuditDeptRef> list = pmAuditDeptRefService.list(lw);
        boolean flay = true;
        if (!ObjectUtils.isEmpty(list)) {
            for (PmAuditDeptRef pmAuditDeptRef : list) {
                // 判断 deptLevel 是否还有更高的 且是 待审核的数据
                if (pmAuditDeptRef.getDeptLevel().compareTo(deptLevel) > 0
                        && pmAuditDeptRef.getStatus().equals(Integer.parseInt("0"))) {
                    flay = false;
                }
                // 更新当前  deptLevel 级别的审核状态
                if (pmAuditDeptRef.getDeptLevel().compareTo(deptLevel) == 0) {
                    pmAuditDeptRef.setStatus(1);
                    pmAuditDeptRefService.updateById(pmAuditDeptRef);
                }
            }
        }
        realReviewTo(vo, flay);
        return AjaxResult.success();
    }

    @Transactional
    public AjaxResult realReviewTo(PlanYearsStandardVo vo, boolean flay) {
        Date now = new Date();
        //年度计划审核通过后同步到季度计划和项目管理
        PlanQuarter quarters = new PlanQuarter();
        PmDemand demand = new PmDemand();
        PlanYears byId = planYearsMapper.getById(vo.getPlanYearId());
        BeanUtils.copyProperties(byId, quarters);
        BeanUtils.copyProperties(byId, demand);
        quarters.setPlanType(0);
        //上传审核文件
        List<SysFileRef> sysFileRefuses = vo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefuses)) {
            for (SysFileRef ref : sysFileRefuses) {
                ref.setRedId(vo.getPlanYearId());
                ref.setType(SysFileRefEnum.PLAN_YEAR_EXAMINE.getType());
                ref.setCreated(vo.getUpdated());
                ref.setCreateTime(now);
                ref.setUpdated(vo.getUpdated());
                ref.setUpdateTime(now);
                sysFileRefMapper.insert(ref);
            }
        }
        if (flay) {
            //同步季度计划
            quarters.setPlanYearId(byId.getPlanYearId());
            quarters.setProjectStatus(ProjectStatus.PLANTOEXAMINE.getCode());
            quarters.setCreateTime(now);
            planQuarterMapper.insertPlanQuarter(quarters);
            //同步到项目管理状态为需求待填制
            demand.setPlanId(quarters.getPlanPracticalId());
            demand.setEvaluation(byId.getEvaluation().doubleValue());
            demand.setIsExcess(Integer.parseInt(byId.getIsExcess()));
            demand.setProjectStatus(PmProjectStatus.DEMAND_WAIT_FILL.getCode());
            demand.setPurchaseDeptId(Long.valueOf(byId.getPurchaseDeptId()));
            demand.setCreateTime(now);
            pmDemandMapper.insert(demand);
            log.info("预警状态更新：demandID：{}", demand.getDemandId());
            demandService.updateDemandWarnStatus(demand.getDemandId());
            //计划附件进行同步---查询年度计划附件后分别添加项目需求附件和季度附件
            LambdaQueryWrapper<SysFileRef> sysFileRefLp = new LambdaQueryWrapper<>();
            sysFileRefLp.eq(SysFileRef::getRedId, vo.getPlanYearId());
            sysFileRefLp.in(SysFileRef::getType, Arrays.asList(SysFileRefEnum.PLAN_YEAR.getType(), SysFileRefEnum.PLAN_YEAR_EXAMINE.getType()));
            List<SysFileRef> sysFileRefs = sysFileRefMapper.selectList(sysFileRefLp);
            if (!ObjectUtils.isEmpty(sysFileRefs)) {
                for (SysFileRef ref : sysFileRefs) {
                    ref.setRedId(quarters.getPlanPracticalId());
                    ref.setType(SysFileRefEnum.PLAN_TEMPORARY.getType());
                    ref.setId(null);
                    ref.setCreated(vo.getUpdated());
                    ref.setCreateTime(now);
                    ref.setUpdated(vo.getUpdated());
                    ref.setUpdateTime(now);
                    sysFileRefMapper.insert(ref);
                }
                for (SysFileRef ref : sysFileRefs) {
                    ref.setRedId(demand.getDemandId());
                    ref.setType(SysFileRefEnum.PM_DEMAND.getType());
                    ref.setId(null);
                    ref.setCreated(vo.getUpdated());
                    ref.setCreateTime(now);
                    ref.setUpdated(vo.getUpdated());
                    ref.setUpdateTime(now);
                    sysFileRefMapper.insert(ref);
                }
            }
            //赋予项目状态已审核
            vo.setProjectStatus(ProjectStatus.PLANTOEXAMINE.getCode());
            return review(vo);
        }
        return AjaxResult.success("成功");
    }

    @Override
    @Transactional
    public AjaxResult reviewReturn(PlanYearsStandardVo vo) {
        Date now = new Date();
        vo.setProjectStatus(ProjectStatus.PLANTOBACK.getCode());
        //上传审核文件并赋予计划审核退回
        List<SysFileRef> sysFileRefuses = vo.getSysFileRefs();
        for (SysFileRef ref : sysFileRefuses) {
            ref.setRedId(vo.getPlanYearId());
            ref.setType(SysFileRefEnum.PLAN_YEAR_EXAMINE.getType());
            ref.setCreated(vo.getUpdated());
            ref.setCreateTime(now);
            ref.setUpdated(vo.getUpdated());
            ref.setUpdateTime(now);
            sysFileRefMapper.insert(ref);
        }
        return review(vo);
    }

    private AjaxResult review(PlanYearsStandardVo vo) {
        int review = planYearsMapper.review(vo);
        if (review != 1) {
            return AjaxResult.error("项目状态数据异常");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult appUpdate(PlanYearsStandardVo vo) {
        //申请后会成为未提交的状态，可以进行修改
        vo.setProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
        int review = planYearsMapper.review(vo);
        if (review != 1) {
            return AjaxResult.error("项目状态数据异常");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult sendLetter(PlanYearsStandardVo yearsStandardVo) {
        int review = planYearsMapper.sendLetter(yearsStandardVo);
        if (review != 1) {
            return AjaxResult.error("项目状态数据异常");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult upLoadPlanFile(PlanYearsStandardVo yearsStandardVo) {
        List<SysFileRef> sysFileRefs = yearsStandardVo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefs)) {
            for (SysFileRef ref : sysFileRefs) {
                ref.setRedId(yearsStandardVo.getPlanYearId());
                ref.setType(SysFileRefEnum.PLAN_YEAR.getType());
                sysFileRefMapper.insert(ref);
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult downLoadPlanFile(PlanYearsStandardVo yearsStandardVo) {

        return AjaxResult.success();
    }

    /**
     * 需求单位--首页--计划管理总数
     *
     * @return
     */
    @Override
    public AjaxResult demandUnitPlanManagementTotal() {
        // List<PlanYears> planYears = new ArrayList<>();
        Long count = null;
        try {
            // 通过用户ID查询角色
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            // 获取角色权限 demand_unit
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("demand_unit")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                // 获取用户
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                // 获取部门
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                // 查询年度计划
                LambdaQueryWrapper<PlanYears> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(PlanYears::getPurchaseDeptId, sysDept.getDeptId());
                queryWrapper.eq(PlanYears::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
                // planYears = planYearsMapper.selectList(queryWrapper);
                count = planYearsMapper.selectCount(queryWrapper);
            }
            // 获取角色权限 admin
            List<SysRole> sysRoleList2 = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("admin")).collect(Collectors.toList());
            if (sysRoleList2.size() > 0) {
                LambdaQueryWrapper<PlanYears> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(PlanYears::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
                // planYears = planYearsMapper.selectList(queryWrapper);
                count = planYearsMapper.selectCount(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(count);
    }

    @Override
    public AjaxResult purchasingManagementPurchasingManagementTotal() {
//        List<PlanYears> planYears = new ArrayList<>();
//        try {
//            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
//            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("purchasing_management")).collect(Collectors.toList());
//            if (sysRoleList.size() > 0) {
//                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
//                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
//                LambdaQueryWrapper<PlanYears> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.eq(PlanYears::getPurchaseDeptId, sysDept.getDeptId())
//                        .in(PlanYears::getProjectStatus, ProjectStatus.PLANWAIEXAMINE.getCode(), ProjectStatus.PLANTOEXAMINE.getCode());
//                planYears = planYearsMapper.selectList(queryWrapper);
//            }
//            List<SysRole> sysRoleList2 = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("admin")).collect(Collectors.toList());
//            if (sysRoleList2.size() > 0) {
//                LambdaQueryWrapper<PlanYears> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.in(PlanYears::getProjectStatus, ProjectStatus.PLANWAIEXAMINE.getCode(), ProjectStatus.PLANTOEXAMINE.getCode());
//                planYears = planYearsMapper.selectList(queryWrapper);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        PlanYearsStandardVo vo = new PlanYearsStandardVo();
        vo.setPurchaseDeptId(String.valueOf(loginUser.getDeptId()));
        vo.setCreated(String.valueOf(loginUser.getUserId()));
        List<PlanYears> planYears = planYearsMapper.query(vo);
        return AjaxResult.success(planYears.size());
    }

    /**
     * 需求单位--首页--需求管理总数
     *
     * @return
     */
    @Override
    public AjaxResult demandUnitDemandManagementTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            // 通过用户ID 查询角色
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            // 获取角色权限 demand_unit
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("demand_unit")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                LambdaQueryWrapper<PmDemand> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(PmDemand::getPurchaseDeptId, sysDept.getDeptId());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
            List<SysRole> sysRoleList2 = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("admin")).collect(Collectors.toList());
            if (sysRoleList2.size() > 0) {
                LambdaQueryWrapper<PmDemand> queryWrapper = new LambdaQueryWrapper<>();
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    @Override
    public AjaxResult purchasingManagementDemandManagementTotal() {
        long ii = selectPmDemandCount(1);
        return AjaxResult.success(ii);
    }

    public long selectPmDemandCount(int reqType) {
        LambdaQueryWrapper<PmDemand> lw = new LambdaQueryWrapper<>();
        //  4 (合同信息管理)、 0(需求单位管理) 、 5(项目建设管理)  需求单位
        //  1(需求需求审核) 、2 (任务下达管理)      采购管理部门
        //  3(采购执行管理)   采购办
        List<PmAuditDeptRef> list = new ArrayList<>();
        LambdaQueryWrapper<PmAuditDeptRef> l = new LambdaQueryWrapper<>();
        l.eq(PmAuditDeptRef::getDeptId, SecurityUtils.getDeptId());
        l.eq(PmAuditDeptRef::getRefType, "2");
        list = pmAuditDeptRefService.list(l);
        if (Arrays.asList(1, 2, 3).contains(reqType)) {
            if (!ObjectUtils.isEmpty(list) && !SecurityUtils.getUserId().equals(Integer.parseInt("1"))) {
                lw.in(PmDemand::getDemandId, list.stream().map(PmAuditDeptRef::getRefId).collect(Collectors.toList()));
            }
        } else {
            lw.eq(PmDemand::getPurchaseDeptId, SecurityUtils.getDeptId());
        }
        if (reqType == 1) { //需求审核单位列表
            lw.apply("(project_status = 6 or project_status = 8 )");
        } else if (reqType == 2) { //任务下达列表
            lw.apply("(project_status = 8 or project_status = 9 )");
        } else if (reqType == 3) { //采购执行列表
            lw.apply("(project_status = 9 or project_status = 10 or project_status = 11 or project_status = 12 or project_status = 13 or project_status = 14 or project_status = 15)");
        } else if (reqType == 4) { //合同信息列表
            lw.apply("(project_status = 15 or project_status = 16 )");
        } else if (reqType == 5) { //项目建设列表
            lw.apply("(project_status = 16 or project_status = 17 )");
        }
        lw.last(" order by project_status, plan_demand_sub_time");
        long count = demandService.count(lw);
        return count;
    }

    @Override
    public AjaxResult demandUnitContractManagementTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("demand_unit")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                LambdaQueryWrapper<PmDemand> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(PmDemand::getPurchaseDeptId, sysDept.getDeptId());
                queryWrapper.in(PmDemand::getProjectStatus, PmProjectStatus.CONTRACT_WAIT_FILL.getCode(), PmProjectStatus.UNDER_CONSTRUCTION.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
            List<SysRole> sysRoleList2 = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("admin")).collect(Collectors.toList());
            if (sysRoleList2.size() > 0) {
                LambdaQueryWrapper<PmDemand> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(PmDemand::getProjectStatus, PmProjectStatus.CONTRACT_WAIT_FILL.getCode(), PmProjectStatus.UNDER_CONSTRUCTION.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    @Override
    public AjaxResult demandUnitConstructionManagementTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("demand_unit")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                LambdaQueryWrapper<PmDemand> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(PmDemand::getPurchaseDeptId, sysDept.getDeptId());
                queryWrapper.in(PmDemand::getProjectStatus, PmProjectStatus.UNDER_CONSTRUCTION.getCode(), PmProjectStatus.COMPLETION_CONSTRUCTION.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
            List<SysRole> sysRoleList2 = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("admin")).collect(Collectors.toList());
            if (sysRoleList2.size() > 0) {
                LambdaQueryWrapper<PmDemand> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(PmDemand::getProjectStatus, PmProjectStatus.UNDER_CONSTRUCTION.getCode(), PmProjectStatus.COMPLETION_CONSTRUCTION.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    @Override
    public AjaxResult purchasingManagementTaskReleaseTotal() {
        long ii = selectPmDemandCount(2);
        return AjaxResult.success(ii);
    }

    @Override
    public AjaxResult procurementOfficeProcurementExecutionTotal() {
        SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
        SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
        PmDemandReqVo pmDemandReqVo = new PmDemandReqVo();
        pmDemandReqVo.setPageNum(1L);
        pmDemandReqVo.setPageSize(10L);
        pmDemandReqVo.setUserId(sysUser.getUserId());
        pmDemandReqVo.setPurchaseDeptId(Math.toIntExact(sysDept.getDeptId()));
        IPage<PmDemandResVo> page = pmDemandService.selectPmDemandList(pmDemandReqVo, 3);
        return AjaxResult.success(page.getTotal());
    }

    @Override
    public AjaxResult procurementOfficeWinningTheBidTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("procurement_office")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                LambdaQueryWrapper<PmDemand> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(PmDemand::getPurchaseDeptId, sysDept.getDeptId())
                        .lt(PmDemand::getProjectStatus, PmProjectStatus.CONTRACT_WAIT_FILL.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
            List<SysRole> sysRoleList2 = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("admin")).collect(Collectors.toList());
            if (sysRoleList2.size() > 0) {
                LambdaQueryWrapper<PmDemand> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.lt(PmDemand::getProjectStatus, PmProjectStatus.CONTRACT_WAIT_FILL.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    @Override
    public AjaxResult procurementOfficeFailureToWinTheBidTotal() {
        List<PmDemand> pmDemands = new ArrayList<>();
        try {
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());
            List<SysRole> sysRoleList = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("procurement_office")).collect(Collectors.toList());
            if (sysRoleList.size() > 0) {
                SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
                SysDept sysDept = deptMapper.selectDeptById(sysUser.getDeptId());
                LambdaQueryWrapper<PmDemand> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(PmDemand::getPurchaseDeptId, sysDept.getDeptId())
                        .gt(PmDemand::getProjectStatus, PmProjectStatus.CONTRACT_WAIT_FILL.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
            List<SysRole> sysRoleList2 = sysRoles.stream().filter(tdto -> tdto.getRoleKey().equals("admin")).collect(Collectors.toList());
            if (sysRoleList2.size() > 0) {
                LambdaQueryWrapper<PmDemand> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.gt(PmDemand::getProjectStatus, PmProjectStatus.CONTRACT_WAIT_FILL.getCode());
                pmDemands = pmDemandMapper.selectList(queryWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(pmDemands.size());
    }

    /**
     * 查询需求单位待办事项(计划待提交)
     *
     * @return
     */
    @Override
    public List<PlanQuarterResponseVo> planWaitCommit() {
        return getListByProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
    }

    /**
     * 采购管理部门首页待办事项(计划待审核)
     *
     * @return
     */
    @Override
    public List<PlanQuarterResponseVo> planWaitExamine() {
        return getListByProjectStatus(ProjectStatus.PLANWAIEXAMINE.getCode());
    }

    /**
     * 需求单位待办事项
     */
    @Override
    public AjaxResult demandUnitWillManipulateTotal() {
        List<HomeToDoQueryResVo> homeRes = new ArrayList<>();
        //计划待提交，需求待提交，合同待填制，项目建设待完成
        List<PlanQuarterResponseVo> planRes = getListByProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
        List<PmDemandResVo> demandRes = demandService.demandWaitCommit();
        demandRes.addAll(demandService.contractWaitFilled());
        demandRes.addAll(demandService.projectWaitFinish());
        //转为首页table展示数据
        if (!ObjectUtils.isEmpty(planRes) && planRes.size() > 0) {
            for (PlanQuarterResponseVo planVo : planRes) {
                HomeToDoQueryResVo home = new HomeToDoQueryResVo();
                BeanUtils.copyProperties(planVo, home);
                homeRes.add(home);
            }
        }
        if (!ObjectUtils.isEmpty(demandRes) && demandRes.size() > 0) {
            for (PmDemandResVo demandResVo : demandRes) {
                HomeToDoQueryResVo home = new HomeToDoQueryResVo();
                home.setEvaluation(BigDecimal.valueOf(demandResVo.getEvaluation()));
                BeanUtils.copyProperties(demandResVo, home);
                homeRes.add(home);
            }
        }

        return AjaxResult.success(homeRes);
    }

    @Override
    public AjaxResult purchasingManagementWillManipulateTotal() {
        List<HomeToDoQueryResVo> homeRes = new ArrayList<>();
        //计划待审核，需求待审核，任务待下达
        List<PlanQuarterResponseVo> planRes = getListByProjectStatus(ProjectStatus.PLANWAIEXAMINE.getCode());
        List<PmDemandResVo> demandRes = demandService.demandWaitExamine();
        demandRes.addAll(demandService.taskWaitRelease());
        //转为首页table展示数据
        if (!ObjectUtils.isEmpty(planRes) && planRes.size() > 0) {
            for (PlanQuarterResponseVo planVo : planRes) {
                HomeToDoQueryResVo home = new HomeToDoQueryResVo();
                BeanUtils.copyProperties(planVo, home);
                homeRes.add(home);
            }
        }
        if (!ObjectUtils.isEmpty(demandRes) && demandRes.size() > 0) {
            for (PmDemandResVo demandResVo : demandRes) {
                HomeToDoQueryResVo home = new HomeToDoQueryResVo();
                home.setEvaluation(BigDecimal.valueOf(demandResVo.getEvaluation()));
                BeanUtils.copyProperties(demandResVo, home);
                homeRes.add(home);
            }
        }

        return AjaxResult.success(homeRes);
    }

    /**
     * 通过年度ID，查询季度、临时计划详情，通过季度、临时计划ID查询项目
     *
     * @param yearsStandardVo
     * @return
     */
    @Override
    public AjaxResult projectDetails(PlanYearsStandardVo yearsStandardVo) {
        Map<String, Object> returnMap = new HashMap<>();
        // 通过年度ID查询年度详情
        PlanYears byId = planYearsMapper.getById(yearsStandardVo.getPlanYearId());
        if (StringUtils.isNull(byId)) {
            return AjaxResult.error("没有查到相关数据！");
        }
        // 通过年度ID查询季度、临时计划详情
        ProvisionalPlan provisionalPlan = provisionalPlanMapper.selectProvisionalPlanByYearId(yearsStandardVo.getPlanYearId().intValue());
        if (StringUtils.isNull(provisionalPlan)) {
            return AjaxResult.error("没有查到相关数据！");
        }
        // 通过季度、临时计划ID查询项目数据
        PmDemand pmDemand = pmDemandService.selectByPlanId(provisionalPlan.getPlanPracticalId());
        if (StringUtils.isNotNull(pmDemand)) {
            String detailType = "";
            if (StringUtils.isNotNull(yearsStandardVo.getDetailType())) {
                detailType = yearsStandardVo.getDetailType();
            } else {
                // 详情类型(1项目计划，2需求建档，3任务下达,4中标信息，5合同信息，6建设情况)
                // 项目计划 4之前（包括4）
                // 需求建党 4之后（不包括4）
                // 任务下达 8之后（不包括8）
                // 采购执行 9之后（不包括9）
                // 合同信息 15之后（不包括15）
                // 项目建设 17
                Integer projectStatus = Integer.valueOf(pmDemand.getProjectStatus());
                if (projectStatus <= 4) {
                    detailType = "1";
                } else if (4 < projectStatus && projectStatus <= 8) {
                    detailType = "2";
                } else if (8 < projectStatus && projectStatus <= 9) {
                    detailType = "3";
                } else if (9 < projectStatus && projectStatus <= 15) {
                    detailType = "4";
                } else if (15 < projectStatus && projectStatus < 17) {
                    detailType = "5";
                } else if (projectStatus == 17) {
                    detailType = "6";
                }
            }
            Long demandId = pmDemand.getDemandId();
            PmDemandResVo vo = new PmDemandResVo();
            vo.setDemandId(demandId);
            vo.setDetailType(detailType);
            if ("1".equals(detailType)) { //项目计划
                BeanUtils.copyProperties(pmDemand, vo);
                SysDeptResponseVo sysDeptResponseVo = (SysDeptResponseVo) deptService.selectDeptById(vo.getPurchaseDeptId()).get("sysDept");
                if (sysDeptResponseVo != null) {
                    vo.setPurchaseDeptName(sysDeptResponseVo.getDeptName());
                }
                String purchaseServicesName = dictDataService.selectDictLabel("purchase_services", vo.getPurchaseServices());
                if (StringUtils.isNotEmpty(purchaseServicesName)) {
                    vo.setPurchaseServicesName(purchaseServicesName);
                }
                //采购需求附件
                List<SysFileInfo> demandFileInfos = getSysFileInfoList(vo.getDemandId(), SysFileRefEnum.PM_DEMAND.getType());
                if (!ObjectUtils.isEmpty(demandFileInfos)) {
                    vo.setDemandFileInfos(demandFileInfos);
                }
                //项目类型
                for (ProjectTypes value : ProjectTypes.values()) {
                    if (vo.getProjectType() != null && vo.getProjectType().equals(value.getCode())) {
                        vo.setProjectTypeName(value.getInfo());
                        break;
                    }
                }
                //是否为超限额计划
                for (IsExcess value : IsExcess.values()) {
                    if (vo.getIsExcess() != null && vo.getIsExcess().equals(value.getCode())) {
                        vo.setIsExcessName(value.getInfo());
                        break;
                    }
                }
                //采购方式
                for (PlanPurchaseMode value : PlanPurchaseMode.values()) {
                    if (vo.getPurchaseMode() != null && vo.getPurchaseMode().equals(value.getCode())) {
                        vo.setPurchaseModeName(value.getInfo());
                        break;
                    }
                }
                //项目属性
                for (ProjectAttribute value : ProjectAttribute.values()) {
                    if (vo.getProjectAttr() != null && vo.getProjectAttr().equals(value.getCode())) {
                        vo.setProjectAttrName(value.getInfo());
                        break;
                    }
                }
                //预警状态
                for (WarnStatus value : WarnStatus.values()) {
                    if (vo.getWarnStatus() != null && vo.getWarnStatus().equals(value.getCode())) {
                        vo.setWarnStatusName(value.getInfo());
                        break;
                    }
                }
                //项目状态
                for (PmProjectStatus value : PmProjectStatus.values()) {
                    if (vo.getProjectStatus() != null && vo.getProjectStatus().equals(value.getCode())) {
                        vo.setProjectStatusName(value.getInfo());
                        break;
                    }
                }
            } else if ("2".equals(detailType)) { //需求建档
                //采购需求审核文件
                List<SysFileInfo> auditFileInfos = getSysFileInfoList(vo.getDemandId(), SysFileRefEnum.PM_DEMAND_EXAMINE.getType());
                if (!ObjectUtils.isEmpty(auditFileInfos)) {
                    vo.setAuditFileInfos(auditFileInfos);
                }
                LambdaQueryWrapper<PmBookBuilding> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(PmBookBuilding::getDemandId, demandId);
                PmBookBuilding pmBookBuilding = pmBookBuildingService.getOne(lambdaQueryWrapper);
                if (pmBookBuilding != null) {
                    PmBookBuildingResVo responseVo = new PmBookBuildingResVo();
                    BeanUtils.copyProperties(pmBookBuilding, responseVo);

                    List<SysFileInfo> fileInfos = getSysFileInfoList(pmBookBuilding.getId(), SysFileRefEnum.PM_BOOK_BUILDING.getType());
                    if (!ObjectUtils.isEmpty(fileInfos)) {
                        responseVo.setFileInfos(fileInfos);
                    }
                    vo.setPmBookBuildingResVo(responseVo);
                }
            } else if ("3".equals(detailType)) { //任务下达
                //任务下达文件
                List<SysFileInfo> taskReleaseFileInfos = getSysFileInfoList(vo.getDemandId(), SysFileRefEnum.PM_TAST_RELEASE.getType());
                if (!ObjectUtils.isEmpty(taskReleaseFileInfos)) {
                    vo.setTaskReleaseFileInfos(taskReleaseFileInfos);
                }
            } else if ("4".equals(detailType)) { //中标信息
                PmPurchaseExecutionResVo pmPurchaseExecutionResVo = new PmPurchaseExecutionResVo();
                List<SysFileInfo> fileInfosAll = new ArrayList<>();
                //代理商信息
                BaseAgency baseAgency = this.baseAgencyService.getById(pmDemand.getAgencyId());
                pmPurchaseExecutionResVo.setBaseAgency(baseAgency);
                //发布公告列表
                LambdaQueryWrapper<PmReleaseAnnouncement> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(PmReleaseAnnouncement::getDemandId, demandId);
                List<PmReleaseAnnouncement> pmReleaseAnnouncementList = this.pmReleaseAnnouncementService.list(lambdaQueryWrapper);
                if (!ObjectUtils.isEmpty(pmReleaseAnnouncementList)) {
                    List<PmReleaseAnnouncementResVo> pmReleaseAnnouncementResVoList = new ArrayList<>();
                    for (PmReleaseAnnouncement pmReleaseAnnouncement : pmReleaseAnnouncementList) {
                        PmReleaseAnnouncementResVo pmReleaseAnnouncementResVo = new PmReleaseAnnouncementResVo();
                        BeanUtils.copyProperties(pmReleaseAnnouncement, pmReleaseAnnouncementResVo);
                        List<SysFileInfo> fileInfos = getSysFileInfoList(pmReleaseAnnouncement.getId(), SysFileRefEnum.PM_ANNOUNCEMENT_FILE.getType());
                        if (!ObjectUtils.isEmpty(fileInfos)) {
                            fileInfosAll.addAll(fileInfos);
                        }
                        pmReleaseAnnouncementResVoList.add(pmReleaseAnnouncementResVo);
                    }
                    pmPurchaseExecutionResVo.setPmReleaseAnnouncementResVoList(pmReleaseAnnouncementResVoList);
                }
                //专家信息列表
                List<PmBaseExpertResVo> pmBaseExpertResVoList = this.pmDemandExpertRefService.getPmBaseExpertResVoList(demandId);
                pmPurchaseExecutionResVo.setPmBaseExpertResVoList(pmBaseExpertResVoList);
                //开标信息列表
                List<PmBidOpeningResVo> pmBidOpeningResVoList = this.pmBidOpeningService.getPmBidOpeningResVoList(demandId);
                pmPurchaseExecutionResVo.setPmBidOpeningResVoList(pmBidOpeningResVoList);
                //中标信息列表
                LambdaQueryWrapper<PmBidWinning> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(PmBidWinning::getDemandId, demandId).orderByDesc(PmBidWinning::getBidAnnouncementTime);
                List<PmBidWinning> pmBidWinningList = this.pmBidWinningService.list(lambdaQueryWrapper1);
                if (!ObjectUtils.isEmpty(pmBidWinningList)) {
                    List<PmBidWinningResVo> pmBidWinningResVoList = new ArrayList<>();
                    for (PmBidWinning pmBidWinning : pmBidWinningList) {
                        PmBidWinningResVo pmBidWinningResVo = new PmBidWinningResVo();
                        BeanUtils.copyProperties(pmBidWinning, pmBidWinningResVo);
                        List<SysFileInfo> fileInfos = getSysFileInfoList(pmBidWinning.getId(), SysFileRefEnum.PM_BID_WINNING_FILE.getType());
                        if (!ObjectUtils.isEmpty(fileInfos)) {
                            fileInfosAll.addAll(fileInfos);
                        }
                        pmBidWinningResVoList.add(pmBidWinningResVo);
                    }
                    pmPurchaseExecutionResVo.setPmBidWinningResVoList(pmBidWinningResVoList);
                }
                //质疑情况
                List<SysFileInfo> callRequestFileInfos = getSysFileInfoList(vo.getDemandId(), SysFileRefEnum.PM_BID_CALL_QEUSTION_FILE.getType());
                if (!ObjectUtils.isEmpty(callRequestFileInfos)) {
                    pmPurchaseExecutionResVo.setCallRequestFileInfos(callRequestFileInfos);
                }
                //流标情况
                LambdaQueryWrapper<PmBidFailure> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(PmBidFailure::getDemandId, demandId).orderByDesc(PmBidFailure::getBidFailureTime);
                List<PmBidFailure> pmBidFailureList = this.pmBidFailureService.list(lambdaQueryWrapper2);
                if (!ObjectUtils.isEmpty(pmBidFailureList)) {
                    List<PmBidFailureResVo> pmBidFailureResVoList = new ArrayList<>();
                    for (PmBidFailure pmBidFailure : pmBidFailureList) {
                        PmBidFailureResVo pmBidFailureResVo = new PmBidFailureResVo();
                        BeanUtils.copyProperties(pmBidFailure, pmBidFailureResVo);
                        List<SysFileInfo> fileInfos = getSysFileInfoList(pmBidFailure.getId(), SysFileRefEnum.PM_BID_FAILURE_FILE.getType());
                        if (!ObjectUtils.isEmpty(fileInfos)) {
                            fileInfosAll.addAll(fileInfos);
                        }
                        pmBidFailureResVoList.add(pmBidFailureResVo);
                    }
                    pmPurchaseExecutionResVo.setPmBidFailureResVoList(pmBidFailureResVoList);
                }
                //中标通知书
                List<SysFileInfo> pmBidWinningNotificationFileInfos = getSysFileInfoList(vo.getDemandId(), SysFileRefEnum.PM_BID_WINNING_NOTIFICATION.getType());
                if (!ObjectUtils.isEmpty(pmBidWinningNotificationFileInfos)) {
                    fileInfosAll.addAll(pmBidWinningNotificationFileInfos);
                }
                pmPurchaseExecutionResVo.setFileInfos(fileInfosAll);
                vo.setPmPurchaseExecutionResVo(pmPurchaseExecutionResVo);
            } else if ("5".equals(detailType)) { //合同信息
                LambdaQueryWrapper<PmContractInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(PmContractInfo::getDemandId, demandId);
                PmContractInfo pmContractInfo = pmContractInfoService.getOne(lambdaQueryWrapper);
                if (pmContractInfo != null) {
                    PmContractInfoResVo pmContractInfoResVo = new PmContractInfoResVo();
                    BeanUtils.copyProperties(pmContractInfo, pmContractInfoResVo);
                    //合同信息文件
                    List<SysFileInfo> fileInfos = getSysFileInfoList(pmContractInfo.getId(), SysFileRefEnum.PM_CONTRACT_INFO.getType());
                    if (!ObjectUtils.isEmpty(fileInfos)) {
                        pmContractInfoResVo.setFileInfos(fileInfos);
                    }
                    vo.setPmContractInfoResVo(pmContractInfoResVo);
                }
            } else if ("6".equals(detailType)) { //建设情况
                LambdaQueryWrapper<PmProjectConstruction> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(PmProjectConstruction::getDemandId, demandId);
                PmProjectConstruction pmProjectConstruction = pmProjectConstructionService.getOne(lambdaQueryWrapper);
                if (pmProjectConstruction != null) {
                    PmProjectConstructionResVo pmProjectConstructionResVo = new PmProjectConstructionResVo();
                    BeanUtils.copyProperties(pmProjectConstruction, pmProjectConstructionResVo);
                    //建设情况文件
                    List<SysFileInfo> fileInfos = getSysFileInfoList(pmProjectConstruction.getId(), SysFileRefEnum.PM_PROJECT_CONSTRUCTION.getType());
                    if (!ObjectUtils.isEmpty(fileInfos)) {
                        pmProjectConstructionResVo.setFileInfos(fileInfos);
                    }
                    vo.setPmProjectConstructionResVo(pmProjectConstructionResVo);
                }
            }
            return AjaxResult.success(vo);
        } else {
            if (StringUtils.isNotNull(provisionalPlan)) {
                return AjaxResult.success(provisionalPlan);
            } else {
                if (StringUtils.isNotNull(byId)) {
                    return AjaxResult.success(byId);
                }
            }
        }
        return AjaxResult.error("没有查到相关数据！");
    }

    @Override
    public List<PlanYears> queryPage(PlanYearsStandardVo vo) {
        List<PlanYears> planYears = planYearsMapper.query(vo);
        if (!ObjectUtils.isEmpty(planYears)) {
            planYears.stream().map(o -> {
                // 当前年度计划的所有关联审核数据
                LambdaQueryWrapper<PmAuditDeptRef> lw = new LambdaQueryWrapper();
                lw.eq(PmAuditDeptRef::getRefId, o.getPlanYearId());
                lw.eq(PmAuditDeptRef::getRefType, "0");
                List<PmAuditDeptRef> list = pmAuditDeptRefService.list(lw);


                if (!ObjectUtils.isEmpty(list)) {
                    // 当地 年度计划 当前部门 的 审核数据
                    List<PmAuditDeptRef> collect = list.stream()
                            .filter(f -> f.getDeptId().equals(Long.valueOf(vo.getPurchaseDeptId())))
                            .collect(Collectors.toList());
                    String deptLevel = collect.get(0).getDeptLevel();

                    boolean f = true;
                    f = collect.get(0).getStatus().equals(Integer.parseInt("1")) ? false : true;

                    for (PmAuditDeptRef pmAuditDeptRef : list) {
                        if (pmAuditDeptRef.getDeptLevel().compareTo(deptLevel) == -1
                                && pmAuditDeptRef.getStatus().equals(Integer.parseInt("0"))) {
                            f = false;
                        }
                    }
                    /*
                    *  String s1="A";
                        String s2="B";
                System.out.println(s1.compareTo(s2));
                *    -1
                * */
                    o.setFlag(f);
                }
                return o;
            }).collect(Collectors.toList());
        }
        return planYears;
    }

    private List<SysFileInfo> getSysFileInfoList(Long redId, Integer type) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("red_id", redId);
        map.put("type", type);
        List<SysFileRef> fileRefs = sysFileRefService.listByMap(map);
        if (!ObjectUtils.isEmpty(fileRefs)) {
            List<SysFileInfo> fileInfos = new ArrayList<>();
            for (SysFileRef ref : fileRefs) {
                SysFileInfo fileInfo = fileService.getById(ref.getFileId());
                fileInfos.add(fileInfo);
            }
            return fileInfos;
        } else {
            return null;
        }

    }

    /**
     * 查询已被催告发函的计划
     *
     * @return
     */
    @Override
    public List<PlanQuarterResponseVo> willSendLetter() {
        LambdaQueryWrapper<PlanYears> yearsLp = new LambdaQueryWrapper<PlanYears>();
        yearsLp.eq(PlanYears::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
        yearsLp.eq(PlanYears::getSendLetter, "1");
        List<PlanYears> planYears = planYearsMapper.selectList(yearsLp);

        LambdaQueryWrapper<PlanQuarter> quarterLp = new LambdaQueryWrapper<PlanQuarter>();
        quarterLp.eq(PlanQuarter::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
        quarterLp.eq(PlanQuarter::getSendLetter, "1");
        List<PlanQuarter> planQuarters = planQuarterMapper.selectList(quarterLp);
        //融合一起
        List<PlanQuarterResponseVo> vos = planComplex(planYears, planQuarters);
        return vos;
    }

    public List<PlanQuarterResponseVo> getListByProjectStatus(String projectStatus) {
        LambdaQueryWrapper<PlanYears> yearsLp = new LambdaQueryWrapper<PlanYears>();
        yearsLp.eq(PlanYears::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
        yearsLp.eq(PlanYears::getProjectStatus, projectStatus);
        List<PlanYears> planYears = planYearsMapper.selectList(yearsLp);

        LambdaQueryWrapper<PlanQuarter> quarterLp = new LambdaQueryWrapper<PlanQuarter>();
        quarterLp.eq(PlanQuarter::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
        quarterLp.eq(PlanQuarter::getProjectStatus, projectStatus);
        List<PlanQuarter> planQuarters = planQuarterMapper.selectList(quarterLp);
        //融合一起
        List<PlanQuarterResponseVo> vos = planComplex(planYears, planQuarters);
        return vos;
    }

    /**
     * 年度计划与季度数据一起
     *
     * @return
     */
    public List<PlanQuarterResponseVo> planComplex(List<PlanYears> planYears, List<PlanQuarter> planQuarters) {
        List<PlanYearsResponseVo> yearsRes = changeTo(planYears);
        List<PlanQuarterResponseVo> quarterRes = quartzServiceImpl.changeTo(planQuarters);
        if (!ObjectUtils.isEmpty(yearsRes) && yearsRes.size() > 0) {
            for (PlanYearsResponseVo yearsRe : yearsRes) {
                PlanQuarterResponseVo responseVo = new PlanQuarterResponseVo();

                BeanUtils.copyProperties(yearsRe, responseVo);
                quarterRes.add(responseVo);
            }
        }
        return quarterRes;
    }

    //字段赋值对应的名称
    @Override
    public List<PlanYearsResponseVo> changeTo(List<PlanYears> planYears) {
        //获取年度计划提报时间的阈值
        List<SysDictData> supTime = dictTypeService.selectDictDataByType("sys_annual_plan");
        HashMap<String, String> thresholdMap = new LinkedHashMap<>();
        //年度提报时间的阈值
        for (SysDictData dictData : supTime) {
            //    字段名称----阈值
            thresholdMap.put(dictData.getDictLabel(), dictData.getDictValue());
        }
        //提前或延后*天进行提醒
        List<SysDictData> alertTime = dictTypeService.selectDictDataByType("alert_time_setting");
        HashMap<String, String> alertTimeMap = new LinkedHashMap<>();
        //根据时间类别设定的提醒时间
        for (SysDictData dictData : alertTime) {
            //    字段名称----阈值
            alertTimeMap.put(dictData.getDictLabel(), dictData.getDictValue());
        }
        //获取字典数据
        HashMap<String, HashMap<String, String>> planEnums = dictTypeService.getAboutEnums();
        HashMap<String, String> projectTypesMap = planEnums.get("projectTypes");
        HashMap<String, String> planPurchaseModesMap = planEnums.get("planPurchaseModes");
        HashMap<String, String> projectAttributes = planEnums.get("projectAttributes");
        List<PlanYearsResponseVo> list = new ArrayList<PlanYearsResponseVo>();
        for (PlanYears planYear : planYears) {
            PlanYearsResponseVo responseVo = new PlanYearsResponseVo();
            SysDeptResponseVo sysDeptResponseVo = (SysDeptResponseVo) deptService.selectDeptById(Long.valueOf(planYear.getPurchaseDeptId())).get("sysDept");
            planYear.setPurchaseDeptName(sysDeptResponseVo.getDeptName());

            for (Map.Entry<String, String> entry : projectTypesMap.entrySet()) {
                if (planYear.getProjectType().equals(entry.getValue())) {
                    planYear.setProjectTypeStr(entry.getKey());
                    break;
                }
            }
            for (Map.Entry<String, String> entry : planPurchaseModesMap.entrySet()) {
                if (planYear.getPurchaseMode().equals(entry.getValue())) {
                    planYear.setPurchaseModeStr(entry.getKey());
                    break;
                }
            }
            //项目属性是拼接的
            if (!ObjectUtils.isEmpty(planYear.getProjectAttr())) {
                if (planYear.getProjectAttr().length() > 1) {
                    StringBuilder builder = new StringBuilder();
                    String[] split = planYear.getProjectAttr().split(",");
                    for (String s : split) {
                        for (Map.Entry<String, String> entry : projectAttributes.entrySet()) {
                            if (s.equals(entry.getValue())) {
                                if (!planYear.getProjectAttr().endsWith(s)) {
                                    builder.append(entry.getKey() + ",");
                                } else {
                                    builder.append(entry.getKey());
                                }
                                break;
                            }
                        }
                    }
                    planYear.setProjectAttrStr(builder.toString());
                } else {
                    for (Map.Entry<String, String> entry : projectAttributes.entrySet()) {
                        if (planYear.getProjectAttr().equals(entry.getValue())) {
                            planYear.setProjectAttrStr(entry.getKey());
                            break;
                        }
                    }
                }
            }
            BeanUtils.copyProperties(planYear, responseVo);
            try {
                responseVo.setTipsMessage(planYearsGetTips(responseVo, thresholdMap, alertTimeMap));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            list.add(responseVo);
        }
        return list;
    }

    /**
     * 根据年度计划提报时间的阈值进行提示
     *
     * @return
     */
    public String planYearsGetTips(PlanYearsResponseVo responseVo, HashMap<String, String> thresholdMap, HashMap<String, String> alertTimeMap) throws ParseException {
        //提示信息：定义距离结束时间*天内提示
        int alertDay = Integer.parseInt(alertTimeMap.get("计划提报时间"));
        Integer remindTime = 1000 * 60 * 60 * 24 * alertDay;
        //提报时间的结束时间阈值
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date thresholdTime = dateFormat.parse(thresholdMap.get("起止时间结束"));
        Date date = new Date();
        thresholdTime.setYear(date.getYear());
        double surplus = thresholdTime.getTime() - date.getTime();
        //少于设定天数便提醒
        if (surplus < remindTime && surplus > 0) {
            //剩余天数(向上取整)
            int i = new Double(Math.ceil(surplus / 1000 / 60 / 60 / 24)).intValue();
            if (i > 0) {
                return "距离计划提报时间不足" + i + "天";
            }
        }
        //距离计划完成采购时间一周内提醒
        Integer alertTime = 1000 * 60 * 60 * 24 * 7;
        double surplusTwo = responseVo.getPlanPurchaseFinishTime().getTime() - System.currentTimeMillis();
        //少于设定阈值便提醒
        if (surplusTwo < alertTime && surplusTwo > 0) {
            //剩余天数(向上取整)
            int i = new Double(Math.ceil(surplusTwo / 1000 / 60 / 60 / 24)).intValue();
            if (i > 0) {
                return "距离计划完成采购时间不足" + i + "天";
            }
        }

        return "";
    }

}
