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.github.pagehelper.PageInfo;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.entity.SysDept;
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.SysFileRefEnum;
import com.ozs.common.exception.ServiceException;
import com.ozs.common.utils.DateUtils;
import com.ozs.common.utils.PageUtils;
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.ProvisionalPlan;
import com.ozs.plan.doman.vo.requestVo.PlanQuarterStandardVo;
import com.ozs.plan.doman.vo.requestVo.ProvisionalPlanVo;
import com.ozs.plan.doman.vo.responseVo.ProvisionalPlanResVo;
import com.ozs.plan.mapper.PlanYearsMapper;
import com.ozs.plan.mapper.ProvisionalPlanMapper;
import com.ozs.plan.service.PlanQuarterService;
import com.ozs.plan.service.ProvisionalPlanService;
import com.ozs.pm.doman.PmAuditDeptRef;
import com.ozs.pm.doman.PmDemand;
import com.ozs.pm.mapper.PmAuditDeptRefMapper;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProvisionalPlanServiceImpl extends ServiceImpl<ProvisionalPlanMapper, ProvisionalPlan> implements ProvisionalPlanService {

    @Autowired
    private ProvisionalPlanMapper provisionalPlanMapper;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private PlanYearsMapper planYearsMapper;
    @Autowired
    private SysFileRefMapper sysFileRefMapper;
    @Autowired
    private SysFileService fileService;
    @Autowired
    private PmDemandMapper pmDemandMapper;
    @Autowired
    private IPmDemandService demandService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private PmAuditDeptRefService pmAuditDeptRefService;
    @Autowired
    private PmAuditDeptRefMapper pmAuditDeptRefMapper;
    @Autowired
    private PlanQuarterService quarterService;

    @Override
    public int deleteProvisionalPlanById(Long planPracticalId) {
        return provisionalPlanMapper.deleteProvisionalPlanById(planPracticalId);
    }

    @Override
    @Transactional
    public int updateProvisionalPlanById(ProvisionalPlanVo provisionalPlan) {
        //默认未超额
        if (ObjectUtils.isEmpty(provisionalPlan.getIsExcess())) {
            provisionalPlan.setIsExcess("0");
        }
        List<SysFileRef> sysFileRefs = provisionalPlan.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefs)) {
            // 删关联
            LambdaQueryWrapper<SysFileRef> lw = new LambdaQueryWrapper<>();
            lw.eq(SysFileRef::getRedId, provisionalPlan.getPlanPracticalId());
            lw.eq(SysFileRef::getType, SysFileRefEnum.PLAN_TEMPORARY.getType());
            sysFileRefMapper.delete(lw);
            for (SysFileRef ref : sysFileRefs) {
                ref.setRedId(provisionalPlan.getPlanPracticalId());
                ref.setType(SysFileRefEnum.PLAN_TEMPORARY.getType());
                ref.setCreated(provisionalPlan.getCreated());
                ref.setCreateTime(new Date());
                ref.setUpdated(provisionalPlan.getCreated());
                ref.setUpdateTime(new Date());
                sysFileRefMapper.insert(ref);
            }
        }
        return provisionalPlanMapper.updateProvisionalPlanById(provisionalPlan);
    }

    @Override
    public String importProvisionalPlan(List<ProvisionalPlan> provisionalPlans, boolean updateSupport, LoginUser loginUser) {
        // 字典项
        HashMap<String, HashMap<String, String>> planEnums = dictTypeService.getAboutEnums();
        HashMap<String, String> projectTypesMap = planEnums.get("projectTypes");
        HashMap<String, String> projectAttributes = planEnums.get("projectAttributes");

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (ProvisionalPlan ofProvisionalPlan : provisionalPlans) {
            try {
                //验证项目名称是否重复导入
                List<ProvisionalPlan> plan = provisionalPlanMapper.selectProjectName(ofProvisionalPlan.getProjectName());
                //将录入信息中的值更改为要保存的数据
                if (plan.size() == 0) {
                    //采购单位
                    SysDept info = deptMapper.checkDeptNameOnlyOne(ofProvisionalPlan.getPurchaseDeptName());
                    if (StringUtils.isNotNull(info)) {
                        ofProvisionalPlan.setPurchaseDeptId(String.valueOf(info.getDeptId()));
                    }
                    ofProvisionalPlan.setProjectType(projectTypesMap.get(ofProvisionalPlan.getProjectType()));
                    ofProvisionalPlan.setProjectStatus(ProjectStatus.PLANWAITCOMMIT.getCode());

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


                    //项目属性是多选字段
                    StringBuilder builder = new StringBuilder();
                    if (ofProvisionalPlan.getProjectAttr().contains(",")) {
                        String[] split = ofProvisionalPlan.getProjectAttr().split(",");
                        for (String s : split) {
                            if (!ofProvisionalPlan.getProjectAttr().endsWith(s)) {
                                builder.append(projectAttributes.get(s) + ",");
                            } else {
                                builder.append(projectAttributes.get(s));
                            }
                        }
                    } else {
                        builder.append(projectAttributes.get(ofProvisionalPlan.getProjectAttr()));
                    }
                    ofProvisionalPlan.setProjectAttr(builder.toString());
                    ofProvisionalPlan.setIsExcess(deptService.isExcessOrNo(ofProvisionalPlan.getProjectType(), ofProvisionalPlan.getEvaluation(), info.getDeptId()));
                    ofProvisionalPlan.setCreated(String.valueOf(loginUser.getUserId()));
                    ofProvisionalPlan.setCreateTime(new Date());
                    ofProvisionalPlan.setPlanType("1");
                    provisionalPlanMapper.insert(ofProvisionalPlan);
                    successNum++;
                    successMsg.append("*" + successNum + "、项目 " + ofProvisionalPlan.getProjectName() + " 导入成功!");
                } else {
                    failureNum++;
                    failureMsg.append("*" + successNum + "、项目 " + ofProvisionalPlan.getProjectName() + " 已存在");
                }
            } catch (Exception exc) {
                failureNum++;
                String msg = "*" + successNum + "、项目 " + ofProvisionalPlan.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
    public List<ProvisionalPlanResVo> selectProvisionalPlanExport(ProvisionalPlanVo vo, LoginUser loginUser) {
        List<ProvisionalPlan> list = new ArrayList<>();
        List<ProvisionalPlanResVo> provisionalPlanList = new ArrayList<>();
        try {
            int num = 1;
            int size = 200;
            while (size == 200) {
                LambdaQueryWrapper<ProvisionalPlan> lw = new LambdaQueryWrapper<ProvisionalPlan>();
                lw.eq(ProvisionalPlan::getPlanType, "1");
                lw.eq(ProvisionalPlan::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
                if (!loginUser.getUserId().equals(Long.valueOf("1"))) {
                    lw.eq(ProvisionalPlan::getPurchaseDeptId, loginUser.getDeptId());
                }
                lw.eq(ProvisionalPlan::getPlanType, "1");
                if (!ObjectUtils.isEmpty(vo.getProjectName())) {
                    lw.like(ProvisionalPlan::getProjectName, vo.getProjectName());
                }
                if (!ObjectUtils.isEmpty(vo.getPurchaseServices())) {
                    lw.eq(ProvisionalPlan::getPurchaseServices, vo.getPurchaseServices());
                }
                if (!ObjectUtils.isEmpty(vo.getIsExcess())) {
                    lw.eq(ProvisionalPlan::getIsExcess, vo.getIsExcess());
                }
                if (!ObjectUtils.isEmpty(vo.getProjectStatus())) {
                    lw.eq(ProvisionalPlan::getProjectStatus, vo.getProjectStatus());
                }
                if (!ObjectUtils.isEmpty(vo.getParams())) {
                    if (!ObjectUtils.isEmpty(vo.getParams().get("beginTime"))) {
                        lw.ge(ProvisionalPlan::getPlanDemandSubTime, vo.getParams().get("beginTime"));
                    }
                    if (!ObjectUtils.isEmpty(vo.getParams().get("endTime"))) {
                        SimpleDateFormat dateFormatT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                        Date parse = dateFormatT.parse(vo.getParams().get("endTime").toString() + " 23:59:59:999");
                        lw.le(ProvisionalPlan::getPlanDemandSubTime, parse);
                    }
                }

                Page<ProvisionalPlan> page = provisionalPlanMapper.selectPage(new Page<ProvisionalPlan>(num, size, false), lw);
                list.addAll(page.getRecords());
                size = page.getRecords().size();
                num++;
            }
            provisionalPlanList = changeTo(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return provisionalPlanList;
    }

    @Override
    @Transactional
    public int commitProvisionalPlan(ProvisionalPlanVo provisionalPlanVo) {
        ProvisionalPlan byId = provisionalPlanMapper.seletById(provisionalPlanVo.getPlanPracticalId());
        //申请修改之后再次提交，先清除上一次提交后的审核记录
        PmAuditDeptRef ref = new PmAuditDeptRef();
        ref.setRefId(byId.getPlanPracticalId()).setRefType("1").setProjectType(byId.getProjectType()).setEvaluation(byId.getEvaluation());
        PlanQuarterServiceImpl.refIsExist(ref, pmAuditDeptRefMapper);
        PlanQuarterServiceImpl.insertAuditDeptRef(userService, pmAuditDeptRefService, ref);
        return provisionalPlanMapper.commitProvisionalPlan(provisionalPlanVo.getPlanPracticalId());
    }

    @Override
    public AjaxResult seletById(Long planPracticalId) {
        ProvisionalPlan provisionalPlan = provisionalPlanMapper.seletById(planPracticalId);
        if (StringUtils.isNull(provisionalPlan)) {
            return AjaxResult.error("数据查询失败");
        }
        // 转换字段中文
        ProvisionalPlan provisionalPlanC = changeToProvisionalPlan(provisionalPlan);
        LambdaQueryWrapper<SysFileRef> lw = new LambdaQueryWrapper<>();
        lw.eq(SysFileRef::getRedId, provisionalPlanC.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<>();
        ProvisionalPlanVo provisionalPlanVo = new ProvisionalPlanVo();
        BeanUtils.copyProperties(provisionalPlanC, provisionalPlanVo);
        if (!ObjectUtils.isEmpty(fileRefs)) {
            for (SysFileRef ref : fileRefs) {
                SysFileInfo fileInfo = fileService.getById(ref.getFileId());
                fileInfos.add(fileInfo);
            }
            provisionalPlanVo.setFileInfos(fileInfos);
        }
        return AjaxResult.success(provisionalPlanVo);
    }


    @Override
    public AjaxResult selectProvisionalPlan(ProvisionalPlanVo vo, HttpServletRequest request, LoginUser loginUser) {
        List<ProvisionalPlanResVo> provisionalPlanList = new ArrayList<>();
        try {
            LambdaQueryWrapper<ProvisionalPlan> lw = new LambdaQueryWrapper<>();
            lw.eq(ProvisionalPlan::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
            lw.eq(ProvisionalPlan::getPlanType, "1");
            if (!loginUser.getUserId().equals(Long.valueOf("1"))) {
                lw.eq(ProvisionalPlan::getPurchaseDeptId, loginUser.getDeptId());
            }
            if (!ObjectUtils.isEmpty(vo.getProjectName())) {
                lw.like(ProvisionalPlan::getProjectName, vo.getProjectName());
            }
            if (!ObjectUtils.isEmpty(vo.getPurchaseServices())) {
                lw.eq(ProvisionalPlan::getPurchaseServices, vo.getPurchaseServices());
            }
            if (!ObjectUtils.isEmpty(vo.getIsExcess())) {
                lw.eq(ProvisionalPlan::getIsExcess, vo.getIsExcess());
            }
            if (!ObjectUtils.isEmpty(vo.getProjectStatus())) {
                lw.eq(ProvisionalPlan::getProjectStatus, vo.getProjectStatus());
            }
            if (!ObjectUtils.isEmpty(vo.getParams())) {
                if (!ObjectUtils.isEmpty(vo.getParams().get("beginTime"))) {
                    lw.ge(ProvisionalPlan::getPlanDemandSubTime, vo.getParams().get("beginTime"));
                }
                if (!ObjectUtils.isEmpty(vo.getParams().get("endTime"))) {
                    SimpleDateFormat dateFormatT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                    Date parse = dateFormatT.parse(vo.getParams().get("endTime").toString() + " 23:59:59:999");
                    lw.le(ProvisionalPlan::getPlanDemandSubTime, parse);
                }
            }
            lw.orderBy(true, false, ProvisionalPlan::getCreateTime);
            List<ProvisionalPlan> list = provisionalPlanMapper.selectList(lw);
            provisionalPlanList = changeTo(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Page pages = PageUtils.getPages(vo.getPageNum().intValue(), vo.getPageSize().intValue(), provisionalPlanList);
        PageInfo<ProvisionalPlan> provisionalPlanPageInfo = new PageInfo<>();
        if (!ObjectUtils.isEmpty(pages) && pages.getRecords().size() > 0) {
            provisionalPlanPageInfo.setList(pages.getRecords());
            provisionalPlanPageInfo.setSize(Math.toIntExact(pages.getSize()));
            provisionalPlanPageInfo.setPageNum(Math.toIntExact(pages.getCurrent()));
            provisionalPlanPageInfo.setTotal(pages.getTotal());
            provisionalPlanPageInfo.setPages(Integer.parseInt(pages.getPages() + ""));
        }
        return AjaxResult.success(provisionalPlanPageInfo);
    }

    @Override
    public AjaxResult selectProvisionalPlanAudit(ProvisionalPlanVo vo, HttpServletRequest request, LoginUser loginUser) {
        List<ProvisionalPlanResVo> provisionalPlanList = new ArrayList<>();
        try {
            LambdaQueryWrapper<ProvisionalPlan> lw = new LambdaQueryWrapper<>();
            lw.eq(ProvisionalPlan::getDelFlay, DataIsDelete.DataNOTDelete.getCode());
            lw.eq(ProvisionalPlan::getPlanType, "1");
            if (!loginUser.getUserId().equals(Long.valueOf("1"))) {
                lw.eq(ProvisionalPlan::getPurchaseDeptId, loginUser.getDeptId());
            }
            if (!ObjectUtils.isEmpty(vo.getProjectName())) {
                lw.like(ProvisionalPlan::getProjectName, vo.getProjectName());
            }
            if (!ObjectUtils.isEmpty(vo.getPurchaseServices())) {
                lw.eq(ProvisionalPlan::getPurchaseServices, vo.getPurchaseServices());
            }
            if (!ObjectUtils.isEmpty(vo.getIsExcess())) {
                lw.eq(ProvisionalPlan::getIsExcess, vo.getIsExcess());
            }
            if (!ObjectUtils.isEmpty(vo.getProjectStatus())) {
                lw.eq(ProvisionalPlan::getProjectStatus, vo.getProjectStatus());
            } else {
                lw.apply("  project_status IN (1,3)", "");
            }
            if (!ObjectUtils.isEmpty(vo.getParams())) {
                if (!ObjectUtils.isEmpty(vo.getParams().get("beginTime"))) {
                    lw.ge(ProvisionalPlan::getPlanDemandSubTime, vo.getParams().get("beginTime"));
                }
                if (!ObjectUtils.isEmpty(vo.getParams().get("endTime"))) {
                    SimpleDateFormat dateFormatT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date ofMonth = DateUtils.getLastDayOfMonth(dateFormat.parse(vo.getParams().get("endTime").toString()));
                    Date parse = dateFormatT.parse(dateFormat.format(ofMonth) + " 23:59:59:999");
                    lw.le(ProvisionalPlan::getPlanDemandSubTime, parse);
                }
            }
            lw.orderBy(true, false, ProvisionalPlan::getCreateTime);
            List<ProvisionalPlan> list = provisionalPlanMapper.selectList(lw);
            provisionalPlanList = changeTo(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Page pages = PageUtils.getPages(vo.getPageNum().intValue(), vo.getPageSize().intValue(), provisionalPlanList);
        PageInfo<ProvisionalPlan> provisionalPlanPageInfo = new PageInfo<>();
        if (!ObjectUtils.isEmpty(pages) && pages.getRecords().size() > 0) {
            provisionalPlanPageInfo.setList(pages.getRecords());
            provisionalPlanPageInfo.setSize(Math.toIntExact(pages.getSize()));
            provisionalPlanPageInfo.setPageNum(Math.toIntExact(pages.getCurrent()));
            provisionalPlanPageInfo.setTotal(pages.getTotal());
            provisionalPlanPageInfo.setPages(Integer.parseInt(pages.getPages() + ""));
        }
        return AjaxResult.success(provisionalPlanPageInfo);
    }

    @Override
    @Transactional
    public AjaxResult auditPass(ProvisionalPlanVo provisionalPlanVo) {
        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, provisionalPlanVo.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(provisionalPlanVo, flay);
        return AjaxResult.success();
    }

    public AjaxResult realReviewTo(ProvisionalPlanVo provisionalPlanVo, boolean flay) {
        Date now = new Date();
        ProvisionalPlan byId = provisionalPlanMapper.seletById(provisionalPlanVo.getPlanPracticalId());
        if (ObjectUtils.isEmpty(byId.getPlanYearId())) {
            PlanYears ofYears = new PlanYears();
            BeanUtils.copyProperties(byId, ofYears);
            ofYears.setProjectStatus(ProjectStatus.PLANTOEXAMINE.getCode());
            planYearsMapper.insertPlanYears(ofYears);
            byId.setPlanYearId(ofYears.getPlanYearId());
        }

        //上传审核文件
        PlanQuarterStandardVo standardVo = new PlanQuarterStandardVo();
        BeanUtils.copyProperties(provisionalPlanVo, standardVo);
        quarterService.upExamineFile(standardVo);
        if (flay) {
            PmDemand demand = new PmDemand();
            BeanUtils.copyProperties(byId, demand);
            demand.setPlanId(Long.valueOf(byId.getPlanPracticalId()));
            demand.setEvaluation(byId.getEvaluation().doubleValue());
            demand.setIsExcess(Integer.parseInt(byId.getIsExcess()));
            //同步到项目管理状态为需求待填制
            demand.setProjectStatus(PmProjectStatus.DEMAND_WAIT_FILL.getCode());
            demand.setPurchaseDeptId(Long.parseLong(byId.getPurchaseDeptId()));
            demand.setCreateTime(now);
            demand.setCreateBy(provisionalPlanVo.getUpdated());
            demand.setUpdateTime(demand.getCreateTime());
            demand.setUpdateBy(demand.getCreateBy());
            demand.setIsExcess(Integer.parseInt(byId.getIsExcess()));
            pmDemandMapper.insert(demand);
            demandService.updateDemandWarnStatus(demand.getDemandId());
            //计划附件也进行同步---查询临时计划附件后复制一份改为项目需求附件
            LambdaQueryWrapper<SysFileRef> sysFileRefLp = new LambdaQueryWrapper<>();
            sysFileRefLp.eq(SysFileRef::getRedId, byId.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);
                    sysFileRefMapper.insert(ref);
                }
                for (SysFileRef ref : sysFileRefs) {
                    ref.setRedId(byId.getPlanYearId());
                    ref.setType(SysFileRefEnum.PLAN_YEAR.getType());
                    ref.setId(null);
                    ref.setCreated(provisionalPlanVo.getUpdated());
                    ref.setCreateTime(now);
                    ref.setUpdated(provisionalPlanVo.getUpdated());
                    ref.setUpdateTime(now);
                    sysFileRefMapper.insert(ref);
                }
            }
            provisionalPlanMapper.updateById(byId);
            //赋予项目状态已审核
            provisionalPlanVo.setProjectStatus(ProjectStatus.PLANTOEXAMINE.getCode());
            return review(provisionalPlanVo);
        }
        return AjaxResult.success("成功");
    }

    @Override
    public AjaxResult auditNoPass(ProvisionalPlanVo provisionalPlanVo) {
        PlanQuarterStandardVo standardVo = new PlanQuarterStandardVo();
        BeanUtils.copyProperties(provisionalPlanVo, standardVo);
        //上传审核文件并赋予计划审核退回
        quarterService.upExamineFile(standardVo);
        provisionalPlanVo.setProjectStatus(ProjectStatus.PLANTOBACK.getCode());
        return review(provisionalPlanVo);
    }

    @Override
    public List<ProvisionalPlan> queryPage(ProvisionalPlanVo vo) throws ParseException {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (!loginUser.getUserId().equals(Long.valueOf("1"))) {
            vo.setPurchaseDeptId(loginUser.getDeptId());
        }
        List<ProvisionalPlan> provisionalPlanList = provisionalPlanMapper.query(vo);
        if (!ObjectUtils.isEmpty(provisionalPlanList)) {
            provisionalPlanList.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);
                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));
                *   over: -1
                * */

                }
                if (vo.getCreated().equals("1")) {
                    fl = false;
                }
                o.setFlag(fl);
                return o;
            }).collect(Collectors.toList());
        }
        return provisionalPlanList;
    }

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

    // 字典项负值
    public ProvisionalPlan changeToProvisionalPlan(ProvisionalPlan provisionalPlan) {
        HashMap<String, HashMap<String, String>> planEnums = dictTypeService.getAboutEnums();
        HashMap<String, String> projectTypesMap = planEnums.get("projectTypes");
        HashMap<String, String> projectAttributes = planEnums.get("projectAttributes");
        if (provisionalPlan.getPurchaseDeptId() != null) {
            SysDeptResponseVo sysDeptResponseVo = (SysDeptResponseVo) deptService.selectDeptById(Long.valueOf(provisionalPlan.getPurchaseDeptId())).get("sysDept");
            provisionalPlan.setPurchaseDeptName(sysDeptResponseVo.getDeptName());
        }
        for (Map.Entry<String, String> entry : projectTypesMap.entrySet()) {
            if (provisionalPlan.getProjectType() != null && provisionalPlan.getProjectType().equals(entry.getValue())) {
                provisionalPlan.setProjectTypeStr(entry.getKey());
                break;
            }
        }
        //项目属性是拼接的
        if (provisionalPlan.getProjectAttr().length() > 1) {
            StringBuilder builder = new StringBuilder();
            String[] split = provisionalPlan.getProjectAttr().split(",");
            for (String s : split) {
                for (Map.Entry<String, String> entry : projectAttributes.entrySet()) {
                    if (s.equals(entry.getValue())) {
                        builder.append(entry.getKey() + ",");
                        break;
                    }
                }
            }
            provisionalPlan.setProjectAttrName(builder.toString());
        } else {
            for (Map.Entry<String, String> entry : projectAttributes.entrySet()) {
                if (provisionalPlan.getProjectAttr() != null && provisionalPlan.getProjectAttr().equals(entry.getValue())) {
                    provisionalPlan.setProjectAttrName(entry.getKey());
                    break;
                }
            }
        }
        /*for (Map.Entry<String, String> entry : purchaseServices.entrySet()) {
            if (provisionalPlan.getPurchaseServices() != null && provisionalPlan.getPurchaseServices().equals(entry.getValue())) {
                provisionalPlan.setPurchaseServicesStr(entry.getKey());
                break;
            }
        }*/
        return provisionalPlan;
    }

    //字段赋值对应的名称
    public List<ProvisionalPlanResVo> changeTo(List<ProvisionalPlan> provisionalPlans) {
        //获取字典数据
        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> budgetAccountMap = planEnums.get("budgetAccount");
        //采购服务站
        HashMap<String, String> purchaseServicesMap = planEnums.get("purchaseServices");

        List<ProvisionalPlanResVo> list = new ArrayList<ProvisionalPlanResVo>();
        for (ProvisionalPlan provisionalPlan : provisionalPlans) {
            ProvisionalPlanResVo provisionalPlanResVo = new ProvisionalPlanResVo();
            if (provisionalPlan.getPurchaseDeptId() != null) {
                SysDeptResponseVo sysDeptResponseVo = (SysDeptResponseVo) deptService.selectDeptById(Long.valueOf(provisionalPlan.getPurchaseDeptId())).get("sysDept");
                provisionalPlan.setPurchaseDeptName(sysDeptResponseVo.getDeptName());
            }
            //预算科目
            for (Map.Entry<String, String> entry : budgetAccountMap.entrySet()) {
                if (!ObjectUtils.isEmpty(provisionalPlan.getBudgetAccount()) && provisionalPlan.getBudgetAccount().equals(entry.getValue())) {
                    provisionalPlan.setBudgetAccountStr(entry.getKey());
                    break;
                }
            }
            //采购服务站
            for (Map.Entry<String, String> entry : purchaseServicesMap.entrySet()) {
                if (!ObjectUtils.isEmpty(provisionalPlan.getPurchaseServices()) && provisionalPlan.getPurchaseServices().equals(entry.getValue())) {
                    provisionalPlan.setPurchaseServicesStr(entry.getKey());
                    break;
                }
            }
            //项目审核状态
            for (Map.Entry<String, String> entry : projectStatusMap.entrySet()) {
                if (!ObjectUtils.isEmpty(provisionalPlan.getProjectStatus()) && provisionalPlan.getProjectStatus().equals(entry.getValue())) {
                    provisionalPlan.setProjectStatusStr(entry.getKey());
                    break;
                }
            }
            //项目类型
            for (Map.Entry<String, String> entry : projectTypesMap.entrySet()) {
                if (provisionalPlan.getProjectType() != null && provisionalPlan.getProjectType().equals(entry.getValue())) {
                    provisionalPlan.setProjectTypeStr(entry.getKey());
                    break;
                }
            }
            //项目属性是拼接的
            if (provisionalPlan.getProjectAttr().length() > 1) {
                StringBuilder builder = new StringBuilder();
                String[] split = provisionalPlan.getProjectAttr().split(",");
                for (String s : split) {
                    for (Map.Entry<String, String> entry : projectAttributes.entrySet()) {
                        if (s.equals(entry.getValue())) {
                            if (!provisionalPlan.getProjectAttr().endsWith(s)) {
                                builder.append(entry.getKey() + ",");
                            } else {
                                builder.append(entry.getKey());
                            }
                            break;
                        }
                    }
                }
                provisionalPlan.setProjectAttrName(builder.toString());
            } else {
                for (Map.Entry<String, String> entry : projectAttributes.entrySet()) {
                    if (provisionalPlan.getProjectAttr() != null && provisionalPlan.getProjectAttr().equals(entry.getValue())) {
                        provisionalPlan.setProjectAttrName(entry.getKey());
                        break;
                    }
                }
            }
            //机关业务指导处(科)为id拼接
            String organDivision = provisionalPlan.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());
                            }
                        }
                    }
                    provisionalPlan.setOrganDivisionStr(builder.toString());
                } else if (length == 1) {
                    sysDept = deptService.selectById(Long.valueOf(organDivision));
                    if (!ObjectUtils.isEmpty(sysDept)) {
                        provisionalPlan.setOrganDivisionStr(sysDept.getDeptName());
                        break;
                    }
                }
            }

            BeanUtils.copyProperties(provisionalPlan, provisionalPlanResVo);
            provisionalPlanResVo.setSendLetterDo("false");
            //状态在采购需求对接和流废标退回之间的项目可以进行催告---已发函不可再次发函
            PmDemand demand = demandService.selectByPlanId(provisionalPlan.getPlanPracticalId());
            if (!ObjectUtils.isEmpty(demand)) {
                if (quarterService.sendLetterDo(demand.getProjectStatus()) && provisionalPlan.getSendLetter().equals("0")) {
                    provisionalPlanResVo.setSendLetterDo("true");
                }
            }
            list.add(provisionalPlanResVo);
        }
        return list;
    }


}
