package com.ozs.plan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ozs.common.constant.Constants;
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.DataIsDelete;
import com.ozs.common.enums.PmProjectStatus;
import com.ozs.common.enums.ProjectStatus;
import com.ozs.common.enums.QuarterEnum;
import com.ozs.common.enums.SysFileRefEnum;
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.plan.doman.PlanQuarter;
import com.ozs.plan.doman.PlanYears;
import com.ozs.plan.doman.vo.requestVo.PlanQuarterStandardVo;
import com.ozs.plan.doman.vo.responseVo.PlanQuarterResponseVo;
import com.ozs.plan.mapper.PlanQuarterMapper;
import com.ozs.plan.mapper.PlanYearsMapper;
import com.ozs.plan.service.PlanQuarterService;
import com.ozs.pm.doman.PmAuditDeptRef;
import com.ozs.pm.doman.PmDemand;
import com.ozs.pm.mapper.PmDemandMapper;
import com.ozs.pm.service.IPmDemandService;
import com.ozs.pm.service.PmAuditDeptRefService;
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.service.ISysDeptService;
import com.ozs.system.service.ISysDictTypeService;
import com.ozs.system.service.ISysUserService;
import com.ozs.system.service.SysFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
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 PlanQuarterServiceImpl extends ServiceImpl<PlanQuarterMapper, PlanQuarter> implements PlanQuarterService {

    @Autowired
    PlanQuarterMapper planQuarterMapper;
    @Autowired
    PlanYearsMapper planYearsMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    SysFileRefMapper sysFileRefMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private SysFileService fileService;
    @Autowired
    private PmDemandMapper pmDemandMapper;
    @Autowired
    private IPmDemandService demandService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private PmAuditDeptRefService pmAuditDeptRefService;

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

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

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

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

    @Override
    public AjaxResult deletePlanQuarterById(Long planId) {
        planQuarterMapper.deletePlanQuarterById(planId);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult view(PlanQuarterStandardVo quarterStandardVo) {

        PlanQuarterResponseVo responseVo = new PlanQuarterResponseVo();
        PlanQuarter byId = planQuarterMapper.getById(quarterStandardVo.getPlanPracticalId());
        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, quarterStandardVo.getPlanPracticalId());
        lw.in(SysFileRef::getType, Arrays.asList(SysFileRefEnum.PLAN_TEMPORARY.getType(), SysFileRefEnum.PLAN_TEMPORARY_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(PlanQuarterStandardVo quarterStandardVo) {
        Date now = new Date();
        if (planQuarterMapper.countProjectNameOther(quarterStandardVo.getProjectName(), String.valueOf(quarterStandardVo.getPlanPracticalId())) > 0) {
            return AjaxResult.error("该项目名称已经存在");
        }
        //默认未超额
        if (ObjectUtils.isEmpty(quarterStandardVo.getIsExcess())) {
            quarterStandardVo.setIsExcess("0");
        }
        PlanQuarter quarters = new PlanQuarter();
        try {
            BeanUtils.copyProperties(quarterStandardVo, quarters);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //quarters.setIsExcess(deptService.isExcessOrNo(quarters.getProjectType(), quarters.getEvaluation(), Long.valueOf(quarters.getPurchaseDeptId())));
        quarters.setUpdateTime(now);
        planQuarterMapper.updateInfoById(quarters);
        List<SysFileRef> sysFileRefs = quarterStandardVo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefs)) {
            // 删关联
            LambdaQueryWrapper<SysFileRef> lw = new LambdaQueryWrapper<>();
            lw.eq(SysFileRef::getRedId, quarters.getPlanPracticalId());
            lw.eq(SysFileRef::getType, SysFileRefEnum.PLAN_TEMPORARY.getType());
            sysFileRefMapper.delete(lw);
            for (SysFileRef ref : sysFileRefs) {
                ref.setRedId(quarters.getPlanPracticalId());
                ref.setType(SysFileRefEnum.PLAN_TEMPORARY.getType());
                ref.setCreated(quarterStandardVo.getUpdated());
                ref.setCreateTime(now);
                ref.setUpdated(quarterStandardVo.getUpdated());
                ref.setUpdateTime(now);
                sysFileRefMapper.insert(ref);
            }
        }
        return AjaxResult.success();
    }

    @Override
    public String importPlanQuarter(List<PlanQuarterStandardVo> planQuarters, boolean isUpdateSupport, LoginUser loginUser) {
        if (StringUtils.isNull(planQuarters) || planQuarters.size() == 0) {
            throw new ServiceException("导入季度计划数据不能为空！");
        }
        List<PlanQuarter> list = new ArrayList<>();
        for (PlanQuarterStandardVo standardVo : planQuarters) {
            PlanQuarter quarter = new PlanQuarter();
            BeanUtils.copyProperties(standardVo, quarter);
            quarter.setPurchaseDeptName(standardVo.getPurchaseDeptId());
            list.add(quarter);
        }
        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 (PlanQuarter planQuarter : list) {
            try {
                //验证项目名称是否重复导入
                //将录入信息中的值更改为要保存的数据
                if (planQuarterMapper.countProjectName(planQuarter.getProjectName()) == 0) {
                    //采购单位
                    SysDept info = deptMapper.checkDeptNameOnlyOne(planQuarter.getPurchaseDeptName());
                    if (!ObjectUtils.isEmpty(info)) {
                        planQuarter.setPurchaseDeptId(String.valueOf(info.getDeptId()));
                    } else {
                        ++failureNum;
                        failureMsg.append("*" + failureNum + "*采购单位“" + planQuarter.getPurchaseDeptName() + "”不存在");
                    }
                    planQuarter.setProjectType(projectTypesMap.get(planQuarter.getProjectType()));
                    planQuarter.setProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
                    planQuarter.setPurchaseMode(planPurchaseModesMap.get(planQuarter.getPurchaseMode()));
                    //项目属性是多选字段
                    StringBuilder builder = new StringBuilder();
                    if (planQuarter.getProjectAttr().contains(",")) {
                        String[] split = planQuarter.getProjectAttr().split(",");
                        for (String s : split) {
                            if (!planQuarter.getProjectAttr().endsWith(s)) {
                                builder.append(projectAttributes.get(s) + ",");
                            } else {
                                builder.append(projectAttributes.get(s));
                            }
                        }
                    } else {
                        builder.append(projectAttributes.get(planQuarter.getProjectAttr()));
                    }
                    planQuarter.setProjectAttr(builder.toString());
                    planQuarter.setIsExcess(deptService.isExcessOrNo(planQuarter.getProjectType(), planQuarter.getEvaluation(), Long.valueOf(planQuarter.getPurchaseDeptId())));
                    planQuarter.setCreated(String.valueOf(loginUser.getUserId()));
                    planQuarter.setCreateTime(new Date());
                    planQuarterMapper.insertPlanQuarter(planQuarter);
                    successNum++;
                    successMsg.append("*" + successNum + "、项目 " + planQuarter.getProjectName() + " 导入成功!");
                } else {
                    failureNum++;
                    failureMsg.append(failureNum + "*项目 " + planQuarter.getProjectName() + " 已存在！/n");
                }
            } catch (Exception exc) {
                failureNum++;
                String msg = "*" + successNum + "*项目 " + planQuarter.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(PlanQuarterStandardVo quarterStandardVo) {
        PlanQuarter byId = planQuarterMapper.getById(quarterStandardVo.getPlanPracticalId());
        if (!isBetweenValue(byId)) {
            return AjaxResult.error("所创计划不在提报日期内!");
        }
        BigDecimal evaluation = byId.getEvaluation();
        SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
        Long deptId = sysUser.getDeptId();
        if (!pmAuditDeptRefService.insertPmAuditDeptRefs(byId.getPlanPracticalId(),
                "1",
                deptId,
                evaluation,
                sysUser.getUserId(),
                byId.getProjectType())) {
            throw new ServiceException("审核关联数据插入失败");
        }

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

    @Override
    @Transactional
    public AjaxResult reviewTo(PlanQuarterStandardVo 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.getPlanPracticalId());
        lw.eq(PmAuditDeptRef::getRefType, "1");
        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();
    }

    public AjaxResult realReviewTo(PlanQuarterStandardVo vo, boolean flay) {
        Date now = new Date();
        //季度计划审核通过后同步到年度计划和项目管理
        PlanQuarter quarters = new PlanQuarter();
        PlanQuarter byId = planQuarterMapper.getById(vo.getPlanPracticalId());
        PlanYears ofYears = new PlanYears();
        BeanUtils.copyProperties(byId, ofYears);
        ofYears.setProjectStatus(ProjectStatus.PLANTOEXAMINE.getCode());
        //上传审核文件并赋予计划审核通过
        List<SysFileRef> sysFileRefuses = vo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefuses)) {
            for (SysFileRef ref : sysFileRefuses) {
                ref.setRedId(vo.getPlanPracticalId());
                ref.setType(SysFileRefEnum.PLAN_TEMPORARY_EXAMINE.getType());
                ref.setCreated(vo.getUpdated());
                ref.setCreateTime(now);
                ref.setUpdated(vo.getUpdated());
                ref.setUpdateTime(now);
                sysFileRefMapper.insert(ref);
            }
        }
        if (flay) {
            planYearsMapper.insertPlanYears(ofYears);
            quarters.setPlanYearId(ofYears.getPlanYearId());
            //同步到项目管理
            PmDemand demand = new PmDemand();
            BeanUtils.copyProperties(byId, demand);
            demand.setEvaluation(byId.getEvaluation().doubleValue());
            demand.setIsExcess(Integer.parseInt(byId.getIsExcess()));
            demand.setPlanId(byId.getPlanPracticalId());
            demand.setPurchaseDeptId(Long.valueOf(byId.getPurchaseDeptId()));
            //同步到项目管理状态为需求待填制
            demand.setProjectStatus(PmProjectStatus.DEMAND_WAIT_FILL.getCode());
            demand.setCreateTime(now);
            pmDemandMapper.insert(demand);
            demandService.updateDemandWarnStatus(demand.getDemandId());
            //计划附件也进行同步---查询季度计划附件后同步到项目需求附件和年度计划附件
            LambdaQueryWrapper<SysFileRef> sysFileRefLp = new LambdaQueryWrapper<>();
            sysFileRefLp.eq(SysFileRef::getRedId, vo.getPlanPracticalId());
            sysFileRefLp.in(SysFileRef::getType, Arrays.asList(SysFileRefEnum.PLAN_TEMPORARY.getType(), SysFileRefEnum.PLAN_TEMPORARY_EXAMINE.getType()));
            List<SysFileRef> sysFileRefs = sysFileRefMapper.selectList(sysFileRefLp);
            if (!ObjectUtils.isEmpty(sysFileRefs)) {
                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);
                }
                for (SysFileRef ref : sysFileRefs) {
                    ref.setRedId(ofYears.getPlanYearId());
                    ref.setType(SysFileRefEnum.PLAN_YEAR.getType());
                    ref.setId(null);
                    ref.setCreated(vo.getUpdated());
                    ref.setCreateTime(now);
                    ref.setUpdated(vo.getUpdated());
                    ref.setUpdateTime(now);
                    sysFileRefMapper.insert(ref);
                }
            }

            planQuarterMapper.updateById(quarters);
            //赋予项目状态已审核
            vo.setProjectStatus(ProjectStatus.PLANTOEXAMINE.getCode());
            return review(vo);
        }
        return AjaxResult.success("成功");

    }

    @Override
    @Transactional
    public AjaxResult reviewReturn(PlanQuarterStandardVo vo) {
        Date now = new Date();
        vo.setProjectStatus(ProjectStatus.PLANTOBACK.getCode());
        //上传审核文件并赋予计划审核退回
        List<SysFileRef> sysFileRefuses = vo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefuses)) {
            for (SysFileRef ref : sysFileRefuses) {
                ref.setRedId(vo.getPlanPracticalId());
                ref.setType(SysFileRefEnum.PLAN_TEMPORARY_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(PlanQuarterStandardVo vo) {
        int review = planQuarterMapper.review(vo);
        if (review != 1) {
            return AjaxResult.error("项目状态数据异常");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult appUpdate(PlanQuarterStandardVo vo) {
        //如果项目管理中数据已填制，则不允许申请修改
        LambdaQueryWrapper<PmDemand> demandLp = new LambdaQueryWrapper<>();
        demandLp.eq(PmDemand::getPlanId, vo.getPlanPracticalId());
        PmDemand demand = pmDemandMapper.selectOne(demandLp);
        if (!String.valueOf(demand.getProjectStatus()).equals(PmProjectStatus.DEMAND_WAIT_FILL.getCode())) {
            return AjaxResult.error("项目信息已填制，不可更改");
        }
        //申请后会成为未提交的状态，可以进行修改
        vo.setProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
        int review = planQuarterMapper.review(vo);
        if (review != 1) {
            return AjaxResult.error("项目状态数据异常");
        }
        return AjaxResult.success();
    }

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

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

    @Override
    public AjaxResult downLoadPlanFile(PlanQuarterStandardVo quarterStandardVo) {

        return AjaxResult.success();
    }

    @Override
    public List<PlanQuarter> queryPage(PlanQuarterStandardVo vo) {
        List<PlanQuarter> query = planQuarterMapper.query(vo);
        if (!ObjectUtils.isEmpty(query)) {
            query.stream().map(o -> {
                LambdaQueryWrapper<PmAuditDeptRef> lw = new LambdaQueryWrapper();
                lw.eq(PmAuditDeptRef::getRefId, o.getPlanPracticalId());
                lw.eq(PmAuditDeptRef::getRefType, "1");
                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));
                *   over: -1
                * */
                    o.setFlag(f);
                }
                return o;
            }).collect(Collectors.toList());
        }
        return query;
    }

    //字段赋值对应的名称
    public List<PlanQuarterResponseVo> changeTo(List<PlanQuarter> planQuarters) {
        //获取季度计划各个季度提报时间的阈值
        List<SysDictData> supTime = dictTypeService.selectDictDataByType("sys_quarterly_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<PlanQuarterResponseVo> list = new ArrayList<PlanQuarterResponseVo>();
        for (PlanQuarter planQuarter : planQuarters) {
            PlanQuarterResponseVo responseVo = new PlanQuarterResponseVo();
            SysDeptResponseVo sysDeptResponseVo = (SysDeptResponseVo) deptService.selectDeptById(Long.valueOf(planQuarter.getPurchaseDeptId())).get("sysDept");
            planQuarter.setPurchaseDeptName(sysDeptResponseVo.getDeptName());

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

            try {
                responseVo.setTipsMessage(planQuarterGetTips(thresholdMap, alertTimeMap));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            list.add(responseVo);
        }
        return list;
    }

    /**
     * 根据季度计划在各个季度提报时间的阈值进行提示
     *
     * @return
     */
    public String planQuarterGetTips(HashMap<String, String> thresholdMap, HashMap<String, String> alertTimeMap) throws ParseException {
        //提示信息：定义距离结束时间*天内提示
        int alertDay = Integer.parseInt(alertTimeMap.get("计划提报时间"));
        //提示信息：定义距离结束时间一周内提示
        Integer remindTine = 1000 * 60 * 60 * 24 * alertDay;  //提示语
        String subTips = "";
        //季度提报时间的结束时间阈值
        Date thresholdTime = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        for (QuarterEnum val : QuarterEnum.values()) {
            if (val.getInfo().contains(date.getMonth() + "")) {
                switch (val.getCode()) {
                    case "1":
                        thresholdTime = dateFormat.parse(thresholdMap.get("第一季度结束时间"));
                    case "2":
                        thresholdTime = dateFormat.parse(thresholdMap.get("第二季度结束时间"));
                    case "3":
                        thresholdTime = dateFormat.parse(thresholdMap.get("第三季度结束时间"));
                    case "4":
                        thresholdTime = dateFormat.parse(thresholdMap.get("第四季度结束时间"));
                    default:
                }
                break;
            }
        }
        thresholdTime.setYear(date.getYear());
        double surplus = thresholdTime.getTime() - date.getTime();
        //少于一周便提醒
        if (surplus < remindTine && surplus > 0) {
            //剩余天数(向上取整)
            int i = new Double(Math.ceil(surplus / 1000 / 60 / 60 / 24)).intValue();
            if (i > 0) {
                subTips = "距离计划提报时间不足" + i + "天";
            }
        }
        return subTips;
    }

    //是否在提报时间内
    public Boolean isBetweenValue(PlanQuarter planQuarter) {
        //获取年度计划提报时间的阈值
        //获取季度计划各个季度提报时间的阈值
        List<SysDictData> supTime = dictTypeService.selectDictDataByType("sys_quarterly_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 thresholdTimeStart = null;
        Date thresholdTimeEnd = null;
        Date subTime = planQuarter.getPlanDemandSubTime();
        try {
            for (QuarterEnum val : QuarterEnum.values()) {
                if (val.getInfo().contains(subTime.getMonth() + "")) {
                    switch (val.getCode()) {
                        case "1":
                            thresholdTimeStart = dateFormat.parse(thresholdMap.get("第一季度开始时间"));
                            thresholdTimeEnd = dateFormat.parse(thresholdMap.get("第一季度结束时间"));
                            break;
                        case "2":
                            thresholdTimeStart = dateFormat.parse(thresholdMap.get("第二季度开始时间"));
                            thresholdTimeEnd = dateFormat.parse(thresholdMap.get("第二季度结束时间"));
                            break;
                        case "3":
                            thresholdTimeStart = dateFormat.parse(thresholdMap.get("第三季度开始时间"));
                            thresholdTimeEnd = dateFormat.parse(thresholdMap.get("第三季度结束时间"));
                            break;
                        default:
                            thresholdTimeStart = dateFormat.parse(thresholdMap.get("第四季度开始时间"));
                            thresholdTimeEnd = dateFormat.parse(thresholdMap.get("第四季度结束时间"));
                    }
                    break;
                }
            }
            if (!ObjectUtils.isEmpty(thresholdTimeStart) && !ObjectUtils.isEmpty(thresholdTimeEnd)) {
                if (subTime.before(thresholdTimeStart) || subTime.after(thresholdTimeEnd)) {
                    return false;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return true;
    }

}
