package com.ozs.pm.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.enums.*;
import com.ozs.common.utils.DateUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.bean.BeanUtils;
import com.ozs.pm.doman.*;
import com.ozs.pm.doman.vo.requestVo.*;
import com.ozs.pm.doman.vo.responseVo.*;
import com.ozs.pm.mapper.PmDemandMapper;
import com.ozs.pm.service.*;
import com.ozs.system.domain.SysFileInfo;
import com.ozs.system.domain.SysFileRef;
import com.ozs.system.domain.vo.responseVo.SysDeptResponseVo;
import com.ozs.system.service.ISysDeptService;
import com.ozs.system.service.ISysDictDataService;
import com.ozs.system.service.SysFileRefService;
import com.ozs.system.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;


/**
 * 采购需求Service业务层处理
 *
 * @author ruoyi
 * @date 2023-01-16
 */
@Service
public class PmDemandServiceImpl extends ServiceImpl<PmDemandMapper, PmDemand> implements IPmDemandService
{
    @Autowired
    private PmDemandMapper pmDemandMapper;

    @Autowired
    private IPmDemandEquipService iPmDemandEquipService;
    @Autowired
    private IPmDemandMaterialsService iPmDemandMaterialsService;

    @Autowired
    private IPmDemandServeService iPmDemandServeService;
    @Autowired
    private IPmDemandEngineeringService iPmDemandEngineeringService;
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private SysFileService fileService;
    @Autowired
    private SysFileRefService sysFileRefService;
    @Autowired
    private IPmFlowChartService iPmFlowChartService;
    /**
     * 查询采购需求
     *
     * @param demandId 采购需求主键
     * @return 采购需求
     */
    @Override
    public PmDemandResVo selectPmDemandByDemandId(Long demandId,String detailType) {
        PmDemand pmDemand = pmDemandMapper.selectPmDemandByDemandId(demandId);
        if(pmDemand != null){
            PmDemandResVo vo = new PmDemandResVo();
            vo.setDemandId(demandId);
            if("1".equals(detailType)) { //项目计划

                BeanUtils.copyProperties(pmDemand, vo);

                SysDeptResponseVo sysDeptResponseVo = (SysDeptResponseVo) deptService.selectDeptById(vo.getPurchaseDeptId()).get("sysDept");
                if(sysDeptResponseVo != null){
                    vo.setPurchaseDeptName(sysDeptResponseVo.getDeptName());
                }

                String purchaseServicesName = dictDataService.selectDictLabel("purchase_services", vo.getPurchaseServices());
                if(StringUtils.isNotEmpty(purchaseServicesName)){
                    vo.setPurchaseServicesName(purchaseServicesName);
                }

                //采购需求附件
                HashMap<String, String> demandFileMap = getFileMap(vo.getDemandId(),SysFileRefEnum.PM_DEMAND.getType());
                if(demandFileMap != null){
                    vo.setDemandFileMap(demandFileMap);
                }

                //项目类型
                for (ProjectTypes value : ProjectTypes.values()) {
                    if (vo.getProjectType() != null && vo.getProjectType().equals(value.getCode())) {
                        vo.setProjectTypeName(value.getInfo());
                        break;
                    }
                }
                //是否为超限额计划
                for (IsExcess value : IsExcess.values()) {
                    if (vo.getIsExcess() != null && vo.getIsExcess().equals(value.getCode())) {
                        vo.setIsExcessName(value.getInfo());
                        break;
                    }
                }

                //采购方式
                for (PlanPurchaseMode value : PlanPurchaseMode.values()) {
                    if (vo.getPurchaseMode() != null && vo.getPurchaseMode().equals(value.getCode())) {
                        vo.setPurchaseModeName(value.getInfo());
                        break;
                    }
                }
                //项目属性
                for (ProjectAttribute value : ProjectAttribute.values()) {
                    if (vo.getProjectAttr() != null && vo.getProjectAttr().equals(value.getCode())) {
                        vo.setProjectAttrName(value.getInfo());
                        break;
                    }
                }
                //预警状态
                for (WarnStatus value : WarnStatus.values()) {
                    if (vo.getWarnStatus() != null && vo.getWarnStatus().equals(value.getCode())) {
                        vo.setWarnStatusName(value.getInfo());
                        break;
                    }
                }

                //项目状态
                for (PmProjectStatus value : PmProjectStatus.values()) {
                    if (vo.getProjectStatus() != null && vo.getProjectStatus().equals(value.getCode())) {
                        vo.setProjectStatusName(value.getInfo());
                        break;
                    }
                }

            } else if("2".equals(detailType)) { //需求建档

                //采购需求审核文件
                HashMap<String, String> auditFileMap = getFileMap(vo.getDemandId(),SysFileRefEnum.PM_DEMAND_EXAMINE.getType());
                if(auditFileMap != null){
                    vo.setAuditFileMap(auditFileMap);
                }

                if(ProjectTypes.EQUIPMENTTYPE.getCode().equals(pmDemand.getProjectType())){//装备类
                    PmDemandEquip obj = new PmDemandEquip();
                    obj.setDemandId(demandId);
                    List<PmDemandEquip> list = iPmDemandEquipService.selectPmDemandEquipList(obj);
                    if(list !=null && list.size() > 0){
                        PmDemandEquipResVo responseVo = new PmDemandEquipResVo();
                        BeanUtils.copyProperties(list.get(0),responseVo);
                        //采购方式建议
                        for (ProcurementMethodSuggest value : ProcurementMethodSuggest.values()) {
                            if (responseVo.getProcurementMethodSuggest() != null && responseVo.getProcurementMethodSuggest().equals(value.getCode())) {
                                responseVo.setProcurementMethodSuggestName(value.getInfo());
                                break;
                            }
                        }

                        HashMap<String, String> fileMap1 = getFileMap(demandId,SysFileRefEnum.PM_DEMAND_EQUIP.getType());
                        if(fileMap1 != null){
                            responseVo.setFileMap(fileMap1);
                        }

                        vo.setPmDemandEquipResVo(responseVo);
                    }
                } else if(ProjectTypes.MATERIALTYPE.getCode().equals(pmDemand.getProjectType())){ //物资类
                    PmDemandMaterials obj = new PmDemandMaterials();
                    obj.setDemandId(demandId);
                    List<PmDemandMaterials> list = iPmDemandMaterialsService.selectPmDemandMaterialsList(obj);
                    if(list !=null && list.size() > 0){
                        PmDemandMaterialsResVo responseVo = new PmDemandMaterialsResVo();
                        BeanUtils.copyProperties(list.get(0),responseVo);
                        //采购方式建议
                        for (ProcurementMethodSuggest value : ProcurementMethodSuggest.values()) {
                            if (responseVo.getProcurementMethodSuggest() != null && responseVo.getProcurementMethodSuggest().equals(value.getCode())) {
                                responseVo.setProcurementMethodSuggestName(value.getInfo());
                                break;
                            }
                        }
                        HashMap<String, String> fileMap2 = getFileMap(demandId,SysFileRefEnum.PM_DEMAND_MATERIALS.getType());
                        if(fileMap2 != null){
                            responseVo.setFileMap(fileMap2);
                        }
                        vo.setPmDemandMaterialsResVo(responseVo);
                    }
                } else if(ProjectTypes.SERVICESTYPE.getCode().equals(pmDemand.getProjectType())){//服务类
                    PmDemandServe obj = new PmDemandServe();
                    obj.setDemandId(demandId);
                    List<PmDemandServe> list = iPmDemandServeService.selectPmDemandServeList(obj);
                    if(list !=null && list.size() > 0){
                        PmDemandServeResVo responseVo = new PmDemandServeResVo();
                        BeanUtils.copyProperties(list.get(0),responseVo);
                        //采购方式建议
                        for (ProcurementMethodSuggest value : ProcurementMethodSuggest.values()) {
                            if (responseVo.getProcurementMethodSuggest() != null && responseVo.getProcurementMethodSuggest().equals(value.getCode())) {
                                responseVo.setProcurementMethodSuggestName(value.getInfo());
                                break;
                            }
                        }
                        HashMap<String, String> fileMap3 = getFileMap(demandId,SysFileRefEnum.PM_DEMAND_SERVE.getType());
                        if(fileMap3 != null){
                            responseVo.setFileMap(fileMap3);
                        }
                        vo.setPmDemandServeResVo(responseVo);
                    }
                } else if(ProjectTypes.PLANTOEXAMINETYPE.getCode().equals(pmDemand.getProjectType())){//工程类
                    PmDemandEngineering obj = new PmDemandEngineering();
                    obj.setDemandId(demandId);
                    List<PmDemandEngineering> list = iPmDemandEngineeringService.selectPmDemandEngineeringList(obj);
                    if(list !=null && list.size() > 0){
                        PmDemandEngineeringResVo responseVo = new PmDemandEngineeringResVo();
                        BeanUtils.copyProperties(list.get(0),responseVo);
                        //采购方式建议
                        for (ProcurementMethodSuggest value : ProcurementMethodSuggest.values()) {
                            if (responseVo.getProcurementMethodSuggest() != null && responseVo.getProcurementMethodSuggest().equals(value.getCode())) {
                                responseVo.setProcurementMethodSuggestName(value.getInfo());
                                break;
                            }
                        }
                        //项目类别
                        for (EngineeringProjectCategory value : EngineeringProjectCategory.values()) {
                            if (responseVo.getProjectCategory() != null && responseVo.getProjectCategory().equals(value.getCode())) {
                                responseVo.setProjectCategoryName(value.getInfo());
                                break;
                            }
                        }
                        //承包方式
                        for (EngineeringContractingMode value : EngineeringContractingMode.values()) {
                            if (responseVo.getContractingMode() != null && responseVo.getContractingMode().equals(value.getCode())) {
                                responseVo.setContractingModeName(value.getInfo());
                                break;
                            }
                        }
                        //施工图是否完成
                        for (ConstructionDrawing value : ConstructionDrawing.values()) {
                            if (responseVo.getConstructionDrawing() != null && responseVo.getConstructionDrawing().equals(value.getCode())) {
                                responseVo.setConstructionDrawingName(value.getInfo());
                                break;
                            }
                        }
                        HashMap<String, String> fileMap4 = getFileMap(demandId,SysFileRefEnum.PM_DEMAND_ENGINEERING.getType());
                        if(fileMap4 != null){
                            responseVo.setFileMap(fileMap4);
                        }
                        vo.setPmDemandEngineeringResVo(responseVo);
                    }
                }
            } else if("3".equals(detailType)) { //任务下达
                //任务下达文件
                HashMap<String, String> taskReleaseFileMap = getFileMap(vo.getDemandId(),SysFileRefEnum.PM_TAST_RELEASE.getType());
                if(taskReleaseFileMap != null){
                    vo.setTaskReleaseFileMap(taskReleaseFileMap);
                }
            } else if("4".equals(detailType)) { //中标信息

            } else if("5".equals(detailType)) { //合同信息

            } else if("6".equals(detailType)) { //建设情况

            }

            return vo;
        } else {
            return null;
        }
    }

