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.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.DateUtils;
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.PmAuditDeptRefMapper;
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.Calendar;
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 SysFileRefService sysFileRefService;
    @Autowired
    private PmAuditDeptRefService pmAuditDeptRefService;
    @Autowired
    private PmAuditDeptRefMapper pmAuditDeptRefMapper;

    @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.getProjectStatus())) {
                    lw.eq(PlanYears::getProjectStatus, vo.getProjectStatus());
                }
                if (!ObjectUtils.isEmpty(vo.getParams())) {
                    if (!ObjectUtils.isEmpty(vo.getParams().get("beginTime"))) {
                        lw.ge(PlanYears::getPlanDemandSubTime, vo.getParams().get("beginTime").toString() + "-01");
                    }
                    if (!ObjectUtils.isEmpty(vo.getParams().get("endTime"))) {
                        SimpleDateFormat dateFormaH = new SimpleDateFormat("yyyy-MM");
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        Date ofMonth = DateUtils.getLastDayOfMonth(dateFormaH.parse(vo.getParams().get("endTime").toString()));
                        lw.le(PlanYears::getPlanDemandSubTime, dateFormat.format(ofMonth) + " 23:59:59:999");
                    }
                }
                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.getProjectStatus())) {
                    lw.eq(PlanYears::getProjectStatus, vo.getProjectStatus());
                } else {
                    lw.in(PlanYears::getProjectStatus, "1,3");
                }
                if (!ObjectUtils.isEmpty(vo.getParams())) {
                    if (!ObjectUtils.isEmpty(vo.getParams().get("beginTime"))) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
                        Date ofMonth = dateFormat.parse(vo.getParams().get("beginTime").toString() + "-01");
                        lw.ge(PlanYears::getPlanDemandSubTime, ofMonth);
                    }
                    if (!ObjectUtils.isEmpty(vo.getParams().get("endTime"))) {
                        SimpleDateFormat dateFormaH = new SimpleDateFormat("yyyy-MM");
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        SimpleDateFormat dateFormatT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                        Date ofMonth = DateUtils.getLastDayOfMonth(dateFormaH.parse(vo.getParams().get("endTime").toString()));
                        Date parse = dateFormatT.parse(dateFormat.format(ofMonth) + " 23:59:59:999");
                        lw.le(PlanYears::getPlanDemandSubTime, parse);
                    }
                }
                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("该项目名称已经存在");
        }
        PlanYears ofYears = new PlanYears();
        try {
            BeanUtils.copyProperties(yearsStandardVo, ofYears);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断是否为超额计划
        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("该项目名称已经存在");
        }
        PlanYears ofYears = new PlanYears();
        try {
            BeanUtils.copyProperties(yearsStandardVo, ofYears);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ofYears.setUpdateTime(new Date());
        planYearsMapper.updateById(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) {
        //获取字典数据
        HashMap<String, HashMap<String, String>> planEnums = dictTypeService.getAboutEnums();
        //项目属性
        HashMap<String, String> projectAttributes = planEnums.get("projectAttributes");
        //项目类型
        HashMap<String, String> projectTypesMap = planEnums.get("projectTypesAds");
        //预算科目
        HashMap<String, String> budgetAccountMap = planEnums.get("budgetAccount");
        //采购服务站
        HashMap<String, String> purchaseServicesMap = planEnums.get("purchaseServices");
        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);
        }

        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() + "”不存在");
                    }
                    //机关业务指导处是多选字段
                    StringBuilder zBuilder = new StringBuilder();
                    if (ofYear.getOrganDivision().contains(",")) {
                        String[] split = ofYear.getOrganDivision().split(",");
                        for (String s : split) {
                            SysDept infoTow = deptMapper.checkDeptNameOnlyOne(s);
                            //不是最后一位就加‘,’，是就直接结尾
                            if (!ofYear.getOrganDivision().endsWith(s)) {
                                if (!ObjectUtils.isEmpty(infoTow)) {
                                    zBuilder.append(infoTow.getDeptId() + ",");
                                } else {
                                    ++failureNum;
                                    failureMsg.append(failureNum + "、机关业务指导处(科)“" + s + "”不存在");
                                }
                            } else {
                                if (!ObjectUtils.isEmpty(infoTow)) {
                                    zBuilder.append(infoTow.getDeptId());
                                } else {
                                    ++failureNum;
                                    failureMsg.append(failureNum + "、机关业务指导处(科)“" + s + "”不存在");
                                }
                            }
                        }
                        //去掉末尾的标点符号
                        String zs = zBuilder.toString();
                        if (zs.endsWith(",")) {
                            zBuilder.replace(0, zBuilder.length(), "");
                            zBuilder.append(zs.substring(0, zs.length() - 1));
                        }
                    } else {
                        //没有多选
                        SysDept infoTow = deptMapper.checkDeptNameOnlyOne(ofYear.getOrganDivision());
                        if (!ObjectUtils.isEmpty(infoTow)) {
                            zBuilder.append(infoTow.getDeptId());
                        } else {
                            ++failureNum;
                            failureMsg.append(failureNum + "、机关业务指导处(科)“" + ofYear.getOrganDivision() + "”不存在");
                        }
                    }
                    ofYear.setOrganDivision(zBuilder.toString());


                    ofYear.setProjectType(projectTypesMap.get(ofYear.getProjectType()));
                    ofYear.setPurchaseServices(purchaseServicesMap.get(ofYear.getPurchaseServices()));
                    ofYear.setBudgetAccount(budgetAccountMap.get(ofYear.getBudgetAccount()));
                    ofYear.setProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());
                    //项目属性是多选字段
                    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.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() + "】已存在！");
                }
            } 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("所创计划不在提报日期内!");
        }
        //申请修改之后再次提交，先清除上一次提交后的审核记录
        PmAuditDeptRef ref = new PmAuditDeptRef();
        ref.setRefId(byId.getPlanYearId()).setRefType("0").setProjectType(byId.getProjectType()).setEvaluation(byId.getEvaluation());
        PlanQuarterServiceImpl.refIsExist(ref, pmAuditDeptRefMapper);
        PlanQuarterServiceImpl.insertAuditDeptRef(userService, pmAuditDeptRefService, ref);

        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) {
        if (flay) {
            //赋予项目状态已审核
            vo.setProjectStatus(ProjectStatus.PLANTOEXAMINE.getCode());
            return review(vo);
        }
        return AjaxResult.success("成功");
    }

    @Override
    @Transactional
    public AjaxResult reviewReturn(PlanYearsStandardVo vo) {
        vo.setProjectStatus(ProjectStatus.PLANTOBACK.getCode());
        return review(vo);
    }

    private AjaxResult review(PlanYearsStandardVo vo) {
        Date now = new Date();
        //上传审核文件
        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);
            }
        }
        int review = planYearsMapper.review(vo);
        if (review != 1) {
            return AjaxResult.error("项目状态数据异常");
        }
        return AjaxResult.success();
    }


    @Override
    public AjaxResult sendLetter(PlanYearsStandardVo yearsStandardVo) {
        PlanYears plan = new PlanYears();
        BeanUtils.copyProperties(yearsStandardVo, plan);
        plan.setSendLetter("1");
        plan.setLetterTime(new Date());
        int review = planYearsMapper.updateById(plan);
        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();
    }

    /**
     * 需求单位--首页--计划管理总数
     *
     * @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() {
        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) && !SysUser.isAdmin(SecurityUtils.getUserId())) {
                lw.in(PmDemand::getDemandId, list.stream().map(PmAuditDeptRef::getRefId).collect(Collectors.toList()));
            }
            lw.eq(PmDemand::getPurchaseDeptId, SecurityUtils.getDeptId());
        } 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() {
        PmDemandReqVo pmDemandReqVo = new PmDemandReqVo();
        pmDemandReqVo.setPageNum(1L);
        pmDemandReqVo.setPageSize(10L);
        pmDemandReqVo.setUserId(SecurityUtils.getUserId());
        pmDemandReqVo.setIsAdmin(SysUser.isAdmin(SecurityUtils.getUserId()));
        pmDemandReqVo.setDeptId(SecurityUtils.getDeptId());
        pmDemandReqVo.setPurchaseDeptId(Math.toIntExact(SecurityUtils.getDeptId()));
        IPage<PmDemandResVo> page = demandService.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())
                        .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());
    }

    @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())
                        .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());
    }

    /**
     * 查询需求单位待办事项(计划待提交)
     *
     * @return
     */
    @Override
    public List<PlanQuarterResponseVo> planWaitCommit() {
        //是否是查询审核（要过滤掉本单位的超额计划）
        String isAd = "false";
        return getListByProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode(), isAd);
    }

    /**
     * 采购管理部门首页待办事项(计划待审核)
     *
     * @return
     */
    @Override
    public List<PlanQuarterResponseVo> planWaitExamine() {
        //是否是查询审核（要过滤掉本单位的超额计划）
        String isAd = "true";
        return getListByProjectStatus(ProjectStatus.PLANWAIEXAMINE.getCode(), isAd);
    }

    /**
     * 需求单位待办事项
     */
    @Override
    public AjaxResult demandUnitWillManipulateTotal() {
        //计划待提交，需求待提交，合同待填制，项目建设待完成
        String isAd = "false";
        List<PlanQuarterResponseVo> planRes = getListByProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode(), isAd);
        List<PmDemand> demandRes = demandService.demandWaitCommit();
        demandRes.addAll(demandService.contractWaitFilled());
        demandRes.addAll(demandService.projectWaitFinish());
        List<PmDemandResVo> resVos = demandService.listToVoList(demandRes);
        return AjaxResult.success(planAndProjectToHome(planRes, resVos));
    }

    /**
     * 需求单位待办事项
     */
    @Override
    public AjaxResult demandUnitWillManipulateTotalNum() {
        List<StatisticalChartsResVo> result = new ArrayList<>();
        //计划待提交，需求待提交，合同待填制，项目建设待完成
        String isAd = "false";
        Integer numByProjectStatus = getNumByProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode(), isAd);
        Integer numByStatus = demandService.getNumByStatus(PmProjectStatus.DEMAND_WAIT_COMMIT.getCode());
        Integer numByStatus1 = demandService.getNumByStatus(PmProjectStatus.CONTRACT_WAIT_FILL.getCode());
        Integer numByStatus2 = demandService.getNumByStatus(PmProjectStatus.UNDER_CONSTRUCTION.getCode());
        StatisticalChartsResVo chartsResVo = new StatisticalChartsResVo();
        chartsResVo.setColumnName("计划待提交");
        chartsResVo.setNum(numByProjectStatus);
        result.add(chartsResVo);

        StatisticalChartsResVo chartsResVo1 = new StatisticalChartsResVo();
        chartsResVo1.setColumnName("需求待提交");
        chartsResVo1.setNum(numByStatus);
        result.add(chartsResVo1);

        StatisticalChartsResVo chartsResVo2 = new StatisticalChartsResVo();
        chartsResVo2.setColumnName("合同待填制");
        chartsResVo2.setNum(numByStatus1);
        result.add(chartsResVo2);

        StatisticalChartsResVo chartsResVo3 = new StatisticalChartsResVo();
        chartsResVo3.setColumnName("项目建设待完成");
        chartsResVo3.setNum(numByStatus2);
        result.add(chartsResVo3);

        StatisticalChartsResVo chartsResVoT = new StatisticalChartsResVo();
        chartsResVoT.setColumnName("全部");
        chartsResVoT.setNum(willTotal(result));
        result.add(chartsResVoT);

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult purchasingManagementWillManipulateTotal() {
        //计划待审核，需求待审核，任务待下达
        String isAd = "true";
        List<PlanQuarterResponseVo> planRes = getListByProjectStatus(ProjectStatus.PLANWAIEXAMINE.getCode(), isAd);
        List<PmDemand> demandRes = demandService.demandWaitExamine();
        demandRes.addAll(demandService.taskWaitRelease());
        List<PmDemandResVo> resVos = demandService.listToVoList(demandRes);
        return AjaxResult.success(planAndProjectToHome(planRes, resVos));
    }

    /**
     * 计划数据和项目数据一起返回给 首页--待办事项
     *
     * @return
     */
    public List<HomeToDoQueryResVo> planAndProjectToHome(List<PlanQuarterResponseVo> planRes, List<PmDemandResVo> demandRes) {
        List<HomeToDoQueryResVo> homeRes = new ArrayList<>();
        //转为首页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 homeRes;
    }

    @Override
    public AjaxResult purchasingManagementWillManipulateTotalNum() {
        List<StatisticalChartsResVo> result = new ArrayList<>();
        //计划待审核，需求待审核，任务待下达
        String isAd = "true";
        Integer status = getNumByProjectStatus(ProjectStatus.PLANWAIEXAMINE.getCode(), isAd);
        Integer numByStatus = demandService.getNumByStatus(PmProjectStatus.DEMAND_WAIT_AUDIT.getCode());
        Integer numByStatus1 = demandService.getNumByStatus(PmProjectStatus.TASK_WAIT_RELEASE.getCode());

        StatisticalChartsResVo chartsResVo = new StatisticalChartsResVo();
        chartsResVo.setColumnName("计划待审核");
        chartsResVo.setNum(status);
        result.add(chartsResVo);

        StatisticalChartsResVo chartsResVo1 = new StatisticalChartsResVo();
        chartsResVo1.setColumnName("需求待审核");
        chartsResVo1.setNum(numByStatus);
        result.add(chartsResVo1);

        StatisticalChartsResVo chartsResVo2 = new StatisticalChartsResVo();
        chartsResVo2.setColumnName("任务待下达");
        chartsResVo2.setNum(numByStatus1);
        result.add(chartsResVo2);

        StatisticalChartsResVo chartsResVoT = new StatisticalChartsResVo();
        chartsResVoT.setColumnName("全部");
        chartsResVoT.setNum(willTotal(result));
        result.add(chartsResVoT);
        return AjaxResult.success(result);
    }

    public Integer willTotal(List<StatisticalChartsResVo> result) {
        Integer re = 0;
        if (!ObjectUtils.isEmpty(result)) {
            for (StatisticalChartsResVo resVo : result) {
                re += resVo.getNum();
            }
        }
        return re;
    }

    /**
     * 通过年度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 (ObjectUtils.isEmpty(byId)) {
            return AjaxResult.error("没有查到相关数据！");
        }
        // 通过年度ID查询季度、临时计划详情
        ProvisionalPlan provisionalPlan = provisionalPlanMapper.selectProvisionalPlanByYearId(yearsStandardVo.getPlanYearId().intValue());
        if (ObjectUtils.isEmpty(provisionalPlan)) {
            return AjaxResult.error("没有查到相关数据！");
        }
        // 通过季度、临时计划ID查询项目数据
        PmDemand pmDemand = demandService.selectByPlanId(provisionalPlan.getPlanPracticalId());
        if (!ObjectUtils.isEmpty(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）
                // 合同信息 19之后（不包括19）
                // 项目建设 21
                Integer projectStatus = Integer.valueOf(pmDemand.getProjectStatus());
                if (projectStatus <= 4 || projectStatus == 18) {
                    detailType = "1";
                } else if (4 < projectStatus && projectStatus <= 8) {
                    detailType = "2";
                } else if (8 < projectStatus && projectStatus <= 9) {
                    detailType = "3";
                } else if (9 < projectStatus && projectStatus <= 19 && projectStatus != 18) {
                    detailType = "4";
                } else if (19 < projectStatus && projectStatus < 21) {
                    detailType = "5";
                } else if (projectStatus == 21) {
                    detailType = "6";
                }
            }
            PmDemandResVo vo = demandService.selectPmDemandByDemandId(pmDemand.getDemandId(), detailType);
            return AjaxResult.success(vo);
        } else {
            if (!ObjectUtils.isEmpty(provisionalPlan)) {
                return AjaxResult.success(provisionalPlan);
            } else {
                if (!ObjectUtils.isEmpty(byId)) {
                    return AjaxResult.success(byId);
                }
            }
        }
        return AjaxResult.error("没有查到相关数据！");
    }

    @Override
    public List<PlanYears> queryPage(PlanYearsStandardVo vo) throws ParseException {
        Map<String, Object> params = vo.getParams();
        if (!ObjectUtils.isEmpty(vo.getParams())) {
            if (!ObjectUtils.isEmpty(vo.getParams().get("beginTime"))) {
                params.put("beginTime" , vo.getParams().get("beginTime").toString() + "-01");
            }
            if (!ObjectUtils.isEmpty(vo.getParams().get("endTime"))) {
                SimpleDateFormat dateFormaH = new SimpleDateFormat("yyyy-MM");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date ofMonth = DateUtils.getLastDayOfMonth(dateFormaH.parse(vo.getParams().get("endTime").toString()));
                params.put("endTime" , dateFormat.format(ofMonth) + " 23:59:59:999");
            }
        }
        vo.setParams(params);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (!loginUser.getUserId().equals(Long.valueOf("1"))) {
            vo.setPurchaseDeptId(String.valueOf(loginUser.getDeptId()));
        }
        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);

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

                        fl = 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"))) {
                                fl = false;
                            }
                        }
                    }

                    /*
                    *  String s1="A";
                        String s2="B";
                System.out.println(s1.compareTo(s2));
                *    -1
                * */

                }
                if (vo.getCreated().equals("1")) {
                    fl = false;
                }
                o.setFlag(fl);
                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() {
        LoginUser user = SecurityUtils.getLoginUser();
        LambdaQueryWrapper<PlanQuarter> quarterLp = new LambdaQueryWrapper<PlanQuarter>();
        quarterLp.eq(PlanQuarter::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
        quarterLp.eq(PlanQuarter::getPurchaseDeptId, user.getDeptId());
        quarterLp.eq(PlanQuarter::getSendLetter, "1");
        List<PlanQuarter> planQuarters = planQuarterMapper.selectList(quarterLp);
        //转换返回类Vo
        List<PlanQuarterResponseVo> quarterRes = quartzServiceImpl.changeTo(planQuarters);
        return quarterRes;
    }

    /**
     * 查询已被催告发函的计划（数量）
     *
     * @return
     */
    @Override
    public Integer willSendLetterNum() {
        //年度计划没有催告，只有临时和季度计划有
        LoginUser user = SecurityUtils.getLoginUser();
        LambdaQueryWrapper<PlanQuarter> quarterLp = new LambdaQueryWrapper<PlanQuarter>();
        quarterLp.eq(PlanQuarter::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
        quarterLp.eq(PlanQuarter::getPurchaseDeptId, user.getDeptId());
        quarterLp.eq(PlanQuarter::getSendLetter, "1");
        Long aLong = planQuarterMapper.selectCount(quarterLp);
        return Math.toIntExact(aLong);
    }

    /**
     * 首页待办事项---计划待提交or待审核
     *
     * @param projectStatus
     * @return
     */
    public List<PlanQuarterResponseVo> getListByProjectStatus(String projectStatus, String isAd) {
        LoginUser user = SecurityUtils.getLoginUser();
        LambdaQueryWrapper<PlanYears> yearsLp = new LambdaQueryWrapper<PlanYears>();
        yearsLp.eq(PlanYears::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
        yearsLp.eq(PlanYears::getProjectStatus, projectStatus);
        if (isAd.equals("true")) {
            List<PmAuditDeptRef> list = new ArrayList<>();
            LambdaQueryWrapper<PmAuditDeptRef> l = new LambdaQueryWrapper<>();
            l.eq(PmAuditDeptRef::getDeptId, SecurityUtils.getDeptId());
            l.eq(PmAuditDeptRef::getRefType, "0");
            l.eq(PmAuditDeptRef::getStatus, 0);
            list = pmAuditDeptRefService.list(l);
            if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
                if (!ObjectUtils.isEmpty(list)) {
                    yearsLp.in(PlanYears::getPlanYearId, list.stream().map(PmAuditDeptRef::getRefId).collect(Collectors.toList()));
                } else {
                    //没有要当前用户单位进行审核的，就不显示
                    yearsLp.in(PlanYears::getPlanYearId, "0");
                }
            }
        } else {
            yearsLp.eq(PlanYears::getPurchaseDeptId, user.getDeptId());
        }
        List<PlanYears> planYears = planYearsMapper.selectList(yearsLp);

        LambdaQueryWrapper<PlanQuarter> quarterLp = new LambdaQueryWrapper<PlanQuarter>();
        quarterLp.eq(PlanQuarter::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
        quarterLp.eq(PlanQuarter::getProjectStatus, projectStatus);
        quarterLp.eq(PlanQuarter::getPurchaseDeptId, user.getDeptId());
        if (isAd.equals("true")) {
            List<PmAuditDeptRef> listF = new ArrayList<>();
            LambdaQueryWrapper<PmAuditDeptRef> lq = new LambdaQueryWrapper<>();
            lq.eq(PmAuditDeptRef::getDeptId, SecurityUtils.getDeptId());
            lq.eq(PmAuditDeptRef::getRefType, "1");
            lq.eq(PmAuditDeptRef::getStatus, 0);
            listF = pmAuditDeptRefService.list(lq);
            if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
                if (!ObjectUtils.isEmpty(listF)) {
                    quarterLp.in(PlanQuarter::getPlanPracticalId, listF.stream().map(PmAuditDeptRef::getRefId).collect(Collectors.toList()));
                } else {
                    //没有要当前用户单位进行审核的，就不显示
                    quarterLp.in(PlanQuarter::getPlanPracticalId, "0");
                }
            }
        } else {
            quarterLp.eq(PlanQuarter::getPurchaseDeptId, user.getDeptId());
        }
        List<PlanQuarter> planQuarters = planQuarterMapper.selectList(quarterLp);
        //融合一起
        List<PlanQuarterResponseVo> vos = planComplex(planYears, planQuarters);
        return vos;
    }

    //计划待提交、计划待审核的数量
    public Integer getNumByProjectStatus(String projectStatus, String isAd) {
        LoginUser user = SecurityUtils.getLoginUser();
        LambdaQueryWrapper<PlanYears> yearsLp = new LambdaQueryWrapper<PlanYears>();
        yearsLp.eq(PlanYears::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
        yearsLp.eq(PlanYears::getProjectStatus, projectStatus);
        if (isAd.equals("true")) {
            List<PmAuditDeptRef> list = new ArrayList<>();
            LambdaQueryWrapper<PmAuditDeptRef> l = new LambdaQueryWrapper<>();
            l.eq(PmAuditDeptRef::getDeptId, SecurityUtils.getDeptId());
            l.eq(PmAuditDeptRef::getRefType, "0");
            l.eq(PmAuditDeptRef::getStatus, "0");
            list = pmAuditDeptRefService.list(l);
            if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
                if (!ObjectUtils.isEmpty(list)) {
                    yearsLp.in(PlanYears::getPlanYearId, list.stream().map(PmAuditDeptRef::getRefId).collect(Collectors.toList()));
                } else {
                    //没有要当前用户单位进行审核的，就不显示
                    yearsLp.in(PlanYears::getPlanYearId, "0");
                }
            }
        } else {
            yearsLp.eq(PlanYears::getPurchaseDeptId, user.getDeptId());
        }
        Long count = planYearsMapper.selectCount(yearsLp);

        LambdaQueryWrapper<PlanQuarter> quarterLp = new LambdaQueryWrapper<PlanQuarter>();
        quarterLp.eq(PlanQuarter::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
        quarterLp.eq(PlanQuarter::getProjectStatus, projectStatus);
        if (isAd.equals("true")) {
            List<PmAuditDeptRef> listF = new ArrayList<>();
            LambdaQueryWrapper<PmAuditDeptRef> lq = new LambdaQueryWrapper<>();
            lq.eq(PmAuditDeptRef::getDeptId, SecurityUtils.getDeptId());
            lq.eq(PmAuditDeptRef::getRefType, "1");
            lq.eq(PmAuditDeptRef::getStatus, "0");
            listF = pmAuditDeptRefService.list(lq);
            if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
                if (!ObjectUtils.isEmpty(listF)) {
                    quarterLp.in(PlanQuarter::getPlanPracticalId, listF.stream().map(PmAuditDeptRef::getRefId).collect(Collectors.toList()));
                } else {
                    //没有要当前用户单位进行审核的，就不显示
                    quarterLp.in(PlanQuarter::getPlanPracticalId, "0");
                }
            }
        } else {
            quarterLp.eq(PlanQuarter::getPurchaseDeptId, user.getDeptId());
        }
        Long aLong = planQuarterMapper.selectCount(quarterLp);
        //融合一起
        return Math.toIntExact(count) + Math.toIntExact(aLong);
    }

    /**
     * 年度计划与季度数据一起
     *
     * @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> projectAttributes = planEnums.get("projectAttributes");
        //项目审核状态
        HashMap<String, String> projectStatusMap = planEnums.get("projectStatus");
        //项目类型
        HashMap<String, String> projectTypesMap = planEnums.get("projectTypes");
        //项目类型
        HashMap<String, String> projectTypesAdMap = planEnums.get("projectTypesAds");
        //预算科目
        HashMap<String, String> budgetAccountMap = planEnums.get("budgetAccount");
        //采购服务站
        HashMap<String, String> purchaseServicesMap = planEnums.get("purchaseServices");

        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 : budgetAccountMap.entrySet()) {
                if (!ObjectUtils.isEmpty(planYear.getBudgetAccount()) && planYear.getBudgetAccount().equals(entry.getValue())) {
                    planYear.setBudgetAccountStr(entry.getKey());
                    break;
                }
            }
            //采购服务站
            for (Map.Entry<String, String> entry : purchaseServicesMap.entrySet()) {
                if (!ObjectUtils.isEmpty(planYear.getPurchaseServices()) && planYear.getPurchaseServices().equals(entry.getValue())) {
                    planYear.setPurchaseServicesStr(entry.getKey());
                    break;
                }
            }
            //项目审核状态
            for (Map.Entry<String, String> entry : projectStatusMap.entrySet()) {
                if (!ObjectUtils.isEmpty(planYear.getProjectStatus()) && planYear.getProjectStatus().equals(entry.getValue())) {
                    planYear.setProjectStatusStr(entry.getKey());
                    break;
                }
            }
            //项目类型
            if (planYear.getProjectStatus().equals(ProjectStatus.PLANWAITCOMMIT)) {
                for (Map.Entry<String, String> entry : projectTypesMap.entrySet()) {
                    if (!ObjectUtils.isEmpty(planYear.getProjectType()) && planYear.getProjectType().equals(entry.getValue())) {
                        planYear.setProjectTypeStr(entry.getKey());
                        break;
                    }
                }
            } else {
                for (Map.Entry<String, String> entry : projectTypesAdMap.entrySet()) {
                    if (!ObjectUtils.isEmpty(planYear.getProjectType()) && planYear.getProjectType().equals(entry.getValue())) {
                        planYear.setProjectTypeStr(entry.getKey());
                        break;
                    }
                }
            }
            //项目属性为value拼接
            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.setProjectAttrName(builder.toString());
                } else {
                    for (Map.Entry<String, String> entry : projectAttributes.entrySet()) {
                        if (planYear.getProjectAttr().equals(entry.getValue())) {
                            planYear.setProjectAttrName(entry.getKey());
                            break;
                        }
                    }
                }
            }
            //机关业务指导处(科)为id拼接
            String organDivision = planYear.getOrganDivision();
            if (!ObjectUtils.isEmpty(organDivision)) {
                int length = organDivision.split(",").length;
                SysDept sysDept = new SysDept();
                if (length > 1) {
                    StringBuilder builder = new StringBuilder();
                    String[] split = organDivision.split(",");
                    for (String s : split) {
                        sysDept = deptService.selectById(Long.valueOf(s));
                        if (!ObjectUtils.isEmpty(sysDept)) {
                            if (!organDivision.endsWith(s)) {
                                builder.append(sysDept.getDeptName() + ",");
                            } else {
                                builder.append(sysDept.getDeptName());
                            }
                        }
                    }
                    planYear.setOrganDivisionStr(builder.toString());
                } else if (length == 1) {
                    sysDept = deptService.selectById(Long.valueOf(organDivision));
                    if (!ObjectUtils.isEmpty(sysDept)) {
                        planYear.setOrganDivisionStr(sysDept.getDeptName());
                    }
                }
            }
            if (!ObjectUtils.isEmpty(planYear.getAppDelete())) {
                //申请过的不能再申请
                planYear.setAppDeleteDo("false");
            } else if (planYear.getProjectStatus().equals(ProjectStatus.PLANWAIEXAMINE.getCode())) {
                //提交后可以申请撤销
                planYear.setAppDeleteDo("true");
            }
            BeanUtils.copyProperties(planYear, responseVo);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            responseVo.setPlanDemandSubTimeStr(sdf.format(responseVo.getPlanDemandSubTime()));
            responseVo.setPlanPurchaseFinishTimeStr(sdf.format(responseVo.getPlanPurchaseFinishTime()));
            responseVo.setPlanDeliverTimeStr(sdf.format(responseVo.getPlanDeliverTime()));
            try {
                responseVo.setTipsMessage(planYearsGetTips(responseVo, thresholdMap, alertTimeMap));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            list.add(responseVo);
        }
        return list;
    }

    @Override
    @Transactional
    public AjaxResult adPurchaseServices(PlanYearsStandardVo yearsStandardVo) {
        PlanYears years = new PlanYears();
        BeanUtils.copyProperties(yearsStandardVo, years);
        if (planYearsMapper.updateById(years) == 1) {
            return AjaxResult.success("成功");
        }
        return AjaxResult.success("成功");
    }

    @Override
    public AjaxResult appDelete(PlanYearsStandardVo yearsStandardVo) {
        PlanQuarter byPlanYearId = planQuarterMapper.getByPlanYearId(yearsStandardVo.getPlanYearId());
        //需求待填制可以申请，需求建档就不能申请
        if (!ObjectUtils.isEmpty(byPlanYearId)) {
            PmDemand demand = demandService.selectByPlanId(byPlanYearId.getPlanPracticalId());
            if (!ObjectUtils.isEmpty(demand) && !demand.getProjectStatus().equals(PmProjectStatus.DEMAND_WAIT_FILL.getCode())) {
                return AjaxResult.error("改需求已建档，不可进行撤销");
            }
        }
        PlanYears years = new PlanYears();
        BeanUtils.copyProperties(yearsStandardVo, years);
        years.setAppDelete("true");
        planYearsMapper.updateById(years);
        return AjaxResult.success("申请成功");
    }

    @Override
    public AjaxResult handleApp(PlanYearsStandardVo yearsStandardVo) {
        //getProjectAttr传值1为同意。-1为拒绝
        if ("1".equals(yearsStandardVo.getProjectAttr())) {
            planYearsMapper.deletePlanYearsById(yearsStandardVo.getPlanYearId());
            //年度计划撤销后季度计划也同步撤销
            PlanQuarter byPlanYearId = planQuarterMapper.getByPlanYearId(yearsStandardVo.getPlanYearId());
            if (!ObjectUtils.isEmpty(byPlanYearId)) {
                planQuarterMapper.deletePlanQuarterById(byPlanYearId.getPlanPracticalId());
            }
            return AjaxResult.success("已成功进行撤销");
        }
        PlanYears years = new PlanYears();
        years.setPlanYearId(yearsStandardVo.getPlanYearId());
        years.setAppDelete("false");
        planYearsMapper.updateById(years);
        return AjaxResult.success("已拒绝改申请");
    }

    @Override
    public List<Integer> idNotInQuarter() {
        return planYearsMapper.idNotInQuarter();
    }

    /**
     * 根据年度计划提报时间的阈值进行提示
     *
     * @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 "";
    }

}
