package com.jeeplus.modules.sg.managementcenter.reserveManagement.service;

import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.PropertiesLoader;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.filing.approvalStage.entity.EarlyStage;
import com.jeeplus.modules.filing.basicInformation.entity.BasicInformationChild;
import com.jeeplus.modules.filing.filingImages.entity.FilingImages;
import com.jeeplus.modules.filing.filingImages.utils.ZipCompressUtil;
import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyActiviUtils;
import com.jeeplus.modules.sg.managementcenter.materialinfo.entity.MaterialInfo;
import com.jeeplus.modules.sg.managementcenter.materialinfo.mapper.MaterialInfoMapper;
import com.jeeplus.modules.sg.managementcenter.materialinfo.util.MaterialInfoUtil;
import com.jeeplus.modules.sg.managementcenter.materialproject.entity.MaterialProject;
import com.jeeplus.modules.sg.managementcenter.materialproject.mapper.MaterialProjectMapper;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.entity.*;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.entity.ReserveProcess;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.mapper.*;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.mapper.ReserveProcessMapper;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.activiti.engine.TaskService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jeeplus.common.config.Global.SYS_TYPE;

/**
 * 人员流转 Service
 */
@Service
@Transactional(readOnly = true)
public class ReserveProcessService extends CrudService<ReserveProcessMapper, ReserveProcess> {

    @Autowired
    private TaskService taskService;

    @Autowired
    private PersonnelTurnoverService personnelTurnoverService;

    @Autowired
    private ProgressScheduleMapper scheduleMapper;

    @Autowired
    private StandardMapper standardMapper;

    @Autowired
    private ReserveManagementMapper reserveManagementMapper;

    @Autowired
    private ScaleDetailsMapper detailsMapper;

    @Autowired
    private PersonnelTurnoverMapper personnelTurnoverMapper;

    @Autowired
    private MaterialInfoMapper materialInfoMapper;

    @Autowired
    private MaterialProjectMapper projectMapper;

    /**
     * 属性文件加载对象
     */
    private static PropertiesLoader loader = new PropertiesLoader("/properties/jeeplus.properties");

    @Override
    public ReserveProcess get(ReserveProcess entity) {
        String projectId = mapper.findProjectId(entity);
        ReserveProcess reserveProcess = mapper.get(projectId);
        return reserveProcess;
    }

    @Override
    public ReserveProcess get(String id) {
        ReserveProcess entity = new ReserveProcess();
        entity.setId(id);
        String projectId = mapper.findProjectId(entity);
        ReserveProcess reserveProcess = mapper.get(projectId);
        return reserveProcess;
    }

    @Override
    public List<ReserveProcess> findList(ReserveProcess entity) {
        return super.findList(entity);
    }

    @Override
    public Page<ReserveProcess> findPage(Page<ReserveProcess> page, ReserveProcess entity) {
        return super.findPage(page, entity);
    }

    public Page<MaterialInfo> findMaterialPage(Page<MaterialInfo> page, MaterialInfo entity) {
        dataRuleFilter(entity);
        entity.setPage(page);
        page.setList(mapper.findMaterialList(entity));
        return page;
    }

    public Page<ReserveProcess> findUploadPage(Page<ReserveProcess> page, ReserveProcess entity) {
        dataRuleFilter(entity);
        entity.setPage(page);
        page.setList(mapper.findUploadList(entity));
        return page;
    }

    public Page<ReserveProcess> findAllUploadPage(Page<ReserveProcess> page, ReserveProcess entity) {
        dataRuleFilter(entity);
        entity.setPage(page);
        page.setList(mapper.findAllUpload(entity));
        return page;
    }


    @Override
    @Transactional(readOnly = false)
    public void save(ReserveProcess entity) {
        if (entity.getIsNewRecord()) {
            entity.preInsert();
            mapper.insert(entity);
        } else {
            entity.preUpdate();
            mapper.update(entity);
        }
    }

    @Transactional(readOnly = false)
    public void insert(ReserveProcess entity) {
        mapper.insert(entity);
    }

