package com.jiayue.ipp.idp.service.impl.an;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiayue.ipp.common.data.entity.InverterInfo;
import com.jiayue.ipp.common.data.entity.InverterStatusData;
import com.jiayue.ipp.common.data.entity.an.ParsingInfo;
import com.jiayue.ipp.common.data.entity.an.ParsingNbqInfo;
import com.jiayue.ipp.common.data.entity.an.ParsingUrl;
import com.jiayue.ipp.common.data.enums.FileTypeEnum;
import com.jiayue.ipp.idp.dto.ParsingConstant;
import com.jiayue.ipp.idp.mapper.an.ParsingNbqInfoMapper;
import com.jiayue.ipp.idp.service.InverterInfoService;
import com.jiayue.ipp.idp.service.InverterStatusDataService;
import com.jiayue.ipp.idp.service.an.ParsingInterface;
import com.jiayue.ipp.idp.service.an.ParsingNbqInfoService;
import com.jiayue.ipp.idp.util.FieldUtil;
import com.jiayue.ipp.idp.util.FileUtil;
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.List;
import java.util.stream.Collectors;

/**
 * 逆变器解析业务层实现类
 *
 * @author tl
 * @date 2022-05-11 18:07:03
 */
@Service
@AllArgsConstructor
@Slf4j
@Transactional
public class ParsingNbqInfoServiceImpl extends ServiceImpl<ParsingNbqInfoMapper, ParsingNbqInfo> implements ParsingNbqInfoService, ParsingInterface {

    private final InverterStatusDataService inverterStatusDataService;

    private final InverterInfoService inverterInfoService;

    @Override
    public boolean save(ParsingInfo parsingInfo) {
        return save((ParsingNbqInfo) parsingInfo);
    }

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

    @Override
    public String parsing(File file, ParsingUrl ftpParsingUrl) {
        String parsingStatus = ParsingConstant.FAIL;

        try {

            //查询符合该场站的nbq配置信息
            List<ParsingNbqInfo> parsingNbqInfos = baseMapper.selectList(Wrappers.lambdaQuery(ParsingNbqInfo.class).like(ParsingInfo::getStationCode, ftpParsingUrl.getStationCode()));
            if (parsingNbqInfos.size() > 0) {

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

                //查询对应该场站路径下的逆变器信息
                List<InverterInfo> inverterInfoList = inverterInfoService.list(Wrappers.lambdaQuery(InverterInfo.class).eq(InverterInfo::getStationCode, ftpParsingUrl.getStationCode()));

                //因为有可能该场站有多种解析配置，例如多个逆变器数据情况，需要循环解析信息
                for (ParsingNbqInfo parsingNbqInfo : parsingNbqInfos) {
                    //判断文件名是否符合配置
                    if (file.getName().indexOf(parsingNbqInfo.getFileName()) >= 0) {

                        //判断数据类型是单行还是多行
                        if (parsingNbqInfo.getDataType().equals(FieldUtil.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 time = parsingTime(parsingNbqInfo.getTime(), fileContent);
                                if (time != 0l) {
                                    InverterStatusData inverterStatusData = new InverterStatusData();
                                    LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
                                    inverterStatusData.setTime(localDateTime);

                                    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(filterInverterInfos.get(0).getEquipmentNo());
                                    inverterStatusData.setStationCode(ftpParsingUrl.getStationCode());
                                    inverterStatusDataService.save(inverterStatusData);
                                    log.info("解析NBQ文件：{} 成功！ O(∩_∩)O", file.getName());
                                    parsingStatus = FileTypeEnum.NBQ.name();
                                } else {
                                    parsingStatus += "nbq {" + nbqName + "} 在本地无配置无法解析";
                                    log.info("nbq {} 在本地无配置无法解析", nbqName);
                                }
                            } else {
                                parsingStatus += "解析NBQ文件时间错误";
                                log.error("解析NBQ文件时间错误");
                            }
                        } else {
                            parsingStatus += "nbq暂无多行解析方式";
                            log.info("nbq暂无多行解析方式");
                        }
                    }
                }
            }
        } catch (Exception e) {
            parsingStatus += "解析逆变器数据失败";
            log.error("解析逆变器数据失败！ /(ㄒoㄒ)/~~", e);
        } finally {
            return parsingStatus;
        }

    }

}
