package com.njcn.process.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.pms.pojo.po.StatationStat;
import com.njcn.minioss.bo.MinIoUploadResDTO;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.enums.OssResponseEnum;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.poi.util.PoiUtil;
import com.njcn.process.mapper.RGeneralSurveyPlanDetailMapper;
import com.njcn.process.mapper.RGeneralSurveyPlanPOMapper;
import com.njcn.process.mapper.RSurveyCycleMapper;
import com.njcn.process.pojo.param.*;
import com.njcn.process.pojo.po.RGeneralSurveyPlanDetail;
import com.njcn.process.pojo.po.RGeneralSurveyPlanPO;
import com.njcn.process.pojo.po.RSurveyCyclePO;
import com.njcn.process.pojo.po.RSurveyPlanConfigPO;
import com.njcn.process.pojo.vo.*;
import com.njcn.process.service.RGeneralSurveyPlanDetailService;
import com.njcn.process.service.RGeneralSurveyPlanPOService;
import com.njcn.process.service.StatationStatService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
import com.njcn.user.pojo.vo.PvTerminalTreeVO;
import com.njcn.web.utils.RequestUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Description:
 * 接口文档访问地址：http://serverIP:port/swagger-ui.html
 * Date: 2022/11/11  11:24【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
public class RGeneralSurveyPlanPOServiceImpl extends MppServiceImpl<RGeneralSurveyPlanPOMapper, RGeneralSurveyPlanPO> implements RGeneralSurveyPlanPOService {

    @Autowired
    private RGeneralSurveyPlanDetailService rGeneralSurveyPlanDetailService;

    @Resource
    private RGeneralSurveyPlanPOMapper rGeneralSurveyPlanPOMapper;

    @Resource
    private RGeneralSurveyPlanDetailMapper rGeneralSurveyPlanDetailMapper;

    @Autowired
    private DeptFeignClient deptFeignClient;

    @Resource
    private FileStorageUtil fileStorageUtil;

    @Autowired
    private StatationStatService statationStatService;
    @Autowired
    private DicDataFeignClient dicDataFeignClient;

    @Autowired
    private RSurveyCycleMapper rSurveyCycleMapper;

    @Autowired
    private RSurveyPlanConfigService rSurveyPlanConfigService;


    /**
     * @param rGeneralSurveyPlanAddParm
     * @Description: addPlan
     * @Param: [rGeneralSurveyPlanAddParm]
     * @return: java.lang.Boolean
     * @Author: clam
     * @Date: 2022/11/14
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addPlan(RGeneralSurveyPlanAddParm rGeneralSurveyPlanAddParm) {

        RGeneralSurveyPlanPO rGeneralSurveyPlanPO = new RGeneralSurveyPlanPO ( );
        BeanUtils.copyProperties (rGeneralSurveyPlanAddParm, rGeneralSurveyPlanPO);
        /*todo 后期与工作流绑定*/
        rGeneralSurveyPlanPO.setStatus (1);
        /**查出周期id**/
        QueryWrapper<RSurveyCyclePO> rSurveyCyclePOQueryWrapper = new QueryWrapper ( );
        rSurveyCyclePOQueryWrapper.le ("start_year", rGeneralSurveyPlanPO.getPlanEndTime ( ));
        rSurveyCyclePOQueryWrapper.ge ("end_year", rGeneralSurveyPlanPO.getPlanEndTime ( ));
        RSurveyCyclePO rSurveyCyclePO = rSurveyCycleMapper.selectOne (rSurveyCyclePOQueryWrapper);

        rGeneralSurveyPlanPO.setCycleId (rSurveyCyclePO.getId ( ));
        String deptIndex = RequestUtil.getDeptIndex ( );
        Dept data = deptFeignClient.getDeptById (deptIndex).getData ( );
        rGeneralSurveyPlanPO.setCheckPerson (data.getPid ());
        rGeneralSurveyPlanPO.setCreatePerson (RequestUtil.getUserIndex ());
         boolean b = this.saveOrUpdateByMultiId (rGeneralSurveyPlanPO);