    @Transactional(readOnly = false)
    public void update(ReserveProcess entity) {
        mapper.update(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void deleteAll(Collection<ReserveProcess> entitys) {
        super.deleteAll(entitys);
    }

    /**
     * 通过项目名称导出符合条件的数据
     */
    public List<MaterialInfo> findMaterialExport(List<String> projectName) {
        return mapper.findMaterialExport(projectName);
    }

    /**
     * 通过项目名称导出符合条件的数据
     */
    public List<MaterialInfo> findMaterialActiviti(String projectName) {
        return mapper.findMaterialActiviti(projectName);
    }

    /**
     * 通过流程定义号修改项目的金额数据
     */
    @Transactional(readOnly = false)
    public void updateAmount(ReserveProcess reserveProcess) {
        mapper.updateAmount(reserveProcess);
    }

    /**
    * 通过id查询符合条件的项目名称
    * */
    public List<String> findByIds(String[] ids){
        return mapper.findByIds(ids);
    }

    /**
     * 查询出所有的项目名称
     */
    public List<String> findAllName() {
        return mapper.findAllName();
    }

    /**
     * 修改项目设计单位信息
     */
    @Transactional(readOnly = false)
    public void updateDesign(ReserveProcess reserveProcess) {
        mapper.updateDesign(reserveProcess);
    }


    /**
     * 通过储备项目编号查询项目是否有甲供材清册
     */
    public Integer findMaterialData(String procInsId) {
        return mapper.findMaterialData(procInsId);
    }

    /**
     * 设计单位判定是否关闭
     */
    @Transactional(readOnly = false)
    public void actDesignUnit(Act act,ReserveProcess reserveProcess) {
        Map<String, Object> vars = Maps.newHashMap();
        String flag = act.getFlag();
        PersonnelTurnover user = MyActiviUtils.findCbUser(act.getProcInsId());
        if ("yes".equals(flag)) {
            vars.put("manager", UserUtils.getByUserName(user.getProjectManager()).getLoginName());
            SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = dft.format(new Date());
            //通过储备项目定义号，查询项目是否已经存在时间记录
            ProgressSchedule progressSchedule = scheduleMapper.findProjectReserveId(reserveProcess.getProjectReserveId());
            ProgressSchedule schedule = new ProgressSchedule();
            schedule.setDesignUpload(format);
            schedule.setProjectReserveId(reserveProcess.getProjectReserveId());
            if (null == progressSchedule) {
                schedule.preInsert();
                scheduleMapper.insert(schedule);
            }else {
                schedule.preUpdate();
                scheduleMapper.updateTimeNode(schedule);
            }
        } else {
            //结束项目流程，修改项目开始流程状态，清空人员流转信息，清空
            //删除对应的流程数据
            //删除对应甲供材信息
            mapper.deleteMaterial(reserveProcess.getProjectName());
            mapper.deleteAct(reserveProcess.getProjectReserveId());
            personnelTurnoverMapper.updateOpenStatus(reserveProcess.getProjectReserveId(), "0");
            personnelTurnoverService.deletePerson(reserveProcess.getProjectReserveId());
            vars.put("manager", UserUtils.getUser().getLoginName());
        }
        vars.put("pass", "yes".equals(flag) ? true : false);
        act.preUpdate();
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = act.getTaskDefKey();
        // 提交流程任务
        complete(act.getTaskId(), act.getProcInsId(), act.getComment(), vars);
    }

    /**
     * 项目经理判定是否通过
     */
    @Transactional(readOnly = false)
    public void actDrawingReview(Act act) {
        Map<String, Object> vars = Maps.newHashMap();
        String flag = act.getFlag();
        PersonnelTurnover user = MyActiviUtils.findCbUser(act.getProcInsId());
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dft.format(new Date());
        ProgressSchedule schedule = new ProgressSchedule();
        schedule.preUpdate();
        if ("yes".equals(flag)) {
            vars.put("manager", UserUtils.getByUserName(user.getEconomicPersonnel()).getLoginName());
            schedule.setDrawingReview(format);
            schedule.setProjectReserveId(mapper.findByProcInsId(act.getProcInsId()));
            scheduleMapper.updateTimeNode(schedule);
        } else {
            vars.put("manager", UserUtils.getByUserName(user.getDesignUnit()).getLoginName());
            schedule.setDesignUpload("-");
            schedule.setProjectReserveId(mapper.findByProcInsId(act.getProcInsId()));
            scheduleMapper.updateTimeNode(schedule);
        }
        vars.put("pass", "yes".equals(flag) ? true : false);
        act.preUpdate();
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = act.getTaskDefKey();
        // 提交流程任务
        complete(act.getTaskId(), act.getProcInsId(), act.getComment(), vars);
    }

    /**
     * 技经人员判断是否通过
     */
    @Transactional(readOnly = false)
    public void actEconomicPersonnel(Act act) {
        Map<String, Object> vars = Maps.newHashMap();
        String flag = act.getFlag();
        PersonnelTurnover user = MyActiviUtils.findCbUser(act.getProcInsId());
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dft.format(new Date());
        ProgressSchedule schedule = new ProgressSchedule();
        schedule.preUpdate();
        if ("yes".equals(flag)) {
            vars.put("manager", UserUtils.getByUserName(user.getProjectManager()).getLoginName());
            schedule.setEstimate(format);
            schedule.setProjectReserveId(mapper.findByProcInsId(act.getProcInsId()));
            scheduleMapper.updateTimeNode(schedule);
        } else {
            vars.put("manager", UserUtils.getByUserName(user.getOperationUnit()).getLoginName());
            schedule.setDrawingReview("-");
            schedule.setDesignUpload("-");
            schedule.setProjectReserveId(mapper.findByProcInsId(act.getProcInsId()));
            scheduleMapper.updateTimeNode(schedule);
        }
        vars.put("pass", "yes".equals(flag) ? true : false);
        act.preUpdate();
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = act.getTaskDefKey();
        // 提交流程任务
        complete(act.getTaskId(), act.getProcInsId(), act.getComment(), vars);
    }


    /**
     * 运行单位审图（联合审图）判断是否通过
     */
    @Transactional(readOnly = false)
    public void actOperationUnit(Act act) {
        Map<String, Object> vars = Maps.newHashMap();
        String flag = act.getFlag();
        PersonnelTurnover user = MyActiviUtils.findCbUser(act.getProcInsId());
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dft.format(new Date());
        ProgressSchedule schedule = new ProgressSchedule();
        schedule.preUpdate();
        if ("yes".equals(flag)) {
            vars.put("manager", UserUtils.getByUserName(user.getEconomicPersonnel()).getLoginName());
            schedule.setJointDrawing(format);
            schedule.setProjectReserveId(mapper.findByProcInsId(act.getProcInsId()));
            scheduleMapper.updateTimeNode(schedule);
            //审核通过修改项目状态，将物料信息导入年度物资上报统计
            //根据流程定义号查询项目编码
            ReserveManagement byProcInsId = reserveManagementMapper.findByProcInsId(act.getProcInsId());
            //通过储备编码查询项目的入库状态-如果是0修改为1，如果是2，修改成3
            String projectReserveId = byProcInsId.getProjectReserveId();
            String projectName = byProcInsId.getProjectName();
            PersonnelTurnover byReserveId = personnelTurnoverMapper.findByReserveId(projectReserveId);
            String addWareHousing = byReserveId.getAddWareHousing();
            if ("0".equals(addWareHousing)) {
                personnelTurnoverMapper.updateAddWareHousingStatus(projectReserveId, "1");
            } else {
                personnelTurnoverMapper.updateAddWareHousingStatus(projectReserveId, "3");
            }
            //修改项目甲供材清册状态
            personnelTurnoverMapper.updateMaterialStatus(projectReserveId, "2");
            personnelTurnoverMapper.updateOpenStatus(projectReserveId, "2");
            //获取所有的物料信息-导入年度物资上报统计
            List<MaterialInfo> materialByName = mapper.findMaterialByName(projectName);
            for (MaterialInfo m :
                    materialByName) {
                m.preInsert();
            }
            materialInfoMapper.insertList(materialByName);
            MaterialProject materialProject = new MaterialProject();
            materialProject.preInsert();
            materialProject.setReserveCode(projectReserveId);
            materialProject.setReserveProjectName(projectName);
            materialInfoMapper.deleteMaterial(projectName);
            projectMapper.insert(materialProject);
        } else {
            vars.put("manager", UserUtils.getByUserName(user.getDesignUnit()).getLoginName());
            schedule.setDrawingReview("-");
            schedule.setEstimate("-");
            schedule.setDesignUpload("-");
            schedule.setProjectReserveId(mapper.findByProcInsId(act.getProcInsId()));
            scheduleMapper.updateTimeNode(schedule);
        }
        vars.put("pass", "yes".equals(flag) ? true : false);
        act.preUpdate();
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = act.getTaskDefKey();
        // 提交流程任务
        complete(act.getTaskId(), act.getProcInsId(), act.getComment(), vars);
    }

    /**
     * 提交任务, 并保存意见
     *
     * @param taskId    任务ID
     * @param procInsId 流程实例ID，如果为空，则不保存任务提交意见
     * @param comment   任务提交意见的内容
     * @param vars      任务变量
     */
    @Transactional(readOnly = false)
    public void complete(String taskId, String procInsId, String comment, Map<String, Object> vars) {
        complete(taskId, procInsId, comment, "", vars);
    }

    @Transactional(readOnly = false)
    public void complete(String taskId, String procInsId, String comment, String title, Map<String, Object> vars) {
        // 添加意见
        if (StringUtils.isNotBlank(procInsId) && StringUtils.isNotBlank(comment)) {
            taskService.addComment(taskId, procInsId, comment);
        }

        // 设置流程变量
        if (vars == null) {
            vars = Maps.newHashMap();
        }

        // 设置流程标题
        if (StringUtils.isNotBlank(title)) {
            vars.put("title", title);
        }

        // 提交任务
        taskService.complete(taskId, vars);
    }

    /**
     *在年度物资上报统计表中保存项目信息，在年度上报明细表中保存物资信息
     */
    @Transactional(readOnly = false)
    public void saveData(MultipartFile file) throws IOException, InvalidFormatException {
        ImportExcel module = new ImportExcel(file,1,"模块表");
        Row row = module.getRow(0);
        Object obj = module.getCellValue(row, 1);
        if(obj==null){
            throw new RuntimeException("找不到项目名称！");
        }
        String projectName = ((String) obj).trim();
        //删除对应项目名称的甲供材信息
        mapper.deleteMaterial(projectName);
        ImportExcel pick = new ImportExcel(file,7,"领料清单");
        List<MaterialInfo> materialInfos = MaterialInfoUtil.getCbData(pick,projectName);   //获取领料清单数据
        List<MaterialInfo> list = MaterialInfoUtil.combineData(materialInfos);      //合并数据
        //通过甲供材信息比对物料规范获得项目建设规模

        saveList(list);
        //将领料清单保存后，获取所有物料规范详细信息，循环领料清单数据，将符合条件的
        List<Standard> standardList = standardMapper.findALl();
        //通过项目名称获取项目编号及名称
        ReserveManagement byName = reserveManagementMapper.findByName(projectName);
        //删除对应的项目规模数据
        detailsMapper.deleteName(projectName);
        ScaleDetails details = new ScaleDetails();
        //开关柜
        BigDecimal switchCabinet = BigDecimal.valueOf(0.0);
        //架空线路
        BigDecimal overheadLines = BigDecimal.valueOf(0.0);
        //电力电缆
        BigDecimal powerCable = BigDecimal.valueOf(0.0);
        //10千伏电缆分接箱
        BigDecimal cableBox =BigDecimal.valueOf(0.0);
        //环网箱/室
        BigDecimal ringCare =BigDecimal.valueOf(0.0);
        //开关站
        BigDecimal switchYard = BigDecimal.valueOf(0.0);
        //柱上开关
        BigDecimal postSwitch = BigDecimal.valueOf(0.0);
        //配电室kva
        StringBuilder distributionKva = new StringBuilder("");
        //配电室
        BigDecimal distribution = BigDecimal.valueOf(0.0);
        //箱变kva
        StringBuilder boxTransformerKva = new StringBuilder("");
        //箱变
        BigDecimal boxTransformer = BigDecimal.valueOf(0.0);
        //配电变压器kva
        StringBuilder disTransformerKva = new StringBuilder("");
        //配电变压器
        BigDecimal disTransformer = BigDecimal.valueOf(0.0);
        //低压线路
        BigDecimal lowVoltageLine = BigDecimal.valueOf(0.0);
        //低压电缆
        BigDecimal lowVoltageCable = BigDecimal.valueOf(0.0);
        //低压电缆分接箱
        BigDecimal lowDistributionBox = BigDecimal.valueOf(0.0);
        //低压配电箱（柜）
        BigDecimal lowBoxCabinet = BigDecimal.valueOf(0.0);
        //配电自动化终端（DTU）
        BigDecimal distributionTerminal = BigDecimal.valueOf(0.0);
        //电缆通道
        BigDecimal cableChannel = BigDecimal.valueOf(0.0);
        List<ScaleDetails> scaleDetails = new ArrayList<>();
        for (MaterialInfo m :
                list) {
            BigDecimal totalCount = BigDecimal.valueOf(m.getTotalCount());
            for (Standard s :
                    standardList) {
                if (m.getMaterialCode().equals(s.getMaterialCode()) && m.getMaterialName().equals(s.getMaterialDescription())) {
                    String projectCategory = s.getProjectCategory();

                    if ("开关柜".equals(projectCategory)) {
                        switchCabinet = switchCabinet.add(totalCount);
                    }
                    if ("架空线路".equals(projectCategory)) {
                        overheadLines = overheadLines.add(totalCount);
                    }
                    if ("电力电缆".equals(projectCategory)) {
                        powerCable = powerCable.add(totalCount);
                    }
                    if ("10千伏电缆分接箱".equals(projectCategory)) {
                        cableBox = cableBox.add(totalCount);
                    }
                    if ("环网箱/室".equals(projectCategory)) {
                        ringCare = ringCare.add(totalCount);
                    }
                    if ("开关站".equals(projectCategory)) {
                        switchYard = switchYard.add(totalCount);
                    }
                    if ("柱上开关".equals(projectCategory)) {
                        postSwitch = postSwitch.add(totalCount);
                    }

                    if ("配电室".equals(projectCategory)) {
                        int i = m.getTotalCount().compareTo(0.0);
                        if (i > 0) {
                            String materialDescription = s.getMaterialDescription();
                            String s1 = returnKva(materialDescription);
                            distributionKva.append(s1);
                        }
                        distribution = distribution.add(totalCount);
                    }

                    if ("箱变".equals(projectCategory)) {
                        int i = m.getTotalCount().compareTo(0.0);
                        if (i > 0) {
                        String materialDescription = s.getMaterialDescription();
                        String s1 = returnKva(materialDescription);
                        boxTransformerKva.append(s1);
                        }
                        boxTransformer = boxTransformer.add(totalCount);
                    }

                    if ("配电变压器".equals(projectCategory)) {
                        int i = m.getTotalCount().compareTo(0.0);
                        if (i > 0) {
                        String materialDescription = s.getMaterialDescription();
                        String s1 = returnKva(materialDescription);
                        disTransformerKva.append(s1);
                        }
                        disTransformer = disTransformer.add(totalCount);
                    }
                    if ("低压线路".equals(projectCategory)) {
                        lowVoltageLine = lowVoltageLine.add(totalCount);
                    }
                    if ("低压电缆".equals(projectCategory)) {
                        lowVoltageCable = lowVoltageCable.add(totalCount);
                    }
                    if ("低压电缆分接箱".equals(projectCategory)) {
                        lowDistributionBox = lowDistributionBox.add(totalCount);
                    }
                    if ("低压配电箱（柜）".equals(projectCategory)) {
                        lowBoxCabinet = lowBoxCabinet.add(totalCount);
                    }
                    if ("配电自动化终端（DTU）".equals(projectCategory)) {
                        distributionTerminal = distributionTerminal.add(totalCount);
                    }
                    if ("电缆通道".equals(projectCategory)) {
                        cableChannel = cableChannel.add(totalCount);
                    }
                }
            }
        }
        details.setProjectName(byName.getProjectName());
        details.setProjectReserveId(byName.getProjectReserveId());
        details.setSwitchCabinet(switchCabinet.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setOverheadLines(overheadLines.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setPowerCable(powerCable.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setCableBox(cableBox.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setRingCare(ringCare.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setSwitchYard(switchYard.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setPostSwitch(postSwitch.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setDistributionKva(distributionKva.toString());
        details.setDistribution(distribution.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setBoxTransformerKva(boxTransformerKva.toString());
        details.setBoxTransformer(boxTransformer.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setDisTransformerKva(disTransformerKva.toString());
        details.setDisTransformer(disTransformer.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setLowVoltageLine(lowVoltageLine.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setLowVoltageCable(lowVoltageCable.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setLowDistributionBox(lowDistributionBox.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setLowBoxCabinet(lowBoxCabinet.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setDistributionTerminal(distributionTerminal.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.setCableChannel(cableChannel.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        details.preInsert();
        detailsMapper.insert(details);
        personnelTurnoverMapper.updateMaterialStatus(byName.getProjectReserveId(), "1");
    }

    private String returnKva(String materialDescription) {
        if (null != materialDescription && !"".equals(materialDescription)) {
            boolean kVA = materialDescription.contains("kVA");
            if (kVA) {
                int kVA1 = materialDescription.lastIndexOf("kVA");
                String substring = materialDescription.substring(kVA1 - 3, kVA1+3);
                return substring;
            }
        }
        return "";
    }

    @Transactional(readOnly = false)
    public void saveList(List<MaterialInfo> list) {
        for(MaterialInfo maintainData : list){
            maintainData.preInsert();
        }
        mapper.insertList(list);
    }

    /**
     * 通过id查询符合条件的储备项目编码
     */
    public List<String> findIds(String[] ids) {
        return mapper.findIds(ids);
    }

    /**
     * 查询出所有的储备项目编码
     */
    public List<String> findAllId() {
        return mapper.findAllId();
    }


    /**
     * 通过项目名称导出储备项目的所有附件
     *
     * @param idList
     */
    public String exportFiles(List<String> idList) throws Exception {
        //设置下载的压缩包名（固定字符+时间戳）
        long timeMillis = System.currentTimeMillis();
        String fileLocality = "项目附件_" + timeMillis;
        //判定当前系统
        String path = Global.getPath();
        path = path + "/" + fileLocality;
        //检查该路径对应的目录是否存在. 如果不存在则创建目录
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }


        //通过id查询出所有的项目信息
        List<ReserveProcess> allList = mapper.findReserveById(idList);

        //循环遍历，判断项目是否存在
        for (ReserveProcess a :
                allList) {
            File dirFile = null;
            File dirFile2 = null;
            File dirFile3 = null;
            File dirFile4 = null;
            List<FilingImages> filingImagesList = null;
            List<FilingImages> exportList = new ArrayList<>();
            List<FilingImages> exportList2 = new ArrayList<>();
            List<FilingImages> exportList3 = new ArrayList<>();
            List<FilingImages> exportList4 = new ArrayList<>();
            String downloadPath = path + "/" + a.getProjectReserveId();
            String budgetStatement = a.getBudgetStatement();
            if (null!=budgetStatement && !"".equals(budgetStatement)) {
                dirFile = new File(downloadPath + "/预算书");
                if (budgetStatement.contains("|")) {
                    String[] split = budgetStatement.split("\\|");
                    for (int i = 0; i < split.length; i++) {
                        FilingImages filingImages = new FilingImages();
                        filingImages.setImgPath(split[i]);
                        exportList.add(filingImages);
                    }
                } else {
                    FilingImages filingImages = new FilingImages();
                    filingImages.setImgPath(budgetStatement);
                    exportList.add(filingImages);
                }
            }
            String projectProposal = a.getProjectProposal();
            if (null!=projectProposal && !"".equals(projectProposal)) {
                dirFile2 = new File(downloadPath + "/项目建议书");
                if (projectProposal.contains("|")) {
                    String[] split = projectProposal.split("\\|");
                    for (int i = 0; i < split.length; i++) {
                        FilingImages filingImages = new FilingImages();
                        filingImages.setImgPath(split[i]);
                        exportList2.add(filingImages);
                    }
                } else {
                    FilingImages filingImages = new FilingImages();
                    filingImages.setImgPath(projectProposal);
                    exportList2.add(filingImages);
                }
            }
            String drawings = a.getDrawings();
            if (null!=drawings && !"".equals(drawings)) {
                dirFile3 = new File(downloadPath + "/图纸");
                if (drawings.contains("|")) {
                    String[] split = drawings.split("\\|");
                    for (int i = 0; i < split.length; i++) {
                        FilingImages filingImages = new FilingImages();
                        filingImages.setImgPath(split[i]);
                        exportList3.add(filingImages);
                    }
                } else {
                    FilingImages filingImages = new FilingImages();
                    filingImages.setImgPath(drawings);
                    exportList3.add(filingImages);
                }
            }
            String drawingSpecification = a.getDrawingSpecification();
            if (null!=drawingSpecification && !"".equals(drawingSpecification)) {
                dirFile4 = new File(downloadPath + "/施工图设计说明书");
                if (drawingSpecification.contains("|")) {
                    String[] split = drawingSpecification.split("\\|");
                    for (int i = 0; i < split.length; i++) {
                        FilingImages filingImages = new FilingImages();
                        filingImages.setImgPath(split[i]);
                            exportList4.add(filingImages);
                    }
                } else {
                    FilingImages filingImages = new FilingImages();
                    filingImages.setImgPath(drawingSpecification);
                    exportList4.add(filingImages);
                }
            }
            if (exportList.size() > 0) {
                this.disposeFileList(exportList, dirFile.getPath());
            }
            if (exportList2.size() > 0) {
                this.disposeFileList(exportList2, dirFile2.getPath());
            }
            if (exportList3.size() > 0) {
                this.disposeFileList(exportList3, dirFile3.getPath());
            }
            if (exportList4.size() > 0) {
                this.disposeFileList(exportList4, dirFile4.getPath());
            }
        }
        //处理完之后进行打包压缩并删除之前的文件
        ZipCompressUtil zipUtil = new ZipCompressUtil();
        File resultFile = new File(path);
        File file = zipUtil.zipCompress(resultFile, true);
        return file.getPath();
    }

    /**
     * 处理文件信息
     *
     * @param downloadPath
     */
    public void disposeFileList(List<FilingImages> filingImages, String downloadPath) throws IOException {
        ZipCompressUtil zipCompressUtil = new ZipCompressUtil();
        String FILE_PREFIX = loader.getProperty("linux.file.store.prefix");
        if (SYS_TYPE.equals("1")) {
            for (FilingImages info : filingImages) {
                zipCompressUtil.downloadRuralProject(info.getImgPath().substring(0, info.getImgPath().lastIndexOf("/")), info.getImgPath().substring(info.getImgPath().lastIndexOf("/") + 1, info.getImgPath().length()), downloadPath);
            }
        } else {
            for (FilingImages info : filingImages) {
                zipCompressUtil.downloadRuralProject(FILE_PREFIX+info.getImgPath().substring(0, info.getImgPath().lastIndexOf("/")), info.getImgPath().substring(info.getImgPath().lastIndexOf("/") + 1, info.getImgPath().length()), downloadPath);
            }
        }

    }

}
