package com.energy.manage.service.service.datatransfer.impl;

import com.energy.manage.common.po.datatransfer.DataTransferHistoryPo;
import com.energy.manage.common.po.datatransfer.DataTransferPo;
import com.energy.manage.common.reponse.ConstVar;
import com.energy.manage.common.reponse.ResultResp;
import com.energy.manage.common.util.UUIDTools;
import com.energy.manage.service.domain.dto.datatransfer.DataTransferDto;
import com.energy.manage.service.domain.dto.datatransfer.DataTransferTypePathDto;
import com.energy.manage.service.domain.dto.datatransfer.EditDataTransferTypeDto;
import com.energy.manage.service.domain.dto.windfieldbatch.WindFileBatchPageDto;
import com.energy.manage.service.domain.vo.datatransfer.*;
import com.energy.manage.service.domain.vo.windfieldbatch.WindFieldBatchVo;
import com.energy.manage.service.mappers.datatransfer.DataTransferMapper;
import com.energy.manage.service.mappers.datatransferhistory.DataTransferHistoryMapper;
import com.energy.manage.service.mappers.datatransfertype.DataTransferTypeMapper;
import com.energy.manage.service.mappers.windfieldbatch.WindFieldBatchMapper;
import com.energy.manage.service.service.datatransfer.DataTransferService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据转换服务
 * @author chy
 * @date 2024/5/20 10:19
 * @desc
 */
@Slf4j
@Service
public class DataTransferServiceImpl implements DataTransferService {

    @Autowired
    private DataTransferMapper dataTransferMapper;

    @Autowired
    private DataTransferTypeMapper dataTransferTypeMapper;

    @Autowired
    private WindFieldBatchMapper windFieldBatchMapper;

    @Autowired
    private DataTransferHistoryMapper historyMapper;

    @Autowired
    private DataTransferTypeMapper typeMapper;

    @Value("${download.url}")
    private String downloadUrl;

    /**
     * 转换中状态
     */
    private final static Integer DATA_TRANSFERING_STATE = 0;

    /**
     * 获取没有进行数据转换的风场批次列表
     * @param roleId
     * @return
     */
    @Override
    public DataTransferQueryAndAddVo fieldBatchListForDataTransfer(Integer roleId) {
        DataTransferQueryAndAddVo queryAndAddVo = new DataTransferQueryAndAddVo();
        List<WindFieldBatchVo> batchCodeList = getDataTransferBatchList(roleId);
        if(CollectionUtils.isEmpty(batchCodeList)){
            return queryAndAddVo;
        }
        queryAndAddVo.setBatchCodeList(batchCodeList);
        List<DataTransferTypeVo> typeVos = typeMapper.selectAllInfo();
        queryAndAddVo.setDataTransferTypeVoList(typeVos);
        return queryAndAddVo;
    }

    /**
     * 查询转换数据组
     * @param dataTransferDto
     * @return
     */
    @Override
    public List<DataTransferBatchShortVo> queryDataTransferGroup(DataTransferDto dataTransferDto){
        PageHelper.startPage(dataTransferDto.getPageNum(), dataTransferDto.getPageSize());
        return dataTransferMapper.queryDataTransferGroup(dataTransferDto.getFieldName(),
                                                        dataTransferDto.getBatchName(),
                                                        dataTransferDto.getRoleId());
    }

    /**
     * 查询批次下数据转换信息
     * @param batchCode
     * @return
     */
    @Override
    public List<DataTransferVo> queryDataTransferByBatchCode(String batchCode){
        List<DataTransferVo> dataTransferVos = dataTransferMapper.selectDataTransferListByBatchCode(batchCode);
        if(CollectionUtils.isNotEmpty(dataTransferVos)){
            //设置转换类型名称
            dataTransferVos.parallelStream().forEach(item -> {
                item.setDownloadUrl(downloadUrl);
                item.setUniqueCode(UUIDTools.getShortUUIDLowCase());
            });
        }
        return dataTransferVos;
    }
    /**
     * 查询数据转换列表
     * @return
     */
    @Override
    public List<DataTransferVo> queryDataTransferList(DataTransferDto dataTransferDto) {
        List<DataTransferVo> dataTransferVos = dataTransferMapper.selectDataTransferListByCondition(dataTransferDto);
        if(CollectionUtils.isNotEmpty(dataTransferVos)){
            //获取所有转换类型
            List<DataTransferTypeVo> typeVos = dataTransferTypeMapper.selectAllInfo();
            if(CollectionUtils.isNotEmpty(typeVos)){
                //设置转换类型名称
                dataTransferVos.parallelStream().forEach(item -> {
                    item.setTransferTypeName(getDataTransferTypeName(typeVos,item.getTransferType()));
                    item.setDownloadUrl(downloadUrl);
                });
            }
        }
        return dataTransferVos;
    }