        QueryWrapper<RGeneralSurveyPlanDetail> queryWrapper = new QueryWrapper ( );
        queryWrapper.lambda ( ).eq (RGeneralSurveyPlanDetail::getPlanNo, rGeneralSurveyPlanAddParm.getPlanNo ( ));
        rGeneralSurveyPlanDetailService.remove (queryWrapper);
        List<RGeneralSurveyPlanDetail> rGeneralSurveyPlanDetailList = new ArrayList<> ( );
        rGeneralSurveyPlanAddParm.getSubIds ( ).forEach (temp -> {
            StatationStat byId = statationStatService.getById (temp);
            RGeneralSurveyPlanDetail rGeneralSurveyPlanDetail = new RGeneralSurveyPlanDetail ( );
            rGeneralSurveyPlanDetail.setPlanNo (rGeneralSurveyPlanAddParm.getPlanNo ( ));
            rGeneralSurveyPlanDetail.setOrgNo (byId.getOrgId ( ));
            rGeneralSurveyPlanDetail.setOrgName (byId.getOrgName ( ));
            rGeneralSurveyPlanDetail.setSubId (byId.getPowerId ( ));
            rGeneralSurveyPlanDetail.setSubName (byId.getPowerName ( ));
            /*目前时间与计划开始时间，结束时间一致*/
            rGeneralSurveyPlanDetail.setGeneralSurveyStartTime (rGeneralSurveyPlanAddParm.getPlanStartTime ( ));
            rGeneralSurveyPlanDetail.setGeneralSurveyTime (rGeneralSurveyPlanAddParm.getPlanStartTime ( ));
            rGeneralSurveyPlanDetail.setGeneralSurveyEndTime (rGeneralSurveyPlanAddParm.getPlanEndTime ( ));
            rGeneralSurveyPlanDetail.setPlanNo (rGeneralSurveyPlanAddParm.getPlanNo ( ));
            rGeneralSurveyPlanDetail.setGeneralSurveyLeader (rGeneralSurveyPlanAddParm.getLeader ( ));
            rGeneralSurveyPlanDetailList.add (rGeneralSurveyPlanDetail);
        });
        boolean b1 = rGeneralSurveyPlanDetailService.saveOrUpdateBatchByMultiId (rGeneralSurveyPlanDetailList, 500);

