package com.cpp.web.service.datafactory.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cpp.web.domain.datafactory.BaseParsing;
import com.cpp.web.domain.datafactory.ParsingNbq;
import com.cpp.web.domain.datafactory.dto.ParsingResultDto;
import com.cpp.web.domain.datafactory.enums.FileTypeEnum;
import com.cpp.web.domain.station.InverterInfo;
import com.cpp.web.domain.station.InverterStatusData;
import com.cpp.web.mapper.datafactory.ParsingNbqMapper;
import com.cpp.web.service.datafactory.ParsingInterface;
import com.cpp.web.service.datafactory.ParsingNbqService;
import com.cpp.web.service.station.InverterInfoService;
import com.cpp.web.service.station.InverterStatusDataService;
import com.cpp.web.utils.ParsingFieldUtil;
import com.cpp.web.utils.ParsingFileUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 逆变器解析业务层实现类
 *
 * @author tl
 * @date 2022-05-11 18:07:03
 */
@Service("nbqParsing")
@AllArgsConstructor
@Slf4j
@Transactional
public class ParsingNbqServiceImpl extends ServiceImpl<ParsingNbqMapper, ParsingNbq> implements ParsingNbqService, ParsingInterface {

    private final InverterStatusDataService inverterStatusDataService;

    private final InverterInfoService inverterInfoService;

    private List<ParsingNbq> parsingNbqs = new ArrayList<>();

    private List<InverterInfo> inverterInfos = new ArrayList<>();

    @Override
    public boolean save(BaseParsing parsingInfo) {
        return save((ParsingNbq) parsingInfo);
    }

    @Override
    public boolean deleteById(Long id) {
        return removeById(id);
    }

    @Override
    public ParsingResultDto parsing(File file, String stationCode) {
        ParsingResultDto parsingResultDto = new ParsingResultDto();
        parsingResultDto.setFileName(file.getName());
        parsingResultDto.setFileType(FileTypeEnum.nbq.name());

        try {

            //查询符合该场站的nbq配置信息
            List<ParsingNbq> parsingNbqInfos = selectByStationCode(stationCode);
            if (parsingNbqInfos.size() > 0) {

                //解析文件内容以行为单位的 List<String>
                List<String> fileContent = ParsingFileUtil.getFileContent(file);

                //查询对应该场站路径下的逆变器信息
                List<InverterInfo> inverterInfoList = inverterInfos.stream().filter(i->i.getStationCode().equals(stationCode)).collect(Collectors.toList());
                //因为有可能该场站有多种解析配置，例如多个逆变器数据情况，需要循环解析信息
                for (ParsingNbq parsingNbqInfo : parsingNbqInfos) {
                        //判断数据类型是单行还是多行
                        if (parsingNbqInfo.getDataType().equals(ParsingFieldUtil.SINGLE)) {
                            /**
                             * 逆变器和风机id  需要解析名称找出对应设备存入id
                             *
                             */
                            String nbqName = parsingName(parsingNbqInfo.getEquipmentName(), fileContent);
                            List<InverterInfo> filterInverterInfos = inverterInfoList.stream().filter(i -> i.getName().equals(nbqName)).collect(Collectors.toList());
                            if (filterInverterInfos.size() > 0) {
                                Long eqId = filterInverterInfos.get(0).getId();
                                Date time = parsingTime(parsingNbqInfo.getTime(), fileContent);
                                if (time != null) {
                                    InverterStatusData inverterStatusData = new InverterStatusData();
                                    inverterStatusData.setTime(time);

                                    inverterStatusData.setActivePower(parsingValue(parsingNbqInfo.getActivePower(), fileContent));
                                    inverterStatusData.setCumulativeGeneratedEnergy(parsingValue(parsingNbqInfo.getCumulativeGeneratedEnergy(), fileContent));
                                    inverterStatusData.setDayGridConnectedHours(parsingValue(parsingNbqInfo.getDayGridConnectedHours(), fileContent));
                                    inverterStatusData.setDayElectricQuantity(parsingValue(parsingNbqInfo.getDayElectricQuantity(), fileContent));
                                    inverterStatusData.setElectricalCurrent(parsingValue(parsingNbqInfo.getElectricalCurrent(), fileContent));
                                    inverterStatusData.setReactivePower(parsingValue(parsingNbqInfo.getReactivePower(), fileContent));
                                    inverterStatusData.setPowerFactor(parsingValue(parsingNbqInfo.getPowerFactor(), fileContent));
                                    inverterStatusData.setVoltage(parsingValue(parsingNbqInfo.getVoltage(), fileContent));
                                    inverterStatusData.setStatus(parsingStatus(parsingNbqInfo.getStatus(), fileContent));
                                    inverterStatusData.setEquipmentId(eqId);
                                    inverterStatusData.setStationCode(stationCode);
                                    inverterStatusDataService.save(inverterStatusData);
                                    log.info("解析NBQ文件：{} 成功！ O(∩_∩)O", file.getName());
                                    parsingResultDto.setStatus("success");
                                } else {
                                    parsingResultDto.setMessage("逆变器在本地无配置无法解析");
                                    log.error("nbq {} 在本地无配置无法解析", nbqName);
                                }
                            } else {
                                parsingResultDto.setStatus("0");
                                parsingResultDto.setMessage("解析逆变器文件时间错误");
                                log.error("解析NBQ文件时间错误");
                            }
                        } else {
                            parsingResultDto.setMessage("逆变器暂无多行解析方式");
                            log.error("nbq暂无多行解析方式");
                        }
                    
                }
            }
        } catch (Exception e) {
            parsingResultDto.setMessage("解析逆变器数据失败！");
            log.error("解析逆变器数据失败！ /(ㄒoㄒ)/~~", e);
        } finally {
            return parsingResultDto;
        }

    }

    @Override
    public boolean activationParsingConf() {
        this.parsingNbqs = baseMapper.selectList(null);
        this.inverterInfos = inverterInfoService.list();
        return false;
    }

    @Override
    public List selectByStationCode(String stationCode) {
        return parsingNbqs.stream().filter(p->p.getStationCode().equals(stationCode)).collect(Collectors.toList());
    }

}