    /**
     * 新增数据转
     * @param dataTransferDto
     * @return
     */
    @Override
    public ResultResp addDataTransfer(DataTransferDto dataTransferDto) {
        log.info("新增转换开始，入参 dataTransferDto = {}",dataTransferDto.toString());
        List<DataTransferTypeVo> typeList = dataTransferTypeMapper.selectAllInfo();
        if(CollectionUtils.isEmpty(typeList)){
            log.error("风场批次batchCode = {} 新增转换失败，转换类型初始化数据是空导致！！",dataTransferDto.getBatchCode());
            return ResultResp.FAIL(ConstVar.DATA_TRANSFER_TYPE_EMPTY);
        }
        //设置风场编号
        dataTransferDto.setFieldCode(getFieldCode(dataTransferDto.getBatchCode()));
        List<DataTransferPo> dataTransferPos = new ArrayList<>();
        typeList.stream().forEach(item -> dataTransferPos.add(getDataTransferPo(dataTransferDto,item.getTransferType())));
        log.info("新增转换，批量添加的转换数据长度 = {}",dataTransferPos.size());
        return ResultResp.SUCCESS(dataTransferMapper.addDataTransferBatch(dataTransferPos));
    }


    /**
     * 数据转换（转换/重新转换）
     * @param editDto
     * @param updateBy
     * @return
     */
    @Override
    public ResultResp dataTransfer(EditDataTransferTypeDto editDto, Integer updateBy) {
//        //检查转换状态是否有正在转换的数据 有的话 不转换
//        if(checkTransferState()){
//            return ResultResp.FAIL(ConstVar.DATA_TRANSFERING);
//        }
        DataTransferPo po = dataTransferMapper.selectByBatchCodeAndDataTransferType(editDto.getBatchCode(),editDto.getDataTransferType());
        //如果数据库中存在的数据路径地址不为空的话 说明已经转换过了 需要重新转换 备份数据
        if(po != null && StringUtils.isNotBlank(po.getTransferAddr())){
            saveHistory(po);
        }
        //状态重新置换为转换中
        po.setTransferState(DATA_TRANSFERING_STATE);
        po.setTransferAddr(editDto.getDataTransferAddr());
        po.setTimeGranularity(editDto.getTimeGranularity());
        po.setUpdateBy(updateBy);
        po.setTransferProgress(BigDecimal.ZERO);
        return ResultResp.SUCCESS(dataTransferMapper.updateDataTransfer(po));
    }


    /**
     * 时间粒度编辑
     * @param batchCode
     * @param dataTransferType
     * @param timeGranularity
     * @param userId
     * @return
     */
    @Override
    public ResultResp editTimeGranularity(String batchCode, String dataTransferType, Integer timeGranularity, Integer userId) {
        DataTransferPo po = dataTransferMapper.selectByBatchCodeAndDataTransferType(batchCode,dataTransferType);
        if(po != null){
            po.setTimeGranularity(timeGranularity);
            po.setUpdateBy(userId);
            dataTransferMapper.updateDataTransfer(po);
        }
        return ResultResp.SUCCESS();
    }

    /**
     * 转换数据时间范围查询
     * @param batchCode
     * @param dataTransferType
     * @return
     */
    @Override
    public DataTransferDataTimeVo queryDataTime(String batchCode, String dataTransferType){
        return dataTransferMapper.selectDataTimeByBatchCodeAndType(batchCode,dataTransferType);
    }