        return b && b1;
    }

    /**
     * @param rGeneralSurveyPlanQueryParm
     * @Description: query
     * @Param: [rGeneralSurveyPlanQueryParm]
     * @return: java.util.List<com.njcn.process.pojo.vo.RGeneralSurveyPlanVO>
     * @Author: clam
     * @Date: 2022/11/15
     */
    @Override
    public IPage<RGeneralSurveyPlanVO> query(RGeneralSurveyPlanQueryParm rGeneralSurveyPlanQueryParm, List<String> statusList,String type) {
        IPage<RGeneralSurveyPlanPO> page = new Page<> (rGeneralSurveyPlanQueryParm.getCurrentPage ( ), rGeneralSurveyPlanQueryParm.getPageSize ( ));
        IPage<RGeneralSurveyPlanVO> returnpage = new Page<> (rGeneralSurveyPlanQueryParm.getCurrentPage ( ), rGeneralSurveyPlanQueryParm.getPageSize ( ));

        LambdaQueryWrapper<RGeneralSurveyPlanPO> queryWrapper = new LambdaQueryWrapper<> ( );
        /*type=1：新建页面：查看自己负责的计划；type=2：审核页面：审核者==当前用户；结果页面：查看自己负责的计划*/
        if(type=="1"||type=="3"){
            queryWrapper.eq (RGeneralSurveyPlanPO::getCreatePerson,RequestUtil.getUserIndex ());
        }
        if(type=="2"){
            queryWrapper.eq (RGeneralSurveyPlanPO::getCheckPerson,RequestUtil.getDeptIndex ());
        }
        if (!StringUtils.isEmpty (rGeneralSurveyPlanQueryParm.getOrgNo ( ))) {
            List<String> data = deptFeignClient.getDepSonIdtByDeptId (rGeneralSurveyPlanQueryParm.getOrgNo ( )).getData ( );

            queryWrapper.in (RGeneralSurveyPlanPO::getOrgNo, data);
        }
        if (!StringUtils.isEmpty (rGeneralSurveyPlanQueryParm.getStatus ( ))) {
            queryWrapper.eq (RGeneralSurveyPlanPO::getStatus, rGeneralSurveyPlanQueryParm.getStatus ( ));
        }
        if (!StringUtils.isEmpty (rGeneralSurveyPlanQueryParm.getIsFileUpload ( ))) {
            queryWrapper.eq (RGeneralSurveyPlanPO::getIsFileUpload, rGeneralSurveyPlanQueryParm.getIsFileUpload ( ));
        }
        if (!Objects.isNull (rGeneralSurveyPlanQueryParm.getPlanStartTime ( ))) {
            queryWrapper.ge (RGeneralSurveyPlanPO::getPlanStartTime, rGeneralSurveyPlanQueryParm.getPlanStartTime ( ));
        }
        if (!Objects.isNull (rGeneralSurveyPlanQueryParm.getPlanEndTime ( ))) {
            queryWrapper.le (RGeneralSurveyPlanPO::getPlanStartTime, rGeneralSurveyPlanQueryParm.getPlanEndTime ( ));
        }
        queryWrapper.in (RGeneralSurveyPlanPO::getStatus, statusList);
        queryWrapper.orderByAsc (RGeneralSurveyPlanPO::getStatus).orderByDesc (RGeneralSurveyPlanPO::getPlanCreateTime);

        List<RGeneralSurveyPlanPO> rGeneralSurveyPlanPOS = rGeneralSurveyPlanPOMapper.selectPage (page, queryWrapper).getRecords ( );
        if (CollectionUtils.isEmpty (rGeneralSurveyPlanPOS)) {
            return returnpage;
        }

        //部门处理：根据部门code取名称
        List<PvTerminalTreeVO> dept = deptFeignClient.allDeptList ( ).getData ( );
        Map<String, String> pvTerminalTreeVOMap = dept.stream ( ).
                collect (Collectors.
                        toMap (PvTerminalTreeVO::getId,
                                PvTerminalTreeVO::getName));


        List<String> collect = rGeneralSurveyPlanPOS.stream ( ).map (RGeneralSurveyPlanPO::getPlanNo).collect (Collectors.toList ( ));
        LambdaQueryWrapper<RGeneralSurveyPlanDetail> lambdaQueryWrapper = new LambdaQueryWrapper<> ( );
        lambdaQueryWrapper.in (RGeneralSurveyPlanDetail::getPlanNo, collect);
        List<RGeneralSurveyPlanDetail> rGeneralSurveyPlanDetails = rGeneralSurveyPlanDetailMapper.selectList (lambdaQueryWrapper);
        List<RGeneralSurveyPlanVO> rGeneralSurveyPlanVOList = new ArrayList<> ( );
        rGeneralSurveyPlanPOS.forEach (temp -> {
            RGeneralSurveyPlanVO rGeneralSurveyPlanVO = new RGeneralSurveyPlanVO ( );
            BeanUtils.copyProperties (temp, rGeneralSurveyPlanVO);
            List<String> collect1 = rGeneralSurveyPlanDetails.stream ( ).
                    filter (surveyPlanDetail -> Objects.equals (surveyPlanDetail.getPlanNo ( ), temp.getPlanNo ( ))).
                    map (RGeneralSurveyPlanDetail::getSubId).collect (Collectors.toList ( ));
            rGeneralSurveyPlanVO.setSubCount (collect1.size ( ));
            rGeneralSurveyPlanVO.setSubIds (collect1);
/*
            long Subcount = rGeneralSurveyPlanDetails.stream ( ).
                    filter (surveyPlanDetail -> Objects.equals (surveyPlanDetail.getPlanNo ( ), temp.getPlanNo ( ))).
                    map (RGeneralSurveyPlanDetail::getSubId).distinct ( ).count ( );*/
//            rGeneralSurveyPlanVO.setBusCount (Busbarcount);
//            List<RGeneralSurveyPlanVO.RGeneralSurveyPlanDetailVO> collect1 = rGeneralSurveyPlanDetails.stream ( ).
//                    filter (surveyPlanDetail -> Objects.equals (surveyPlanDetail.getPlanNo ( ), temp.getPlanNo ( ))).
//                    map (surveyPlanDetail -> {
//                        RGeneralSurveyPlanVO.RGeneralSurveyPlanDetailVO rGeneralSurveyPlanDetailVO = new RGeneralSurveyPlanVO.RGeneralSurveyPlanDetailVO ( );
//                        BeanUtils.copyProperties (surveyPlanDetail, rGeneralSurveyPlanDetailVO);
//                        return rGeneralSurveyPlanDetailVO;
//                    }).collect (Collectors.toList ( ));
            rGeneralSurveyPlanVO.setOrgName (pvTerminalTreeVOMap.get (temp.getOrgNo ( ))); //单位名称
//
//            rGeneralSurveyPlanVO.setRGeneralSurveyPlanDetailVOList (collect1);

            rGeneralSurveyPlanVOList.add (rGeneralSurveyPlanVO);
        });
        returnpage.setRecords (rGeneralSurveyPlanVOList);
        return returnpage;
    }

    /**
     * @param surveyResultUploadParam
     * @Description: surveyResultUpload
     * @Param: [surveyResultUploadParam]
     * @return: boolean
     * @Author: clam
     * @Date: 2022/11/18
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean surveyResultUpload(SurveyResultUploadParam surveyResultUploadParam) {
        boolean result = true;
        RGeneralSurveyPlanPO rGeneralSurveyPlanPO = new RGeneralSurveyPlanPO ( );
        rGeneralSurveyPlanPO.setPlanNo (surveyResultUploadParam.getPlanId ( ));
        rGeneralSurveyPlanPO = this.selectByMultiId (rGeneralSurveyPlanPO);
        String filePath = rGeneralSurveyPlanPO.getFilePath ( );
        filePath = Optional.ofNullable (filePath).orElse ("");
        Integer fileCount = rGeneralSurveyPlanPO.getFileCount ( );
        fileCount = Optional.ofNullable (fileCount).orElse (0);
        for (int i = 0; i < surveyResultUploadParam.getFile ( ).length; i++) {
            String OriginalFilename = surveyResultUploadParam.getFile ( )[i].getOriginalFilename ( );
            String fileStoragePath = fileStorageUtil.uploadMultipart (surveyResultUploadParam.getFile ( )[i], OssPath.SURVEY_RESULT);
            /*filePath格式：minIo服务文件名+##+原始文件名+；*/
            filePath = filePath + fileStoragePath + "##" + OriginalFilename + ";";
            fileCount++;
        }
        rGeneralSurveyPlanPO.setStatus (4);
        rGeneralSurveyPlanPO.setFileCount (fileCount);
        rGeneralSurveyPlanPO.setFilePath (filePath);
        rGeneralSurveyPlanPO.setIsFileUpload (1);
        rGeneralSurveyPlanPO.setUploadTime (new Date ( ));
        this.saveOrUpdateByMultiId (rGeneralSurveyPlanPO);
        return result;
    }

    /**
     * @param planNo
     * @Description: surveyResultDownload
     * @Param: [surveyResultUploadParam]
     * @return: java.util.List<java.lang.String>
     * @Author: clam
     * @Date: 2022/11/18
     */
    @Override
    public List<MinIoUploadResDTO> surveyResultDownload(String planNo) {
        RGeneralSurveyPlanPO rGeneralSurveyPlanPO = new RGeneralSurveyPlanPO ( );
        rGeneralSurveyPlanPO.setPlanNo (planNo);
        rGeneralSurveyPlanPO = this.selectByMultiId (rGeneralSurveyPlanPO);
        String filePath = rGeneralSurveyPlanPO.getFilePath ( );
        if (StringUtils.isEmpty (filePath)) {
            throw new BusinessException (OssResponseEnum.DOWNLOAD_FILE_ERROR);
        }
        String[] split = filePath.substring (0, filePath.length ( ) - 1).split (";");
        List<MinIoUploadResDTO> collect = Stream.of (split).map (temp -> {
            String[] split1 = temp.split ("##");
            String OriginalFilename = split1[1];
            String minoFileName = split1[0];
            MinIoUploadResDTO dto = new MinIoUploadResDTO (OriginalFilename, fileStorageUtil.getFileUrl (minoFileName));
            return dto;
        }).collect (Collectors.toList ( ));
        return collect;
    }

    /**
     * @Description: exportSurveyPlan
     * @Param: []
     * @return: java.util.List<com.njcn.process.pojo.vo.SurveyPlanExcel>
     * @Author: clam
     * @Date: 2022/11/21
     */
    @Override
    public List<SurveyPlanExcel> exportSurveyPlan(List<String> planIdList) {
        List<SurveyPlanExcel> surveyPlanExcels = new ArrayList<> ( );
        LambdaQueryWrapper<RGeneralSurveyPlanPO> queryWrapper = new LambdaQueryWrapper<> ( );
        queryWrapper.in (RGeneralSurveyPlanPO::getPlanNo, planIdList);
        List<RGeneralSurveyPlanPO> rGeneralSurveyPlanPOS = rGeneralSurveyPlanPOMapper.selectList (queryWrapper);
        LambdaQueryWrapper<RGeneralSurveyPlanDetail> lambdaQueryWrapper = new LambdaQueryWrapper<> ( );
        lambdaQueryWrapper.in (RGeneralSurveyPlanDetail::getPlanNo, planIdList);
        List<RGeneralSurveyPlanDetail> rGeneralSurveyPlanDetails = rGeneralSurveyPlanDetailMapper.selectList (lambdaQueryWrapper);

        //部门处理：根据部门code取名称
        List<PvTerminalTreeVO> dept = deptFeignClient.allDeptList ( ).getData ( );
        Map<String, String> pvTerminalTreeVOMap = dept.stream ( ).
                collect (Collectors.
                        toMap (PvTerminalTreeVO::getId,
                                PvTerminalTreeVO::getName));
        rGeneralSurveyPlanPOS.forEach (temp -> {
            SurveyPlanExcel surveyPlanExcel = new SurveyPlanExcel ( );
            BeanUtils.copyProperties (temp, surveyPlanExcel);

//            long Busbarcount = rGeneralSurveyPlanDetails.stream ( ).
//                    filter (surveyPlanDetail -> Objects.equals (surveyPlanDetail.getPlanNo ( ), temp.getPlanNo ( ))).
//                    map (RGeneralSurveyPlanDetail::getBusbarId).distinct ( ).count ( );

            long Subcount = rGeneralSurveyPlanDetails.stream ( ).
                    filter (surveyPlanDetail -> Objects.equals (surveyPlanDetail.getPlanNo ( ), temp.getPlanNo ( ))).
                    map (RGeneralSurveyPlanDetail::getSubId).distinct ( ).count ( );
//            surveyPlanExcel.setBusCount (Busbarcount);
            surveyPlanExcel.setSubCount (Subcount);
            surveyPlanExcel.setOrgNo (pvTerminalTreeVOMap.get (surveyPlanExcel.getOrgNo ( )));
            surveyPlanExcel.setStatus (getPlanStatus(temp.getStatus ()));
            surveyPlanExcels.add (surveyPlanExcel);
        });

        return surveyPlanExcels;
    }

    private String getPlanStatus(int status) {
        String result = "";
        switch (status) {
            case 0:
                result = "新建";
                break;
            case 1:
                result = "待审核";
                break;
            case 2:
                result = "审核未通过";
                break;
            case 3:
                result = "已发布";
                break;
            case 4:
                result = "已完成";
                break;
            default:
                result = "";
        }
        return result;
    }
    /**
     * @param questionQueryParm
     * @Description: querySurveyPlanOnQuestion
     * @Param: [questionQueryParm]
     * @return: java.util.List<com.njcn.process.pojo.vo.RGeneralSurveyPlanDetailOnQuestionVO>
     * @Author: clam
     * @Date: 2022/11/30
     */
    @Override
    public List<RGeneralSurveyPlanDetailOnQuestionVO> querySurveyPlanOnQuestion(SurveyPlanQuestionQueryParm questionQueryParm) {
        List<RGeneralSurveyPlanDetailOnQuestionVO> rGeneralSurveyPlanDetailOnQuestionVOS = new ArrayList<> ( );
        rGeneralSurveyPlanDetailOnQuestionVOS = rGeneralSurveyPlanDetailMapper.querySurveyPlanOnQuestion (questionQueryParm);

        return rGeneralSurveyPlanDetailOnQuestionVOS;
    }

    /**
     * @param questionQueryParm
     * @Description: 更具questionQueryParm查计划名称
     * @Param: [questionQueryParm]
     * @return: java.util.List<com.njcn.process.pojo.param.SurveyPlanQuestionQueryParm>
     * @Author: clam
     * @Date: 2022/12/1
     */
    @Override
    public List<RGeneralSurveyPlanPO> querySurveyPlanName(SurveyPlanQuestionQueryParm questionQueryParm) {

        List<String> data = deptFeignClient.getDepSonIdtByDeptId (questionQueryParm.getOrgNo ( )).getData ( );

        QueryWrapper<RGeneralSurveyPlanPO> queryWrapper = new QueryWrapper<> ( );
        queryWrapper.select ("plan_name").
                in ("org_no", data).
                eq ("DATE_FORMAT(upload_time, '%Y-%m')", new SimpleDateFormat ("yyyy-MM").
                        format (questionQueryParm.getPlanStartTime ( )));
        List<RGeneralSurveyPlanPO> list = this.list (queryWrapper);

        return list;
    }

    /**
     * @param rGeneralSurveyPlanChcekParm
     * @Description: checkPlanAudit
     * @Param: [rGeneralSurveyPlanChcekParm]
     * @return: java.lang.Boolean
     * @Author: clam
     * @Date: 2023/2/22
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean checkPlanAudit(RGeneralSurveyPlanChcekParm rGeneralSurveyPlanChcekParm) {
        boolean result = true;
        UpdateWrapper<RGeneralSurveyPlanPO> updateWrapper = new UpdateWrapper ( );
        updateWrapper.eq ("plan_no", rGeneralSurveyPlanChcekParm.getPlanNo ( ));
        updateWrapper.set ("check_comment", rGeneralSurveyPlanChcekParm.getCheckComment ( ));
//        updateWrapper.set ("check_person", rGeneralSurveyPlanChcekParm.getCheckPerson ( ));
        updateWrapper.set ("status", Objects.equals ("1", rGeneralSurveyPlanChcekParm.getCheckResult ( )) ? 3 : 2);
        result = this.update (updateWrapper);
        return result;
    }

    @Override
    public void importSubStatation(MultipartFile file, HttpServletResponse response) {
        ImportParams params = new ImportParams ( );
        params.setHeadRows (1);
        params.setTitleRows (0);
        //params.setNeedVerify(true);
        //第一个sheet为台账信息
        params.setStartSheetIndex (0);
        params.setSheetNum (1);
        try {
            ExcelImportResult<StatationStatExcel> terminalBaseList = ExcelImportUtil.importExcelMore (file.getInputStream ( ), StatationStatExcel.class, params);
            //如果存在非法数据，将不合格的数据导出

            /*规则1:StatationStat的orgName要在原系统存在2:电压等级不对*/
            List<PvTerminalTreeVO> data = deptFeignClient.allDeptList ( ).getData ( );
            Map<String, PvTerminalTreeVO> pvTerminalTreeVOMap = data.stream ( ).collect (Collectors.toMap (PvTerminalTreeVO::getName, pvTerminalTreeVO -> pvTerminalTreeVO));
            //获取电压等级的字典
            List<DictData> voltageLevelList = dicDataFeignClient.getDicDataByTypeCode (DicDataTypeEnum.DEV_VOLTAGE.getCode ( )).getData ( );
            //将电压信息转成map，key：id  value：name
            Map<String, DictData> voltageLevelMap = voltageLevelList.stream ( ).collect (Collectors.toMap (DictData::getName, voltageLevel -> voltageLevel));
            List<StatationStatExcel> trueCollect = new ArrayList<> ( );
            List<StatationStatExcel> falseCollect = new ArrayList<> ( );
            for (int i = 0; i < terminalBaseList.getList ( ).size ( ); i++) {
                StatationStatExcel statationStatExcel = terminalBaseList.getList ( ).get (i);
                if (pvTerminalTreeVOMap.containsKey (statationStatExcel.getOrgName ( ))) {
                    statationStatExcel.setOrgId (pvTerminalTreeVOMap.get (statationStatExcel.getOrgName ( )).getId ( ));
                } else {
                    statationStatExcel.setExceptionMessage ("系统中不存在此电站的部门");
                    falseCollect.add (statationStatExcel);
                    continue;
                }
                if (voltageLevelMap.containsKey (statationStatExcel.getVoltageLevel ( ))) {
                    statationStatExcel.setVoltageLevel (voltageLevelMap.get (statationStatExcel.getVoltageLevel ( )).getId ( ));
                } else {
                    statationStatExcel.setExceptionMessage ("系统中不存在此电站的电压等级");
                    falseCollect.add (statationStatExcel);
                    continue;
                }
                trueCollect.add (statationStatExcel);

            }
            if (!CollectionUtils.isEmpty (trueCollect)) {
                List<StatationStat> collect = trueCollect.stream ( ).map (temp -> {
                    StatationStat statationStat = new StatationStat ( );
                    BeanUtils.copyProperties (temp, statationStat);
                    return statationStat;
                }).collect (Collectors.toList ( ));
                statationStatService.saveOrUpdateBatch (collect, 500);
            }
            if (!CollectionUtils.isEmpty (falseCollect)) {
                ExportParams exportExcel = new ExportParams ("批量导入模板（请严格按照模板标准填入数据）", "非法电站信息");
                Workbook workbook = ExcelExportUtil.exportExcel (exportExcel, StatationStatExcel.class, falseCollect);
                PoiUtil.exportFileByWorkbook (workbook, "非法台账信息.xlsx", response);

            }

        } catch (Exception e) {
            e.printStackTrace ( );
        }
    }

    @Override
    public RGeneralSurveyPlanAddParm querySubStatation(Integer statetionNum) {
        /*查询所有电站并过滤已经参加当期普测电站*/
        List<StatationStat> list = statationStatService.list ( );

        /**查出当前周期id**/
        QueryWrapper<RSurveyCyclePO> rSurveyCyclePOQueryWrapper = new QueryWrapper ( );
        rSurveyCyclePOQueryWrapper.le ("start_year", LocalDate.now ( ));
        rSurveyCyclePOQueryWrapper.ge ("end_year", LocalDate.now ( ));
        RSurveyCyclePO rSurveyCyclePO = rSurveyCycleMapper.selectOne (rSurveyCyclePOQueryWrapper);


        LambdaQueryWrapper<RGeneralSurveyPlanPO> queryWrapper = new LambdaQueryWrapper<> ( );
        queryWrapper.eq (RGeneralSurveyPlanPO::getCycleId, rSurveyCyclePO.getId ( ));
        List<RGeneralSurveyPlanPO> rGeneralSurveyPlanPOS = rGeneralSurveyPlanPOMapper.selectList (queryWrapper);
        List<String> planIds = rGeneralSurveyPlanPOS.stream ( ).map (RGeneralSurveyPlanPO::getPlanNo).collect (Collectors.toList ( ));
        List<String> subIds = new ArrayList<> ( );
        if (!CollectionUtils.isEmpty (planIds)) {
            QueryWrapper<RGeneralSurveyPlanDetail> rGeneralSurveyPlanDetailQueryWrapper = new QueryWrapper ( );
            rGeneralSurveyPlanDetailQueryWrapper.in ("plan_no", planIds);
            List<RGeneralSurveyPlanDetail> rGeneralSurveyPlanDetails = rGeneralSurveyPlanDetailMapper.selectList (rGeneralSurveyPlanDetailQueryWrapper);
            subIds = rGeneralSurveyPlanDetails.stream ( ).map (RGeneralSurveyPlanDetail::getSubId).collect (Collectors.toList ( ));
        }


        List<String> finalSubIds = subIds;
        List<StatationStat> filterList = list.stream ( ).filter (temp -> !finalSubIds.contains (temp.getPowerId ( ))).collect (Collectors.toList ( ));
        List<StatationStat> addList = new ArrayList<> ( );

        List<RSurveyPlanConfigPO> rSurveyPlanConfigPOList = rSurveyPlanConfigService.list ( );
        Map<String, RSurveyPlanConfigPO> orgIdMap = rSurveyPlanConfigPOList.stream ( ).
                collect (Collectors.toMap (RSurveyPlanConfigPO::getOrgId, temp -> temp));
        List<PvTerminalTreeVO> data = deptFeignClient.allDeptList ( ).getData ( );
        data.stream ( ).forEach (temp -> {
            DeptSubstationVO deptSubstationVO = new DeptSubstationVO ( );
            BeanUtils.copyProperties (temp, deptSubstationVO);
            /*如果存在电站占比配置随机抽出配置电站个数*/
            if (orgIdMap.containsKey (temp.getId ( ))) {
                List<StatationStat> collect = filterList.stream ( ).filter (statationStat -> Objects.
                        equals (statationStat.getOrgId ( ), temp.getId ( ))).collect (Collectors.toList ( ));
                RSurveyPlanConfigPO rSurveyPlanConfigPO = orgIdMap.get (temp.getId ( ));
                //向上取整
                int v = (int) Math.ceil (rSurveyPlanConfigPO.getProportion ( ) *
                        statetionNum);
                if (collect.size ( ) >= v) {
                    Collections.shuffle (collect);
                    List<StatationStat> lastList = collect.stream ( ).limit (v).collect (Collectors.toList ( ));
                    addList.addAll (lastList);
                } else {
                    addList.addAll (collect);
                }
            }

        });


        if (statetionNum > addList.size ( )) {
            /*取差集，当通过比例抽取变电站不够时 重差集里取*/
            List<StatationStat> collect = filterList.stream ( ).filter (o -> !addList.contains (o)).collect (Collectors.toList ( ));
            int differenceCount = statetionNum - addList.size ( );
            Collections.shuffle (collect);
            List<StatationStat> lastList = collect.stream ( ).limit (differenceCount).collect (Collectors.toList ( ));
            addList.addAll (lastList);
        }
        List<String> result = addList.stream ( ).map (StatationStat::getPowerId).collect (Collectors.toList ( ));
        RGeneralSurveyPlanAddParm rGeneralSurveyPlanAddParm = new RGeneralSurveyPlanAddParm ( );
        rGeneralSurveyPlanAddParm.setSubIds (result);
        return rGeneralSurveyPlanAddParm;
    }

    @Override
    public List<DeptSubstationVO> initDetpStataionTree(String orgdid) {

        /*查询所有电站并过滤已经参加当期普测电站*/
        List<StatationStat> list = statationStatService.list ( );

        /**查出当前周期id**/
        QueryWrapper<RSurveyCyclePO> rSurveyCyclePOQueryWrapper = new QueryWrapper ( );
        rSurveyCyclePOQueryWrapper.le ("start_year", LocalDate.now ( ));
        rSurveyCyclePOQueryWrapper.ge ("end_year", LocalDate.now ( ));
        RSurveyCyclePO rSurveyCyclePO = rSurveyCycleMapper.selectOne (rSurveyCyclePOQueryWrapper);
/**
 * 不存则新建周期
 */
        if (Objects.equals (rSurveyCyclePO, null)) {
            List<RSurveyCyclePO> rSurveyCyclePOS = rSurveyCycleMapper.selectList (null);
            int cycleNum = 0;
            if (CollectionUtils.isEmpty (rSurveyCyclePOS)) {

                cycleNum = 5;
            } else {
                rSurveyCyclePOS = rSurveyCyclePOS.stream ( )
                        .sorted (Comparator.comparing (RSurveyCyclePO::getEndYear).reversed ( ))
                        .collect (Collectors.toList ( ));

                cycleNum = rSurveyCyclePOS.get (0).getSurveyCycle ( );
            }
            LocalDate enddate = LocalDate.now ( ).plusYears (cycleNum);
            rSurveyCyclePO = new RSurveyCyclePO ( );
            rSurveyCyclePO.setStartYear (LocalDate.now ( ));
            rSurveyCyclePO.setEndYear (enddate);
            rSurveyCyclePO.setSurveyCycle (cycleNum);
            rSurveyCycleMapper.insert (rSurveyCyclePO);
        }

        LambdaQueryWrapper<RGeneralSurveyPlanPO> queryWrapper1 = new LambdaQueryWrapper<> ( );
        queryWrapper1.eq (RGeneralSurveyPlanPO::getCycleId, rSurveyCyclePO.getId ( ));
        queryWrapper1.in (RGeneralSurveyPlanPO::getStatus, Stream.of (3, 4).collect (Collectors.toList ( )));
        List<RGeneralSurveyPlanPO> rGeneralSurveyPlanPOS = rGeneralSurveyPlanPOMapper.selectList (queryWrapper1);
        List<String> planIds = rGeneralSurveyPlanPOS.stream ( ).map (RGeneralSurveyPlanPO::getPlanNo).collect (Collectors.toList ( ));
        List<String> subIds = new ArrayList<> ( );
        if (!CollectionUtils.isEmpty (planIds)) {
            QueryWrapper<RGeneralSurveyPlanDetail> rGeneralSurveyPlanDetailQueryWrapper = new QueryWrapper ( );
            rGeneralSurveyPlanDetailQueryWrapper.in ("plan_no", planIds);
            List<RGeneralSurveyPlanDetail> rGeneralSurveyPlanDetails = rGeneralSurveyPlanDetailMapper.selectList (rGeneralSurveyPlanDetailQueryWrapper);
            subIds = rGeneralSurveyPlanDetails.stream ( ).map (RGeneralSurveyPlanDetail::getSubId).collect (Collectors.toList ( ));
        }


        List<String> finalSubIds = subIds;

        List<PvTerminalTreeVO> data = deptFeignClient.allDeptList ( ).getData ( );
        List<DeptSubstationVO> deptSubstationVOList = data.stream ( ).map (temp -> {
            DeptSubstationVO deptSubstationVO = new DeptSubstationVO ( );
            BeanUtils.copyProperties (temp, deptSubstationVO);
            deptSubstationVO.setDisabled (true);
            deptSubstationVO.setFlag (true);
            QueryWrapper<StatationStat> queryWrapper = new QueryWrapper<> ( );
            queryWrapper.eq ("org_id", temp.getCode ( ));
            List<StatationStat> list1 = statationStatService.list (queryWrapper);
            List<DeptSubstationVO> children = deptSubstationVO.getChildren ( );
            List<DeptSubstationVO> collect = list1.stream ( ).map (statationStat -> {
                DeptSubstationVO deptSubstationVO1 = new DeptSubstationVO ( );
                deptSubstationVO1.setId (statationStat.getPowerId ( ));
                deptSubstationVO1.setPid (temp.getId ( ));
                deptSubstationVO1.setName (statationStat.getPowerName ( ));
                if (finalSubIds.contains (statationStat.getPowerId ( ))) {
                    deptSubstationVO1.setDisabled (true);
                }
                deptSubstationVO1.setFlag (true);
                return deptSubstationVO1;
            }).collect (Collectors.toList ( ));
            children.addAll (collect);

            return deptSubstationVO;
        }).collect (Collectors.toList ( ));

        /*
         遍历两次data来组装带有children关联性的对象，如果找到子级就删除result的数据

*/
        List<DeptSubstationVO> result = new ArrayList<> (deptSubstationVOList);

        for (DeptSubstationVO pv : deptSubstationVOList) {
            for (DeptSubstationVO pv2 : deptSubstationVOList) {

                /*如果本级id与数据的父id相同，就说明是子父级关系*/

                if (pv.getId ( ).equals (pv2.getPid ( ))) {
                    pv.getChildren ( ).add (pv2);
                    result.remove (pv2);
                }
            }
        }

        result = recursion (result.get (0), orgdid);

        return result;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public RSurveyCycleVO addPlanCycle(Integer cycleNum) {

        /**查出当前周期id**/
        QueryWrapper<RSurveyCyclePO> rSurveyCyclePOQueryWrapper = new QueryWrapper ( );
        rSurveyCyclePOQueryWrapper.le ("start_year", LocalDate.now ( ));
        rSurveyCyclePOQueryWrapper.ge ("end_year", LocalDate.now ( ));
        RSurveyCyclePO rSurveyCyclePO = rSurveyCycleMapper.selectOne (rSurveyCyclePOQueryWrapper);

        int insert = 0;
        Boolean flag = true;
        if (Objects.equals (rSurveyCyclePO, null)) {
            rSurveyCyclePO = new RSurveyCyclePO ( );
            LocalDate enddate = LocalDate.now ( ).plusYears (cycleNum);
            rSurveyCyclePO.setStartYear (LocalDate.now ( ));
            rSurveyCyclePO.setEndYear (enddate);
            rSurveyCyclePO.setSurveyCycle (cycleNum);
            insert = rSurveyCycleMapper.insert (rSurveyCyclePO);
        } else {
            flag = false;
        }
        RSurveyCycleVO rSurveyCycleVO = new RSurveyCycleVO ( );
        BeanUtils.copyProperties (rSurveyCyclePO, rSurveyCycleVO);
        rSurveyCycleVO.setFlag (flag);
        return rSurveyCycleVO;
    }

    public List<DeptSubstationVO> recursion(DeptSubstationVO result, String orgdid) {
        List<DeptSubstationVO> deptSubstationVOList = new ArrayList<> ( );
        if (Objects.equals (result.getId ( ), orgdid)) {
            deptSubstationVOList.add (result);
            return deptSubstationVOList;

        } else {
            for (DeptSubstationVO deptSubstationVO : result.getChildren ( )) {

                List<DeptSubstationVO> recursion = recursion (deptSubstationVO, orgdid);
                if(recursion.size ()>0){
                    return recursion;
                }

            }
        }
        return deptSubstationVOList;
    }

}
