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.PowerStationStatusData;
import com.jiayue.ipp.common.data.entity.an.ParsingInfo;
import com.jiayue.ipp.common.data.entity.an.ParsingRpInfo;
import com.jiayue.ipp.common.data.entity.an.ParsingUrl;
import com.jiayue.ipp.common.data.enums.FileTypeEnum;
import com.jiayue.ipp.idp.dto.FileParsingConfig;
import com.jiayue.ipp.idp.dto.ParsingConstant;
import com.jiayue.ipp.idp.mapper.an.ParsingRpInfoMapper;
import com.jiayue.ipp.idp.service.PowerStationStatusDataService;
import com.jiayue.ipp.idp.service.an.ParsingInterface;
import com.jiayue.ipp.idp.service.an.ParsingRpInfoService;
import com.jiayue.ipp.idp.util.FieldUtil;
import com.jiayue.ipp.idp.util.FileUtil;
import com.jiayue.ipp.idp.util.PUtil;
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.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

/**
 * 实际功率解析业务层实现类
 *
 * @author tl
 * @date 2022-05-11 18:07:03
 */
@Service
@Slf4j
@AllArgsConstructor
@Transactional
public class ParsingRpInfoServiceImpl extends ServiceImpl<ParsingRpInfoMapper, ParsingRpInfo> implements ParsingRpInfoService, ParsingInterface {

    private final PowerStationStatusDataService powerStationStatusDataService;

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

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

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

        try {
            List<ParsingRpInfo> parsingRpInfos = baseMapper.selectList(Wrappers.lambdaQuery(ParsingRpInfo.class).like(ParsingInfo::getStationCode, parsingUrl.getStationCode()));
            if (!parsingRpInfos.isEmpty()) {
                ParsingRpInfo parsingRpInfo = parsingRpInfos.get(0);

                //判断文件名是否符合配置
                if (file.getName().contains(parsingRpInfo.getFileName())) {

                    List<String> fileContent = FileUtil.getFileContent(file);
                    if (parsingRpInfo.getDataType().equals(FieldUtil.SINGLE)) {
                        BigDecimal bigDecimal;
                        if (parsingRpInfo.getAbleValue() != null) ;
                        bigDecimal = parsingValue(parsingRpInfo.getRealValue(), fileContent);


                        Long time = parsingForecastTime(parsingRpInfo.getTime(), fileContent);

                        if (time != 0l) {
                            PowerStationStatusData powerStationStatusData = new PowerStationStatusData();
                            powerStationStatusData.setStationCode(parsingUrl.getStationCode());
//                                powerStationStatusData.setAbleValue(bigDecimals.get(0));
                            powerStationStatusData.setRealValue(bigDecimal);
                            LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
                            powerStationStatusData.setTime(localDateTime);

                            powerStationStatusDataService.save(powerStationStatusData);

                            log.info("解析RP文件：{} 成功！ O(∩_∩)O", file.getName());
                            parsingStatus = FileTypeEnum.RP.name();
                        } else {
                            parsingStatus += "解析RP文件时间错误";
                            log.error("解析RP文件时间错误");
                        }


                    } else {
                        parsingStatus += "RP暂无单行解析方式";
                        log.info("RP暂无单行解析方式");
                    }
                }
            }
        } catch (Exception e) {
            parsingStatus += "解析实际功率数据失败";
            log.error("解析实际功率数据失败！ /(ㄒoㄒ)/~~", e);
        } finally {
            return parsingStatus;
        }

    }


    protected Long parsingForecastTime(String sign, List<String> fileContent) {
        Long forecastTime = 0l;
        try {
            FileParsingConfig config = FieldUtil.getConfig(sign);
            String s = fileContent.get(PUtil.noParseInt(config.getLineNumber()));
            int signIndex = s.indexOf(config.getDataSign());
            String result;
            if (signIndex > 0) {
                int startLength = config.getDataSign().length() + signIndex + 1;
                int length = config.getFormat().length();
                if (String.valueOf(s.charAt(startLength + 1)).equals("'")) {
                    startLength += 1;
                }
                result = s.substring(startLength, startLength + length);

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(config.getFormat());

                forecastTime = simpleDateFormat.parse(result).getTime();

                log.info("解析实际功率【时间】成功==》开始时间为：{}", result);
            } else {
                log.error("解析实际功率【时间】时公式标识不存在所在行");
            }
        } catch (RuntimeException e) {
            log.error("解析实际功率【时间】失败");
            e.printStackTrace();
        } finally {
            return forecastTime;
        }

    }


    /*
     * 解析配置格式规则：
     *   s=>>1=>>entity=
     *   s：单行标识
     *   1：取值在1行
     *   entity=：键标记标记
     *
     *   m=>>4-20=>>3
     *   m：多行标识
     *   4-20：取值在4-20行
     *   3：第三列
     * */
    protected List<BigDecimal> parsingFpValue(String sign, List<String> fileContent) {
        List<BigDecimal> fpValues = new ArrayList<>();
        try {
            FileParsingConfig config = FieldUtil.getConfig(sign);


            String[] lineNumber = config.getLineNumber().split("-");
            int startLine = PUtil.noParseInt(lineNumber[0]);
            int endLine = PUtil.noParseInt(lineNumber[1]);

            for (int i = startLine; i <= endLine; i++) {
                String[] strings = PUtil.splitLineWithSpace(fileContent.get(i));
                String result = strings[PUtil.noParseInt(config.getRowNumber())];

                fpValues.add(new BigDecimal(result));
            }

            log.info("解析短期【实际功率】成功！！！==》记录数：{}", fpValues.size());
        } catch (RuntimeException e) {
            log.error("解析短期【实际功率】失败");
            e.printStackTrace();
        } finally {
            return fpValues;
        }
    }

}