    /**
     * 查询采购需求列表
     *
     * @param pmDemandReqVo
     * @return 采购需求
     */
    @Override
    public IPage<PmDemandResVo> selectPmDemandList(PmDemandReqVo pmDemandReqVo, int reqType) {

        LambdaQueryWrapper<PmDemand> lw = new LambdaQueryWrapper<>();
        if (!StringUtils.isBlank(pmDemandReqVo.getProjectName())) {
            lw.like(PmDemand::getProjectName, "%" + pmDemandReqVo.getProjectName() + "%");
        }
        if (!StringUtils.isBlank(pmDemandReqVo.getPurchaseServices())) {
            lw.eq(PmDemand::getPurchaseServices, pmDemandReqVo.getPurchaseServices());
        }
        if (pmDemandReqVo.getProjectStatus() != null) {
            lw.eq(PmDemand::getProjectStatus, pmDemandReqVo.getProjectStatus());
        }
        if (pmDemandReqVo.getIsExcess() != null) {
            lw.eq(PmDemand::getIsExcess, pmDemandReqVo.getIsExcess());
        }
        if (!StringUtils.isBlank(pmDemandReqVo.getBeginDate())) {
            lw.apply("(plan_demand_sub_time >= '" + pmDemandReqVo.getBeginDate() +"' or plan_purchase_finish_time >= '" + pmDemandReqVo.getBeginDate() + "' or plan_deliver_time >=  '" + pmDemandReqVo.getBeginDate() +"' )");
        }
        if (!StringUtils.isBlank(pmDemandReqVo.getEndDate())) {
            lw.apply("(plan_demand_sub_time <= '" + pmDemandReqVo.getEndDate() +"' or plan_purchase_finish_time <= '" + pmDemandReqVo.getEndDate() + "' or plan_deliver_time <=  '" + pmDemandReqVo.getEndDate() +"' )");
        }

        if(reqType== 1) { //需求审核单位列表
            lw.eq(PmDemand::getProjectStatus, PmProjectStatus.DEMAND_WAIT_AUDIT.getCode());
        } 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 )");
        } else  if(reqType== 4) { //合同信息列表
            lw.apply("(project_status = 10 or project_status = 11 )");
        }  else  if(reqType== 5) { //项目建设列表
            lw.apply("(project_status = 11 or project_status = 12 )");
        }

        IPage<PmDemand> pageRes = this.page(new Page<>(pmDemandReqVo.getPageNum(), pmDemandReqVo.getPageSize()), lw);
        IPage<PmDemandResVo> results = new Page<>(pageRes.getCurrent(), pageRes.getSize(), pageRes.getTotal());
        if(pageRes.getRecords() != null && pageRes.getRecords().size() > 0){
            List<PmDemandResVo> pmDemandResponseVoList = new ArrayList<>();
            for(PmDemand pmDemand1 : pageRes.getRecords()){
                PmDemandResVo vo = new PmDemandResVo();
                BeanUtils.copyProperties(pmDemand1,vo);
                if(vo.getPurchaseDeptId() != null){
                    Map<String, Object> deptMap =  deptService.selectDeptById(vo.getPurchaseDeptId());
                    if(deptMap!= null){
                        SysDeptResponseVo sysDeptResponseVo = (SysDeptResponseVo)deptMap.get("sysDept");
                        if(sysDeptResponseVo != null){
                            vo.setPurchaseDeptName(sysDeptResponseVo.getDeptName());
                        }
                    }
                }

                String purchaseServicesName = dictDataService.selectDictLabel("purchase_services",vo.getPurchaseServices());
                if(StringUtils.isNotEmpty(purchaseServicesName)){
                    vo.setPurchaseServicesName(purchaseServicesName);
                }

                //项目类型
                for (ProjectTypes value : ProjectTypes.values()) {
                    if (vo.getProjectType() != null && vo.getProjectType().equals(value.getCode())) {
                        vo.setProjectTypeName(value.getInfo());
                        break;
                    }
                }
                //是否为超限额计划
                for (IsExcess value : IsExcess.values()) {
                    if (vo.getIsExcess() != null && vo.getIsExcess().equals(value.getCode())) {
                        vo.setIsExcessName(value.getInfo());
                        break;
                    }
                }

                //采购方式
                for (PlanPurchaseMode value : PlanPurchaseMode.values()) {
                    if (vo.getPurchaseMode() != null && vo.getPurchaseMode().equals(value.getCode())) {
                        vo.setPurchaseModeName(value.getInfo());
                        break;
                    }
                }
                //项目属性
                for (ProjectAttribute value : ProjectAttribute.values()) {
                    if (vo.getProjectAttr() != null && vo.getProjectAttr().equals(value.getCode())) {
                        vo.setProjectAttrName(value.getInfo());
                        break;
                    }
                }
                //预警状态
                for (WarnStatus value : WarnStatus.values()) {
                    if (vo.getWarnStatus() != null && vo.getWarnStatus().equals(value.getCode())) {
                        vo.setWarnStatusName(value.getInfo());
                        break;
                    }
                }

                //项目状态
                for (PmProjectStatus value : PmProjectStatus.values()) {
                    if (vo.getProjectStatus() != null && vo.getProjectStatus().equals(value.getCode())) {
                        vo.setProjectStatusName(value.getInfo());
                        break;
                    }
                }
                pmDemandResponseVoList.add(vo);
            }
            results.setRecords(pmDemandResponseVoList);
        }

        return results;
    }


    /**
     * 新增采购需求
     *
     * @param pmDemand 采购需求
     * @return 结果
     */
    @Override
    public int insertPmDemand(PmDemand pmDemand) {
        pmDemand.setCreateTime(DateUtils.getNowDate());
        return pmDemandMapper.insertPmDemand(pmDemand);
    }

    /**
     * 修改采购需求
     *
     * @param pmDemand 采购需求
     * @return 结果
     */
    @Override
    public int updatePmDemand(PmDemand pmDemand) {
        pmDemand.setUpdateTime(DateUtils.getNowDate());
        return pmDemandMapper.updatePmDemand(pmDemand);
    }

    /**
     * 需求建档
     *
     * @param vo 采购需求
     * @return 结果
     */
    @Override
    public int bookBuilding(PmBookBuildingReqVo vo) {
        PmDemand pmDemand = pmDemandMapper.selectPmDemandByDemandId(vo.getDemandId());
        String projectType = pmDemand.getProjectType();
        if(ProjectTypes.EQUIPMENTTYPE.getCode().equals(projectType)){ //装备类
            PmDemandEquipReqVo pmDemandEquipReqVo =  vo.getPmDemandEquipReqVo();
            PmDemandEquip pmDemandEquipReq = new PmDemandEquip();
            pmDemandEquipReq.setDemandId(vo.getDemandId());
            PmDemandEquip pmDemandEquip = null;
            List<PmDemandEquip> pmDemandEquipList = iPmDemandEquipService.selectPmDemandEquipList(pmDemandEquipReq);
            if(pmDemandEquipList != null && pmDemandEquipList.size() > 0){
                pmDemandEquip = pmDemandEquipList.get(0);
                pmDemandEquipReqVo.setDemandEquipId(pmDemandEquip.getDemandEquipId());
                BeanUtils.copyProperties(pmDemandEquipReqVo,pmDemandEquip);
                pmDemandEquip.setUpdateBy(vo.getUpdateBy());
                pmDemandEquip.setUpdateTime(new Date());
                iPmDemandEquipService.updatePmDemandEquip(pmDemandEquip);
            } else {
                pmDemandEquip = new PmDemandEquip();
                BeanUtils.copyProperties(pmDemandEquipReqVo,pmDemandEquip);
                pmDemandEquip.setCreateBy(vo.getUpdateBy());
                pmDemandEquip.setCreateTime(new Date());
                pmDemandEquip.setUpdateBy(vo.getUpdateBy());
                pmDemandEquip.setUpdateTime(new Date());
                iPmDemandEquipService.insertPmDemandEquip(pmDemandEquip);
            }

            List<SysFileRef> sysFileRefs = pmDemandEquipReqVo.getSysFileRefs();
            if (!ObjectUtils.isEmpty(sysFileRefs)) {
                for (SysFileRef ref : sysFileRefs) {
                    if(ref.getFileId() == null){
                        continue;
                    }
                    QueryWrapper<SysFileRef> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(SysFileRef::getFileId,ref.getFileId())
                            .eq(SysFileRef::getRedId,pmDemandEquip.getDemandEquipId())
                            .eq(SysFileRef::getType,SysFileRefEnum.PM_DEMAND_EQUIP.getType());
                    List<SysFileRef> sysFileRefList = sysFileRefService.list(queryWrapper);
                    if(!CollectionUtils.isEmpty(sysFileRefList)){
                        sysFileRefService.remove(queryWrapper);
                    }
                    ref.setRedId(pmDemandEquip.getDemandEquipId());
                    ref.setType(SysFileRefEnum.PM_DEMAND_EQUIP.getType());
                    ref.setCreated(vo.getUpdateBy());
                    ref.setCreateTime(new Date());
                    ref.setUpdated(vo.getUpdateBy());
                    ref.setUpdateTime(new Date());
                    sysFileRefService.save(ref);
                }
            }
        } else if(ProjectTypes.MATERIALTYPE.getCode().equals(projectType)) { //物资类
            PmDemandMaterialsReqVo pmDemandMaterialsReqVo =  vo.getPmDemandMaterialsReqVo();
            PmDemandMaterials pmDemandMaterialsReq = new PmDemandMaterials();
            pmDemandMaterialsReq.setDemandId(vo.getDemandId());
            PmDemandMaterials pmDemandMaterials = null;
            List<PmDemandMaterials> pmDemandMaterialsList = iPmDemandMaterialsService.selectPmDemandMaterialsList(pmDemandMaterialsReq);
            if(pmDemandMaterialsList != null && pmDemandMaterialsList.size() > 0){
                pmDemandMaterials = pmDemandMaterialsList.get(0);
                pmDemandMaterialsReqVo.setDemandMaterialsId(pmDemandMaterials.getDemandMaterialsId());
                BeanUtils.copyProperties(pmDemandMaterialsReqVo,pmDemandMaterials);
                pmDemandMaterials.setUpdateBy(vo.getUpdateBy());
                pmDemandMaterials.setUpdateTime(new Date());
                iPmDemandMaterialsService.updatePmDemandMaterials(pmDemandMaterials);
            } else {
                pmDemandMaterials = new PmDemandMaterials();
                BeanUtils.copyProperties(pmDemandMaterialsReqVo,pmDemandMaterials);
                pmDemandMaterials.setCreateBy(vo.getUpdateBy());
                pmDemandMaterials.setCreateTime(new Date());
                pmDemandMaterials.setUpdateBy(vo.getUpdateBy());
                pmDemandMaterials.setUpdateTime(new Date());
                iPmDemandMaterialsService.insertPmDemandMaterials(pmDemandMaterials);
            }

            List<SysFileRef> sysFileRefs = pmDemandMaterialsReqVo.getSysFileRefs();
            if (!ObjectUtils.isEmpty(sysFileRefs)) {
                for (SysFileRef ref : sysFileRefs) {
                    if(ref.getFileId() == null){
                        continue;
                    }
                    QueryWrapper<SysFileRef> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(SysFileRef::getFileId,ref.getFileId())
                            .eq(SysFileRef::getRedId,pmDemandMaterials.getDemandMaterialsId())
                            .eq(SysFileRef::getType,SysFileRefEnum.PM_DEMAND_MATERIALS.getType());
                    List<SysFileRef> sysFileRefList = sysFileRefService.list(queryWrapper);
                    if(!CollectionUtils.isEmpty(sysFileRefList)){
                        sysFileRefService.remove(queryWrapper);
                    }
                    ref.setRedId(pmDemandMaterials.getDemandMaterialsId());
                    ref.setType(SysFileRefEnum.PM_DEMAND_MATERIALS.getType());
                    ref.setCreated(vo.getUpdateBy());
                    ref.setCreateTime(new Date());
                    ref.setUpdated(vo.getUpdateBy());
                    ref.setUpdateTime(new Date());
                    sysFileRefService.save(ref);
                }
            }
        } else if(ProjectTypes.SERVICESTYPE.getCode().equals(projectType)) { //服务类
            PmDemandServeReqVo pmDemandServeReqVo =  vo.getPmDemandServeReqVo();
            PmDemandServe pmDemandServeReq = new PmDemandServe();
            pmDemandServeReq.setDemandId(vo.getDemandId());
            PmDemandServe pmDemandServe = null;
            List<PmDemandServe> pmDemandServeList = iPmDemandServeService.selectPmDemandServeList(pmDemandServeReq);
            if(pmDemandServeList != null && pmDemandServeList.size() > 0){
                pmDemandServe = pmDemandServeList.get(0);
                pmDemandServeReqVo.setDemandServeId(pmDemandServe.getDemandServeId());
                BeanUtils.copyProperties(pmDemandServeReqVo,pmDemandServe);
                pmDemandServe.setUpdateBy(vo.getUpdateBy());
                pmDemandServe.setUpdateTime(new Date());
                iPmDemandServeService.updatePmDemandServe(pmDemandServe);
            } else {
                pmDemandServe = new PmDemandServe();
                BeanUtils.copyProperties(pmDemandServeReqVo,pmDemandServe);
                pmDemandServe.setCreateBy(vo.getUpdateBy());
                pmDemandServe.setCreateTime(new Date());
                pmDemandServe.setUpdateBy(vo.getUpdateBy());
                pmDemandServe.setUpdateTime(new Date());
                iPmDemandServeService.insertPmDemandServe(pmDemandServe);
            }
            List<SysFileRef> sysFileRefs = pmDemandServeReqVo.getSysFileRefs();
            if (!ObjectUtils.isEmpty(sysFileRefs)) {
                for (SysFileRef ref : sysFileRefs) {
                    if(ref.getFileId() == null){
                        continue;
                    }
                    QueryWrapper<SysFileRef> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(SysFileRef::getFileId,ref.getFileId())
                            .eq(SysFileRef::getRedId,pmDemandServe.getDemandServeId())
                            .eq(SysFileRef::getType,SysFileRefEnum.PM_DEMAND_SERVE.getType());
                    List<SysFileRef> sysFileRefList = sysFileRefService.list(queryWrapper);
                    if(!CollectionUtils.isEmpty(sysFileRefList)){
                        sysFileRefService.remove(queryWrapper);
                    }
                    ref.setRedId(pmDemandServe.getDemandServeId());
                    ref.setType(SysFileRefEnum.PM_DEMAND_SERVE.getType());
                    ref.setCreated(vo.getUpdateBy());
                    ref.setCreateTime(new Date());
                    ref.setUpdated(vo.getUpdateBy());
                    ref.setUpdateTime(new Date());
                    sysFileRefService.save(ref);
                }
            }
        } else if(ProjectTypes.PLANTOEXAMINETYPE.getCode().equals(projectType)) { //工程类
            PmDemandEngineeringReqVo pmDemandEngineeringReqVo =  vo.getPmDemandEngineeringReqVo();
            PmDemandEngineering pmDemandEngineeringReq = new PmDemandEngineering();
            pmDemandEngineeringReq.setDemandId(vo.getDemandId());
            PmDemandEngineering pmDemandEngineering = null;
            List<PmDemandEngineering> pmDemandEngineeringList = iPmDemandEngineeringService.selectPmDemandEngineeringList(pmDemandEngineeringReq);
            if(pmDemandEngineeringList != null && pmDemandEngineeringList.size() > 0){
                pmDemandEngineering = pmDemandEngineeringList.get(0);
                pmDemandEngineeringReqVo.setDemandEngineeringId(pmDemandEngineering.getDemandEngineeringId());
                BeanUtils.copyProperties(pmDemandEngineeringReqVo,pmDemandEngineering);
                pmDemandEngineering.setUpdateBy(vo.getUpdateBy());
                pmDemandEngineering.setUpdateTime(new Date());
                iPmDemandEngineeringService.updatePmDemandEngineering(pmDemandEngineering);
            } else {
                pmDemandEngineering = new PmDemandEngineering();
                BeanUtils.copyProperties(pmDemandEngineeringReqVo,pmDemandEngineering);
                pmDemandEngineering.setCreateBy(vo.getUpdateBy());
                pmDemandEngineering.setCreateTime(new Date());
                pmDemandEngineering.setUpdateBy(vo.getUpdateBy());
                pmDemandEngineering.setUpdateTime(new Date());
                iPmDemandEngineeringService.insertPmDemandEngineering(pmDemandEngineering);
            }
            List<SysFileRef> sysFileRefs = pmDemandEngineeringReqVo.getSysFileRefs();
            if (!ObjectUtils.isEmpty(sysFileRefs)) {
                for (SysFileRef ref : sysFileRefs) {
                    if(ref.getFileId() == null){
                        continue;
                    }
                    QueryWrapper<SysFileRef> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(SysFileRef::getFileId,ref.getFileId())
                            .eq(SysFileRef::getRedId,pmDemandEngineering.getDemandEngineeringId())
                            .eq(SysFileRef::getType,SysFileRefEnum.PM_DEMAND_ENGINEERING.getType());
                    List<SysFileRef> sysFileRefList = sysFileRefService.list(queryWrapper);
                    if(!CollectionUtils.isEmpty(sysFileRefList)){
                        sysFileRefService.remove(queryWrapper);
                    }
                    ref.setRedId(pmDemandEngineering.getDemandEngineeringId());
                    ref.setType(SysFileRefEnum.PM_DEMAND_ENGINEERING.getType());
                    ref.setCreated(vo.getUpdateBy());
                    ref.setCreateTime(new Date());
                    ref.setUpdated(vo.getUpdateBy());
                    ref.setUpdateTime(new Date());
                    sysFileRefService.save(ref);
                }
            }
        }

        pmDemand.setUpdateBy(vo.getUpdateBy());
        pmDemand.setUpdateTime(DateUtils.getNowDate());
        return pmDemandMapper.updatePmDemand(pmDemand);
    }

    private HashMap<String, String> getFileMap(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)) {
            HashMap<String, String> fileMap = new HashMap<>();
            for (SysFileRef ref : fileRefs) {
                SysFileInfo fileInfo = fileService.getById(ref.getFileId());
                fileMap.put(fileInfo.getFileUrl(), fileInfo.getFileName());
            }
            return fileMap;
        } else {
            return null;
        }

    }


    /**
     * 查看流程图
     *
     * @param demandId 采购需求主键
     * @return 采购需求
     */
    @Override
    public Object viewFlowChart(Long demandId) {
        PmDemand pmDemand = pmDemandMapper.selectPmDemandByDemandId(demandId);
        String projectStatus = String.valueOf(pmDemand.getProjectStatus());
        String moduleName = null;
        if (PmProjectStatus.DEMAND_WAIT_FILL.getCode().equals(projectStatus) || PmProjectStatus.DEMAND_AUDIT_RETURN.getCode().equals(projectStatus)) {
            moduleName = "需求填制";
        } else if(PmProjectStatus.DEMAND_WAIT_COMMIT.getCode().equals(projectStatus)) {
            moduleName = "需求提交";
        } else if(PmProjectStatus.DEMAND_WAIT_AUDIT.getCode().equals(projectStatus)) {
            moduleName = "需求审核";
        } else if(PmProjectStatus.TASK_WAIT_RELEASE.getCode().equals(projectStatus)) {
            moduleName = "任务下达";
        } else if(PmProjectStatus.WAIT_SELECT_AGENT.getCode().equals(projectStatus)) {
            moduleName = "选取代理";
        } else if(PmProjectStatus.WAIT_UPLOAD_BID_FILE.getCode().equals(projectStatus)) {
            moduleName = "上传招标文件";
        } else if(PmProjectStatus.WAIT_ANNOUNCEMENT.getCode().equals(projectStatus)) {
            moduleName = "发布公告";
        } else if(PmProjectStatus.WAIT_OPEN_BID.getCode().equals(projectStatus)) {
            moduleName = "填写专家信息,填写开标信息";
        } else if(PmProjectStatus.WAIT_BID_ANNOUNCEMENT.getCode().equals(projectStatus)) {
            moduleName = "填写中标信息";
        } else if(PmProjectStatus.BIDDING_PUBLICITY.getCode().equals(projectStatus)) {
            moduleName = "质疑处理,上传中标通知书";
        } else if(PmProjectStatus.CONTRACT_WAIT_FILL.getCode().equals(projectStatus)) {
            moduleName = "合同填制";
        } else if(PmProjectStatus.UNDER_CONSTRUCTION.getCode().equals(projectStatus)) {
            moduleName = "建设文档填制";
        } else if(PmProjectStatus.COMPLETION_CONSTRUCTION.getCode().equals(projectStatus)) {
            moduleName = "项目归档";
        }
        return moduleName;
    }

    public PmFlowChartResVo getModuleInfo(Long demandId,String moduleName){
        PmDemand pmDemand = pmDemandMapper.selectPmDemandByDemandId(demandId);
        String projectType = pmDemand.getProjectType();

        PmFlowChart pmFlowChartReq = new PmFlowChart();
        pmFlowChartReq.setModuleName(moduleName);
        List<PmFlowChart> pmFlowChartList = iPmFlowChartService.selectPmFlowChartList(pmFlowChartReq);
        if(pmFlowChartList == null || pmFlowChartList.size() ==0){
            return null;
        }
        PmFlowChartResVo vo = new PmFlowChartResVo();
        BeanUtils.copyProperties(pmFlowChartList.get(0), vo);

        if("需求填制".equals(moduleName)) {
            HashMap<String, String> fileMap = getFileMap(demandId,SysFileRefEnum.PM_DEMAND.getType());
            if(fileMap != null){
                vo.setFileMap(fileMap);
            }
        } else if("需求提交".equals(moduleName)) {
            if(ProjectTypes.EQUIPMENTTYPE.getCode().equals(projectType)){ //装备类
                PmDemandEquip pmDemandEquipReq = new PmDemandEquip();
                pmDemandEquipReq.setDemandId(demandId);
                List<PmDemandEquip> pmDemandEquipList = iPmDemandEquipService.selectPmDemandEquipList(pmDemandEquipReq);
                if(pmDemandEquipList != null && pmDemandEquipList.size() > 0){
                    HashMap<String, String> fileMap = getFileMap(pmDemandEquipList.get(0).getDemandEquipId(),SysFileRefEnum.PM_DEMAND_EQUIP.getType());
                    if(fileMap != null){
                        vo.setFileMap(fileMap);
                    }
                }
            } else if(ProjectTypes.MATERIALTYPE.getCode().equals(projectType)) { //物资类
                PmDemandMaterials pmDemandMaterialsReq = new PmDemandMaterials();
                pmDemandMaterialsReq.setDemandId(demandId);
                List<PmDemandMaterials> pmDemandMaterialsList = iPmDemandMaterialsService.selectPmDemandMaterialsList(pmDemandMaterialsReq);
                if(pmDemandMaterialsList != null && pmDemandMaterialsList.size() > 0){
                    HashMap<String, String> fileMap = getFileMap(pmDemandMaterialsList.get(0).getDemandMaterialsId(),SysFileRefEnum.PM_DEMAND_MATERIALS.getType());
                    if(fileMap != null){
                        vo.setFileMap(fileMap);
                    }
                }
            } else if(ProjectTypes.SERVICESTYPE.getCode().equals(projectType)) { //服务类
                PmDemandServe pmDemandServeReq = new PmDemandServe();
                pmDemandServeReq.setDemandId(demandId);
                List<PmDemandServe> pmDemandServeList = iPmDemandServeService.selectPmDemandServeList(pmDemandServeReq);
                if(pmDemandServeList != null && pmDemandServeList.size() > 0){
                    HashMap<String, String> fileMap = getFileMap(pmDemandServeList.get(0).getDemandServeId(),SysFileRefEnum.PM_DEMAND_SERVE.getType());
                    if(fileMap != null){
                        vo.setFileMap(fileMap);
                    }
                }
            } else if(ProjectTypes.PLANTOEXAMINETYPE.getCode().equals(projectType)) { //工程类
                PmDemandEngineering pmDemandEngineeringReq = new PmDemandEngineering();
                pmDemandEngineeringReq.setDemandId(demandId);
                List<PmDemandEngineering> pmDemandEngineeringList = iPmDemandEngineeringService.selectPmDemandEngineeringList(pmDemandEngineeringReq);
                if(pmDemandEngineeringList != null && pmDemandEngineeringList.size() > 0){
                    HashMap<String, String> fileMap = getFileMap(pmDemandEngineeringList.get(0).getDemandEngineeringId(),SysFileRefEnum.PM_DEMAND_ENGINEERING.getType());
                    if(fileMap != null){
                        vo.setFileMap(fileMap);
                    }
                }
            }

        } else if("需求审核".equals(moduleName)) {
            HashMap<String, String> fileMap = getFileMap(demandId,SysFileRefEnum.PM_DEMAND_EXAMINE.getType());
            if(fileMap != null){
                vo.setFileMap(fileMap);
            }
        } else if("任务下达".equals(moduleName)) {
            //todo
        }

         return vo;
    }

    /**
     * 提交采购需求
     *
     * @param pmDemandReqVo
     * @return 结果
     */
    @Override
    public int commit(PmDemandReqVo pmDemandReqVo) {
        PmDemand pmDemand = new PmDemand();
        pmDemand.setDemandId(pmDemandReqVo.getDemandId());
        pmDemand.setProjectStatus(Long.parseLong(PmProjectStatus.DEMAND_WAIT_AUDIT.getCode()));
        pmDemand.setUpdateBy(pmDemandReqVo.getUpdateBy());
        pmDemand.setUpdateTime(DateUtils.getNowDate());
        return pmDemandMapper.updatePmDemand(pmDemand);
    }

    /**
     * 审核采购需求通过
     *
     * @param pmDemandReqVo
     * @return 结果
     */
    @Override
    public int reviewTo(PmDemandReqVo pmDemandReqVo) {
        PmDemand pmDemand = new PmDemand();
        pmDemand.setDemandId(pmDemandReqVo.getDemandId());
        pmDemand.setProjectStatus(Long.parseLong(PmProjectStatus.TASK_WAIT_RELEASE.getCode()));
        List<SysFileRef> sysFileRefs = pmDemandReqVo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefs)) {
            for (SysFileRef ref : sysFileRefs) {
                if(ref.getFileId() == null){
                    continue;
                }
                QueryWrapper<SysFileRef> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(SysFileRef::getFileId,ref.getFileId())
                        .eq(SysFileRef::getRedId,pmDemandReqVo.getDemandId())
                        .eq(SysFileRef::getType,SysFileRefEnum.PM_DEMAND_EXAMINE.getType());
                List<SysFileRef> sysFileRefList = sysFileRefService.list(queryWrapper);
                if(!CollectionUtils.isEmpty(sysFileRefList)){
                    sysFileRefService.remove(queryWrapper);
                }
                ref.setRedId(pmDemandReqVo.getDemandId());
                ref.setType(SysFileRefEnum.PM_DEMAND_EXAMINE.getType());
                ref.setCreated(pmDemandReqVo.getUpdateBy());
                ref.setCreateTime(new Date());
                ref.setUpdated(pmDemandReqVo.getUpdateBy());
                ref.setUpdateTime(new Date());
                sysFileRefService.save(ref);
            }
        }
        pmDemand.setUpdateBy(pmDemandReqVo.getUpdateBy());
        pmDemand.setUpdateTime(DateUtils.getNowDate());
        pmDemand.setAuditTime(DateUtils.getNowDate());
        return pmDemandMapper.updatePmDemand(pmDemand);
    }

    /**
     * 审核采购需求退回
     *
     * @param pmDemandReqVo
     * @return 结果
     */
    @Override
    public int reviewReturn(PmDemandReqVo pmDemandReqVo) {
        PmDemand pmDemand = new PmDemand();
        pmDemand.setDemandId(pmDemandReqVo.getDemandId());
        pmDemand.setProjectStatus(Long.parseLong(PmProjectStatus.DEMAND_WAIT_COMMIT.getCode()));
        pmDemand.setAdjustReason(pmDemandReqVo.getRefuseReason());
        pmDemand.setUpdateBy(pmDemandReqVo.getUpdateBy());
        pmDemand.setUpdateTime(DateUtils.getNowDate());
        pmDemand.setAuditTime(DateUtils.getNowDate());
        return pmDemandMapper.updatePmDemand(pmDemand);
    }

    /**
     * 下达任务
     *
     * @param pmDemandReqVo
     * @return 结果
     */
    @Override
    public int releaseTask(PmDemandReqVo pmDemandReqVo) {
        PmDemand pmDemand = new PmDemand();
        pmDemand.setDemandId(pmDemandReqVo.getDemandId());
        pmDemand.setProjectStatus(Long.parseLong(PmProjectStatus.WAIT_SELECT_AGENT.getCode()));
        List<SysFileRef> sysFileRefs = pmDemandReqVo.getSysFileRefs();
        if (!ObjectUtils.isEmpty(sysFileRefs)) {
            for (SysFileRef ref : sysFileRefs) {
                if(ref.getFileId() == null){
                    continue;
                }
                QueryWrapper<SysFileRef> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(SysFileRef::getFileId,ref.getFileId())
                        .eq(SysFileRef::getRedId,pmDemandReqVo.getDemandId())
                        .eq(SysFileRef::getType,SysFileRefEnum.PM_TAST_RELEASE.getType());
                List<SysFileRef> sysFileRefList = sysFileRefService.list(queryWrapper);
                if(!CollectionUtils.isEmpty(sysFileRefList)){
                    sysFileRefService.remove(queryWrapper);
                }
                ref.setRedId(pmDemandReqVo.getDemandId());
                ref.setType(SysFileRefEnum.PM_TAST_RELEASE.getType());
                ref.setCreated(pmDemandReqVo.getUpdateBy());
                ref.setCreateTime(new Date());
                ref.setUpdated(pmDemandReqVo.getUpdateBy());
                ref.setUpdateTime(new Date());
                sysFileRefService.save(ref);
            }
        }
        pmDemand.setUpdateBy(pmDemandReqVo.getUpdateBy());
        pmDemand.setUpdateTime(DateUtils.getNowDate());
        pmDemand.setAuditTime(DateUtils.getNowDate());
        return pmDemandMapper.updatePmDemand(pmDemand);
    }

}