    /**
     * 根据角色获取批次编号
     * @param roleId
     * @return
     */
    private List<WindFieldBatchVo> getDataTransferBatchList(Integer roleId) {
        //获取角色可以看到的风场批次信息
        List<WindFieldBatchVo>  batchVoList = windFieldBatchMapper.selectWindFieldBatch(new WindFileBatchPageDto().setRoleId(roleId));
        //获取已经进行过数据转换的批次号
        List<String> dataTransferBatchList = dataTransferMapper.selectAllWindFieldBtach(roleId);
        return batchVoList.parallelStream().filter(item -> !dataTransferBatchList.contains(item.getBatchCode())).collect(Collectors.toList());
    }

    /**
     * 根据类型获取类型名称
     * @param typeVos
     * @param dataTransferType
     * @return
     */
    private String getDataTransferTypeName(List<DataTransferTypeVo> typeVos,String dataTransferType){
        return typeVos.parallelStream().filter(typeVo -> typeVo.getTransferType().equals(dataTransferType))
                .map(DataTransferTypeVo::getTransferTypeName)
                .findFirst()
                .get();
    }


    /**
     * 获取数据转换po
     * @param dataTransferDto
     * @param dataTransferType
     * @return
     */
    private DataTransferPo getDataTransferPo(DataTransferDto dataTransferDto,String dataTransferType){
        DataTransferPo dataTransferPo = new DataTransferPo();
        dataTransferPo.setFieldCode(dataTransferDto.getFieldCode());
        dataTransferPo.setBatchCode(dataTransferDto.getBatchCode());
        dataTransferPo.setTransferType(dataTransferType);
        Integer userId = dataTransferDto.getUserId();
        dataTransferPo.setCreateBy(userId);
        dataTransferPo.setUpdateBy(userId);
        DataTransferTypePathDto pathDto = getTransferAddr(dataTransferDto,dataTransferType);
        if(pathDto != null && StringUtils.isNotBlank(pathDto.getTransferAddr())){
            dataTransferPo.setTransferAddr(pathDto.getTransferAddr());
            dataTransferPo.setTransferState(DATA_TRANSFERING_STATE);
        }
        if(pathDto != null && pathDto.getTimeGranularity() != null){
            dataTransferPo.setTimeGranularity(pathDto.getTimeGranularity());
        }
        return dataTransferPo;
    }

    /**
     * 根据类型获取转换文件地址
     * @param dataTransferDto
     * @param dataTransferType
     * @return
     */
    private DataTransferTypePathDto getTransferAddr(DataTransferDto dataTransferDto,String dataTransferType){
        List<DataTransferTypePathDto>  pathDtoList = dataTransferDto.getDataTransferTypePathDtoList();
        return pathDtoList.stream().filter(item -> item.getTransferType().equals(dataTransferType)).findFirst().orElse(null);
    }


    /**
     * 获取风场编号
     * @param batchCode
     * @return
     */
    private String getFieldCode(String batchCode){
        WindFieldBatchVo vo = windFieldBatchMapper.selectByBatchCode(batchCode);
        return vo.getFieldCode();
    }

    /**
     * 检查转换状态系统中是否有正在转换的数据
     * @return
     */
//    private boolean checkTransferState(){
//        return dataTransferMapper.selectCountByTransferState(DATA_TRANSFERING_STATE) > 0;
//    }

    /**
     * 备份转换数据
     * @param po
     */
    private void saveHistory(DataTransferPo po){
        DataTransferHistoryPo historyPo = new DataTransferHistoryPo();
        historyPo.setBatchCode(po.getBatchCode());
        historyPo.setEngineCount(po.getEngineCount());
        historyPo.setTransferAddr(po.getTransferAddr());
        historyPo.setTransferType(po.getTransferType());
        historyPo.setErrInfo(po.getErrInfo());
        historyPo.setTransferFinishTime(po.getTransferFinishTime());
        historyPo.setOptionBy(po.getUpdateBy());
        historyMapper.addDataTransferHistory(historyPo);
    }
}
