package com.yeejoin.amos.api.householdapi.face.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.api.householdapi.Utils.KsolarRequestUtil;
import com.yeejoin.amos.api.householdapi.constant.GoLangConstant;
import com.yeejoin.amos.api.householdapi.constant.KSolarConstant;
import com.yeejoin.amos.api.householdapi.face.dto.AlarmDto;
import com.yeejoin.amos.api.householdapi.face.dto.CollectorDetailDto;
import com.yeejoin.amos.api.householdapi.face.dto.KsolarAlarmDto;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.hygf.JpCollector;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.hygf.JpInverter;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.hygf.JpInverterElectricity;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.hygf.JpStation;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.*;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.KsolarStationCollectList;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.hygf.JpCollectorMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.hygf.JpInverterElectricityMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.hygf.JpInverterMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.hygf.JpStationMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.*;
import com.yeejoin.amos.api.householdapi.face.service.KSolarDataAcquisitionService;
import com.yeejoin.amos.openapi.enums.PVProducerInfoEnum;
import fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author DELL
 */
@Service
public class KsolarDataAcquisitionServiceImpl implements KSolarDataAcquisitionService {



    @Autowired
    KsolarRequestUtil kSolarRequestUtil;

    @Autowired
    KsolarStationMapper kSolarStationMapper;

    @Autowired
    private JpStationMapper jpStationMapper;

    @Autowired
    private HYGFJPStationPowerHistoryMapper hygfjpStationPowerHistoryMapper;

    @Autowired
    private HYGFJPInverterHistoryMapper hygfjpInverterHistoryMapper;

    @Autowired
    private HYGFJPCollectorHistoryMapper hygfjpCollectorHistoryMapper;

    @Autowired
    private HYGFJPInverterWarnMapper hygfjpInverterWarnMapper;

    @Autowired
    private HYGFJPInverterElecHistoryMapper hygfjpInverterElecHistoryMapper;

    @Autowired
    private HYGFJPDayPowerMapper hygfjpDayPowerMapper;

    @Autowired
    private KsolarStationDetailsMapper ksolarStationDetailsMapper;

    @Autowired
    private KsolarStationEarnMapper ksolarStationEarnMapper;

    @Autowired
    private KsolarStationCollectListMapper ksolarStationCollectListMapper;

    @Autowired
    private JpCollectorMapper jpCollectorMapper;

    @Autowired
    private JpInverterMapper jpInverterMapper;
    //监盘逆变器电量mapper
    @Autowired
    private JpInverterElectricityMapper jpInverterElectricityMapper;

    @Scheduled(cron = "${dataRequstScheduled.keshida}")
    @Override
    public void stationList() {
        HashMap<String, Object> requestInfo = new HashMap<>();
        String requestParaminfo = JSON.toJSONString(requestInfo);
        List<KsolarStationList> kSolarStationListList = kSolarRequestUtil.getResPonse(
                KSolarConstant.stationListUrl,
                KSolarConstant.requestGET,
                requestParaminfo,
                KSolarConstant.resovle_rows,
                KsolarStationList.class);
        for (KsolarStationList kSolarStation : kSolarStationListList) {
            kSolarStation.setCreatedTime(System.currentTimeMillis());
            kSolarStationMapper.insert(kSolarStation);
        }
    }

    @Scheduled(cron = "${dataRequstScheduled.keshida}")
    @Override
    public void stationDetail() {
        List<String> stationIds = kSolarStationMapper.getStationIds();
        String today = DateUtil.today();
        String hour = new Date().getHours() + ":00";

        for (String stationId : stationIds) {
            LambdaQueryWrapper<KsolarStationList> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(KsolarStationList::getStationId, stationId);
            wrapper.orderByDesc(KsolarStationList::getCreatedTime);
            List<KsolarStationList> ksolarStationLists = kSolarStationMapper.selectList(wrapper);
            if (!CollectionUtils.isEmpty(ksolarStationLists)) {
                KsolarStationList ksolarStation = ksolarStationLists.get(0);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                HashMap<String, Object> requestInfo = new HashMap<>(1);
                String requestParaminfo = JSON.toJSONString(requestInfo);
                String url = KSolarConstant.stationInfoByIdUrl + "?stationId=" + ksolarStation.getStationId();
                // 获取电站详情
                List<KsolarStationDetails> ksolarStationDetailsList = kSolarRequestUtil.getResPonse(
                        url,
                        KSolarConstant.requestPOST,
                        requestParaminfo,
                        KSolarConstant.resovle_data,
                        KsolarStationDetails.class);
                // 获取单个电站的发电量和收益
                KsolarStationEarn stationEarn = getStationEarn(ksolarStation.getStationId());

                // 获取单个电站月收益
                Map<String, Double> monthEarn = getStationMonthEarn(ksolarStation.getStationId(), "month");

                // 获取单个电站年收益
                Map<String, Double> yearEarn = getStationMonthEarn(ksolarStation.getStationId(), "year");

                for (KsolarStationDetails ksolarStationDetail : ksolarStationDetailsList) {

                    ksolarStationDetail.setCreatedTime(System.currentTimeMillis());
                    JpStation jpStation = jpStationMapper.selectOne(new QueryWrapper<JpStation>().
                            eq("third_code", PVProducerInfoEnum.KSOLAR.getCode()).
                            eq("third_station_id", ksolarStation.getStationId()));
                    // 给户用光伏存储的数据赋值
                    if (ObjectUtils.isEmpty(jpStation)) {
                        jpStation = new JpStation();
                    }
                    jpStation.setThirdStationId(ksolarStation.getStationId());
                    jpStation.setCapacity(ksolarStationDetail.getInstallCapacity());
                    jpStation.setName(ksolarStationDetail.getStationName());
                    jpStation.setPrice(ksolarStationDetail.getElecPrice());
                    jpStation.setAddress(ksolarStationDetail.getStationAddressDetail());
                    jpStation.setLongitude(ksolarStationDetail.getLongitude());
                    jpStation.setOnGridType("自发自用");//客户确认
                    jpStation.setRatedPower(100D);//客户确认
                    jpStation.setLatitude(ksolarStationDetail.getLatitude());
                    jpStation.setThirdCode(PVProducerInfoEnum.KSOLAR.getCode());
                    // 业主姓名
                    jpStation.setUserName(ksolarStation.getUserName());
                    jpStation.setState(KSolarConstant.collectStaus.get(String.valueOf(ksolarStation.getStatus())));
                    jpStation.setRealTimePower(ksolarStation.getPowerInter());

                    jpStation.setDayGenerate(ksolarStation.getDayGeneration());
                    jpStation.setAccumulatedPower(ksolarStation.getTotalGeneration());
                    jpStation.setArea(ksolarStation.getAddress());
                    // 日收益
                    jpStation.setDayIncome(stationEarn.getDayEarn());
                    // 月发电量
                    jpStation.setMonthGenerate(stationEarn.getMonthGeneration());
                    // 年发电量
                    jpStation.setYearGenerate(stationEarn.getYearGeneration());

                    // 月收益
                    jpStation.setMonthIncome(monthEarn.get("monthEarn"));
                    // 年收益
                    jpStation.setYearIncome(yearEarn.get("yearEarn"));
                    // 累计收益
                    jpStation.setCumulativeIncome(stationEarn.getTotalEarn());

                    // 并网类型
                    //                jpStation.setOnGridType(GoLangConstant.intoNetWorkStatus.get(String.valueOf(golangStationDetail.getStationtypenew())));
                    //                // 邮箱
                    //                jpStation.setEmail(golangStationDetail.getUseremail());
                    //                // 并网时间
                    //                jpStation.setOnGridTime(new Date(golangStationDetail.getFispowertime()));
                    //                // 接入平台时间
                    //                jpStation.setAccessTime(new Date(golangStationDetail.getFisgeneratetime()));
                    //                // 创建时间
                    //                jpStation.setCreateTime(new Date(golangStationDetail.getCreatedate()));
                    //                // 额定功率
                    //                jpStation.setRatedPower(Double.valueOf(golangStationDetail.getInverterpower()));
                    // 第三方电站id
                    //                jpStation.setThirdStationId(String.valueOf(golangStationDetail.getId()));
                    // 第三方厂商标识
                    //                jpStation.setThirdCode(PVProducerInfoEnum.JLY.getCode());
                    // 业主电话
                    //                jpStation.setUserPhone(String.valueOf(golangStationDetail.getUsermobile()));
                    // 电站联系人
                    //                jpStation.setStationContact(String.valueOf(golangStationDetail.getMobile()).toLowerCase().replace("null", ""));
                    // 组件数量
                    //                jpStation.setModuleCount(ObjectUtils.isEmpty(Math.toIntExact(golangStationDetail.getModule()))?0:Math.toIntExact(golangStationDetail.getModule()));

                    if (!ObjectUtils.isEmpty(jpStation.getSequenceNbr())) {
                        jpStationMapper.updateById(jpStation);
                    } else {
                        jpStationMapper.insert(jpStation);
                    }

                    HYGFJPStationPowerHistory hygfjpStationPowerHistory = new HYGFJPStationPowerHistory();
                    hygfjpStationPowerHistory.setCreatedTime(System.currentTimeMillis());
                    hygfjpStationPowerHistory.setThirdStationId(jpStation.getThirdStationId());
                    hygfjpStationPowerHistory.setPower(ksolarStation.getPowerInter());
                    hygfjpStationPowerHistory.setThirdCode(jpStation.getThirdCode());
                    hygfjpStationPowerHistory.setTime(System.currentTimeMillis());
                    hygfjpStationPowerHistoryMapper.insert(hygfjpStationPowerHistory);
                    HYGFJPDayPower hygfjpDayPower = hygfjpDayPowerMapper.selectOne(
                            new QueryWrapper<HYGFJPDayPower>().
                                    eq("tation_id", ksolarStation.getStationId()).
                                    eq("year_month_day", today).
                                    eq("hour", hour)
                    );
                    if (ObjectUtils.isEmpty(hygfjpDayPower)) {
                        hygfjpDayPower = new HYGFJPDayPower();
                    }
                    hygfjpDayPower.setTationId(ksolarStation.getStationId());
                    hygfjpDayPower.setHour(hour);
                    hygfjpDayPower.setYearMonthDay(today);
                    hygfjpDayPower.setPower(ksolarStation.getPowerInter());
                    if (ObjectUtils.isEmpty(hygfjpDayPower.getCreatedTime())) {
                        hygfjpDayPower.setCreatedTime(System.currentTimeMillis());
                        hygfjpDayPowerMapper.insert(hygfjpDayPower);
                    } else {
                        hygfjpDayPowerMapper.insert(hygfjpDayPower);
                    }
                    ksolarStationDetail.setCreatedTime(System.currentTimeMillis());

                    ksolarStationDetailsMapper.insert(ksolarStationDetail);
                }
            }
        }
    }

    /**
     * 获取单个站的发电量
     *
     * @param stationId 站id
     * @return 发电量实体
     */
    private KsolarStationEarn getStationEarn(String stationId) {
        KsolarStationEarn ksolarStationEarn = new KsolarStationEarn();
        // 获取单个电站的发电量和收益
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        HashMap<String, Object> requestInfo = new HashMap<>(1);
        String requestParaminfo = JSON.toJSONString(requestInfo);
        String url = KSolarConstant.stationEarnUrl + "?stationId=" + stationId;
        List<KsolarStationEarn> ksolarStationEarns = kSolarRequestUtil.getResPonse(
                url,
                KSolarConstant.requestGET,
                requestParaminfo,
                KSolarConstant.resovle_data,
                KsolarStationEarn.class);

        if (!CollectionUtils.isEmpty(ksolarStationEarns)) {
            ksolarStationEarn = ksolarStationEarns.get(0);
            ksolarStationEarn.setCreatedTime(System.currentTimeMillis());
            ksolarStationEarnMapper.insert(ksolarStationEarn);
        }
        return ksolarStationEarn;
    }

    Map<String, Double> getStationMonthEarn(String stationId, String type) {
        Map<String, Double> map = new HashMap<>(1);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        HashMap<String, Object> requestInfo = new HashMap<>(1);
        String requestParaminfo = JSON.toJSONString(requestInfo);
        // 获取当前日期
        Date currentDate = new Date();
        // 创建SimpleDateFormat实例，指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        // 格式化日期为字符串
        String formattedDate = sdf.format(currentDate);
        // 从格式化后的字符串中提取年份和月份
        String year = formattedDate.substring(0, 4);
        String month = formattedDate;
        String attribId = "201";
        String stime = month;
        if ("year".equals(type)) {
            attribId = "202";
            stime = year;
        }
        String url = KSolarConstant.stationEarnChartUrl + "?stationId=" + stationId + "&attribId=" + attribId + "&stime=" + stime;
        List<KsolarStationEarnChart> ksolarStationEarnCharts = kSolarRequestUtil.getResPonse(
                url,
                KSolarConstant.requestGET,
                requestParaminfo,
                KSolarConstant.resovle_arr,
                KsolarStationEarnChart.class);
        double earnValues = 0;
        if (!CollectionUtils.isEmpty(ksolarStationEarnCharts)) {
            earnValues += ksolarStationEarnCharts.stream().mapToDouble(ksolarStationEarnChart -> Double.parseDouble(ksolarStationEarnChart.getEarnValue())).sum();
        }
        if ("year".equals(type)) {
            map.put("yearEarn", earnValues);
        } else {
            map.put("monthEarn", earnValues);
        }
        return map;
    }

    @Scheduled(cron = "${dataRequstScheduled.keshida}")
    @Override
    public void collectorList() {
        List<String> stationIds = kSolarStationMapper.getStationIds();
        for (String stationId : stationIds) {
            LambdaQueryWrapper<KsolarStationList> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(KsolarStationList::getStationId, stationId);
            wrapper.orderByDesc(KsolarStationList::getCreatedTime);
            List<KsolarStationList> ksolarStationLists = kSolarStationMapper.selectList(wrapper);
            if (!CollectionUtils.isEmpty(ksolarStationLists)) {
                KsolarStationList ksolarStationList = ksolarStationLists.get(0);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                HashMap<String, Object> requestInfo = new HashMap<>(1);
                String requestParaminfo = JSON.toJSONString(requestInfo);
                String url = KSolarConstant.stationCollectListUrl + "?stationId=" + ksolarStationList.getStationId() + "&pageNumber=1&pageSize=200";
                List<KsolarStationCollectList> result = kSolarRequestUtil.getResPonse(
                        url,
                        KSolarConstant.requestGET,
                        requestParaminfo,
                        KSolarConstant.resovle_rows,
                        KsolarStationCollectList.class
                );
                for (KsolarStationCollectList ksolarStationCollectList : result) {

                    ksolarStationCollectList.setCreatedTime(System.currentTimeMillis());
                    ksolarStationCollectList.setThirdStationId(ksolarStationList.getStationId());
                    ksolarStationCollectListMapper.insert(ksolarStationCollectList);

                    JpCollector jpCollector = jpCollectorMapper.selectOne(new QueryWrapper<JpCollector>().
                            eq("third_station_id", ksolarStationCollectList.getThirdStationId()).
                            eq("sn_code", ksolarStationCollectList.getCollectId()).
                            eq("third_code", PVProducerInfoEnum.KSOLAR.getCode()));
                    if (ObjectUtils.isEmpty(jpCollector)) {
                        jpCollector = new JpCollector();
                    }
//                //出场日期
//                jpCollector.setDischargeDate(new Date(collectorDetailDto.getFactoryTime()));
//                //生产日期
//                jpCollector.setProductDate(new Date(collectorDetailDto.getFactoryTime()));
//                //数据上传间隔
//                jpCollector.setDataPeriod(collectorDetailDto.getDataUploadCycle());
//                //本次上电时间
//                jpCollector.setThisWorkTime(new DateTime(collectorDetailDto.getCurrentWorkingTime()));
//                //累计工作时间
//                jpCollector.setTotalWorkTime(new DateTime(collectorDetailDto.getTotalWorkingTime()));

                    // sn编码
                    jpCollector.setSnCode(ksolarStationCollectList.getCollectId());
                    // 更新时间
                    jpCollector.setUpdateTime(new Date());
                    // 第三方电站id
                    jpCollector.setThirdStationId(ksolarStationCollectList.getThirdStationId());
                    // 第三方厂商标识
                    jpCollector.setThirdCode(PVProducerInfoEnum.KSOLAR.getCode());
                    //第三方厂商标识
                    jpCollector.setState(KSolarConstant.collectStaus.get(ksolarStationCollectList.getStatus()));
                    jpCollector.setStationName(ksolarStationCollectList.getStationName());
                    jpCollector.setAddr(ksolarStationCollectList.getAddress());
                    jpCollector.setName(ksolarStationCollectList.getCollectName());
                    jpCollector.setVersion(ksolarStationCollectList.getCollectVersion());
                    jpCollector.setType(ksolarStationCollectList.getDeviceModel());
                    if (ObjectUtils.isEmpty(jpCollector.getSequenceNbr())) {
                        jpCollectorMapper.insert(jpCollector);
                    } else {
                        jpCollectorMapper.updateById(jpCollector);
                    }


                    HYGFJPCollectorHistory hygfjpCollectorHistory = new HYGFJPCollectorHistory();
                    hygfjpCollectorHistory.setTime(System.currentTimeMillis());
                    hygfjpCollectorHistory.setCreatedTime(System.currentTimeMillis());
                    hygfjpCollectorHistory.setSnCode(ksolarStationCollectList.getCollectId());
                    hygfjpCollectorHistory.setSignalStrength(ksolarStationCollectList.getSignal());
                    hygfjpCollectorHistory.setThirdStationId(ksolarStationCollectList.getThirdStationId());
                    hygfjpCollectorHistory.setThirdCode(PVProducerInfoEnum.KSOLAR.getCode());
                    hygfjpCollectorHistoryMapper.insert(hygfjpCollectorHistory);
                }
            }
        }
    }

    @Scheduled(cron = "${dataRequstScheduled.keshida}")
    @Override
    public void collectorDetail() {
        List<String> collectIds = ksolarStationCollectListMapper.getCollectIds();
        if (!CollectionUtils.isEmpty(collectIds)) {
            collectIds.forEach(collectId -> {
                LambdaQueryWrapper<KsolarStationCollectList> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(KsolarStationCollectList::getCollectId, collectId);
                wrapper.orderByDesc(KsolarStationCollectList::getCreatedTime);
                List<KsolarStationCollectList> ksolarStationCollectLists = ksolarStationCollectListMapper.selectList(wrapper);
                if (!CollectionUtils.isEmpty(ksolarStationCollectLists)) {
                    KsolarStationCollectList ksolarStationCollectList = ksolarStationCollectLists.get(0);
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    HashMap<String, Object> requestInfo = new HashMap<>(1);
                    String requestParaminfo = JSON.toJSONString(requestInfo);
                    String url = KSolarConstant.stationCollectDataUrl + "?collectId=" + ksolarStationCollectList.getCollectId();
                    List<KsolarStationCollectData> result = kSolarRequestUtil.getResPonse(
                            url,
                            KSolarConstant.requestGET,
                            requestParaminfo,
                            KSolarConstant.resovle_data,
                            KsolarStationCollectData.class
                    );

                    if (!CollectionUtils.isEmpty(result)) {
                        result.forEach(ksolarStationCollectData -> {
                            JpInverter jpInverter = jpInverterMapper.selectOne(new QueryWrapper<JpInverter>().
                                    eq("third_station_id", ksolarStationCollectList.getThirdStationId()).
                                    eq("third_code", PVProducerInfoEnum.KSOLAR.getCode()).
                                    eq("sn_code", ksolarStationCollectData.getInverterId()));
                            if (ObjectUtils.isEmpty(jpInverter)) {
                                jpInverter = new JpInverter();
                            }

                            // 品牌
//                        jpInverter.setBrand(inverterDetailDto.getName());
                            // 国标
//                        jpInverter.setNationalStandard(inverterDetailDto.getNationalStandards());
                            // 满发小时数
//                        jpInverter.setGenerationHours(String.valueOf(inverterDetailDto.getFullHour()));
                            // 装机容量
//                        jpInverter.setCapacity(inverterDetailDto.getPower().intValue());

                            jpInverter.setSnCode(ksolarStationCollectData.getInverterId());
                            jpInverter.setId(ksolarStationCollectData.getInverterId());
                            jpInverter.setState(KSolarConstant.stationStaus.get(ksolarStationCollectData.getStatus()));
                            jpInverter.setCollectorId(ksolarStationCollectList.getCollectId());
                            jpInverter.setCollectorSnCode(ksolarStationCollectList.getCollectId());
                            jpInverter.setUpdateTime(new Date());

                            jpInverter.setCurrentPower(ksolarStationCollectData.getPowerApparent());
                            jpInverter.setDayPowerGeneration(ksolarStationCollectData.getDayGeneration());
                            jpInverter.setMonthPowerGeneration(ksolarStationCollectData.getMonthGeneration());
                            jpInverter.setYearPowerGeneration(ksolarStationCollectData.getYearGeneration());
                            jpInverter.setTotalPowerGeneration(ksolarStationCollectData.getTotalGeneration());
                            jpInverter.setModel(ksolarStationCollectData.getDeviceModel());
                            jpInverter.setVersion(ksolarStationCollectData.getVersion());
                            jpInverter.setThirdStationId(ksolarStationCollectList.getThirdStationId());
                            jpInverter.setThirdCode(PVProducerInfoEnum.KSOLAR.getCode());
                            jpInverter.setStationName(ksolarStationCollectList.getStationName());
                            jpInverter.setAddr(ksolarStationCollectList.getAddress());
                            if (!ObjectUtils.isEmpty(jpInverter.getSequenceNbr())) {
                                jpInverterMapper.updateById(jpInverter);
                            } else {
                                jpInverterMapper.insert(jpInverter);
                            }


                            String jsonString = JSON.toJSONString(ksolarStationCollectData);
                            Map<String, Object> hanlderResult = JSON.parseObject(jsonString, Map.class);

                            for (int k1 = 1; k1 < 13; k1++) {
                                JpInverterElectricity jpInverterElectricity = jpInverterElectricityMapper.selectOne(new QueryWrapper<JpInverterElectricity>().
                                        eq("sn_code", ksolarStationCollectData.getInverterId()).
                                        eq("type", "直流").
                                        eq("name", "PV" + k1)
                                );
                                if (ObjectUtils.isEmpty(jpInverterElectricity)) {
                                    jpInverterElectricity = new JpInverterElectricity();
                                }
                                jpInverterElectricity.setInverterId(ksolarStationCollectData.getInverterId());
                                jpInverterElectricity.setSnCode(ksolarStationCollectData.getInverterId());
                                jpInverterElectricity.setThirdCode(PVProducerInfoEnum.KSOLAR.getCode());
                                jpInverterElectricity.setThirdStationId(ksolarStationCollectList.getThirdStationId());
                                jpInverterElectricity.setType("直流");
                                jpInverterElectricity.setName("PV" + k1);
                                jpInverterElectricity.setVoltage(Double.valueOf(hanlderResult.get("voltagePv" + k1).toString()));
                                jpInverterElectricity.setCurrent(Double.valueOf(hanlderResult.get("currentPv" + k1).toString()));
                                jpInverterElectricity.setPower(Double.valueOf(hanlderResult.get("powerPv" + k1).toString()));
                                if (ObjectUtils.isEmpty(jpInverterElectricity.getSequenceNbr())) {
                                    jpInverterElectricityMapper.insert(jpInverterElectricity);
                                } else {
                                    jpInverterElectricityMapper.updateById(jpInverterElectricity);
                                }
                            }

                            JpInverterElectricity jpInverterElectricityR = jpInverterElectricityMapper.selectOne(new QueryWrapper<JpInverterElectricity>().
                                    eq("sn_code", ksolarStationCollectData.getInverterId()).
                                    eq("type", "交流").
                                    eq("name", "RS")
                            );
                            if (ObjectUtils.isEmpty(jpInverterElectricityR)) {
                                jpInverterElectricityR = new JpInverterElectricity();
                            }
                            jpInverterElectricityR.setInverterId(ksolarStationCollectData.getInverterId());
                            jpInverterElectricityR.setSnCode(ksolarStationCollectData.getInverterId());
                            jpInverterElectricityR.setThirdCode(PVProducerInfoEnum.KSOLAR.getCode());
                            jpInverterElectricityR.setThirdStationId(ksolarStationCollectList.getThirdStationId());
                            jpInverterElectricityR.setType("交流");
                            jpInverterElectricityR.setName("RS");
                            jpInverterElectricityR.setVoltage(ksolarStationCollectData.getVoltageRs());
                            jpInverterElectricityR.setCurrent(ksolarStationCollectData.getCurrentR());
                            if (ObjectUtils.isEmpty(jpInverterElectricityR.getSequenceNbr())) {
                                jpInverterElectricityMapper.insert(jpInverterElectricityR);
                            } else {
                                jpInverterElectricityMapper.updateById(jpInverterElectricityR);
                            }

                            JpInverterElectricity jpInverterElectricityS = jpInverterElectricityMapper.selectOne(new QueryWrapper<JpInverterElectricity>().
                                    eq("sn_code", ksolarStationCollectData.getInverterId()).
                                    eq("type", "交流").
                                    eq("name", "ST")
                            );
                            if (ObjectUtils.isEmpty(jpInverterElectricityS)) {
                                jpInverterElectricityS = new JpInverterElectricity();
                            }
                            jpInverterElectricityS.setInverterId(ksolarStationCollectData.getInverterId());
                            jpInverterElectricityS.setSnCode(ksolarStationCollectData.getInverterId());
                            jpInverterElectricityS.setThirdCode(PVProducerInfoEnum.KSOLAR.getCode());
                            jpInverterElectricityS.setThirdStationId(ksolarStationCollectList.getThirdStationId());
                            jpInverterElectricityS.setType("交流");
                            jpInverterElectricityS.setName("ST");
                            jpInverterElectricityS.setVoltage(ksolarStationCollectData.getVoltageSt());
                            jpInverterElectricityS.setCurrent(ksolarStationCollectData.getCurrents());
                            if (ObjectUtils.isEmpty(jpInverterElectricityS.getSequenceNbr())) {
                                jpInverterElectricityMapper.insert(jpInverterElectricityS);
                            } else {
                                jpInverterElectricityMapper.updateById(jpInverterElectricityS);
                            }


                            JpInverterElectricity jpInverterElectricityT = jpInverterElectricityMapper.selectOne(new QueryWrapper<JpInverterElectricity>().
                                    eq("sn_code", ksolarStationCollectData.getInverterId()).
                                    eq("type", "交流").
                                    eq("name", "TR")
                            );
                            if (ObjectUtils.isEmpty(jpInverterElectricityT)) {
                                jpInverterElectricityT = new JpInverterElectricity();
                            }
                            jpInverterElectricityT.setInverterId(ksolarStationCollectData.getInverterId());
                            jpInverterElectricityT.setSnCode(ksolarStationCollectData.getInverterId());
                            jpInverterElectricityT.setThirdCode(PVProducerInfoEnum.KSOLAR.getCode());
                            jpInverterElectricityT.setThirdStationId(ksolarStationCollectList.getThirdStationId());
                            jpInverterElectricityT.setType("交流");
                            jpInverterElectricityT.setName("TR");
                            jpInverterElectricityT.setVoltage(ksolarStationCollectData.getVoltageTr());
                            jpInverterElectricityT.setCurrent(ksolarStationCollectData.getCurrentT());
                            if (ObjectUtils.isEmpty(jpInverterElectricityT.getSequenceNbr())) {
                                jpInverterElectricityMapper.insert(jpInverterElectricityT);
                            } else {
                                jpInverterElectricityMapper.updateById(jpInverterElectricityT);
                            }

//
                            HYGFJPInverterElecHistory hygfjpInverterElecHistory = new HYGFJPInverterElecHistory();
                            hygfjpInverterElecHistory.setThirdStationId(ksolarStationCollectList.getThirdStationId());
                            hygfjpInverterElecHistory.setCreatedTime(System.currentTimeMillis());
                            hygfjpInverterElecHistory.setSnCode(ksolarStationCollectData.getInverterId());

                            hygfjpInverterElecHistory.setUAcCurrent(ksolarStationCollectData.getCurrentR());
                            hygfjpInverterElecHistory.setVAcCurrent(ksolarStationCollectData.getCurrents());
                            hygfjpInverterElecHistory.setWAcCurrent(ksolarStationCollectData.getCurrentT());
                            hygfjpInverterElecHistory.setUAcVoltage(ksolarStationCollectData.getVoltageRs());
                            hygfjpInverterElecHistory.setVAcVoltage(ksolarStationCollectData.getVoltageSt());
                            hygfjpInverterElecHistory.setWAcVoltage(ksolarStationCollectData.getVoltageTr());
                            hygfjpInverterElecHistory.setThirdCode(PVProducerInfoEnum.KSOLAR.getCode());
                            hygfjpInverterElecHistory.setTime(System.currentTimeMillis());
                            hygfjpInverterElecHistoryMapper.insert(hygfjpInverterElecHistory);

                            // 逆变器历史
                            String today = DateUtil.today();
                            HYGFJPInverterHistory hygfjpInverterHistory = hygfjpInverterHistoryMapper.selectOne(
                                    new QueryWrapper<HYGFJPInverterHistory>().eq("sn_code", ksolarStationCollectData.getInverterId()).eq("date", today));
                            if (ObjectUtils.isEmpty(hygfjpInverterHistory)) {
                                hygfjpInverterHistory = new HYGFJPInverterHistory();
                            }

                            // 满发小时数
//                        hygfjpInverterHistory.setGenerationHours(inverterDetailDto.getFullHour());
                            hygfjpInverterHistory.setDate(today);
                            hygfjpInverterHistory.setThirdStationId(ksolarStationCollectList.getThirdStationId());
                            hygfjpInverterHistory.setInverterId(ksolarStationCollectData.getInverterId());
                            hygfjpInverterHistory.setSnCode(ksolarStationCollectData.getInverterId());
                            hygfjpInverterHistory.setThirdCode(PVProducerInfoEnum.KSOLAR.getCode());
                            hygfjpInverterHistory.setPowerGeneration(ksolarStationCollectData.getTotalGeneration());
                            if (ObjectUtils.isEmpty(hygfjpInverterHistory.getCreatedTime())) {
                                hygfjpInverterHistory.setCreatedTime(System.currentTimeMillis());
                                hygfjpInverterHistoryMapper.insert(hygfjpInverterHistory);
                            } else {
                                hygfjpInverterHistoryMapper.insert(hygfjpInverterHistory);
                            }
                        });
                    }
                }
            });
        }
        // 实时告警
        try {
            inverAlramInfo();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void inverterList() {

    }

    @Override
    public void inverterDetail() {
    }

    private void inverAlramInfo() throws ParseException {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        HashMap<String, Object> requestInfo = new HashMap<>(1);
        String requestParaminfo = JSON.toJSONString(requestInfo);
        String url = KSolarConstant.stationCollectAlarmUrl + "?pageNumber=1&pageSize=200";
        List<KsolarAlarmDto> result = kSolarRequestUtil.getResPonse(
                url,
                KSolarConstant.requestGET,
                requestParaminfo,
                KSolarConstant.resovle_rows,
                KsolarAlarmDto.class
        );
        if (!CollectionUtils.isEmpty(result)) {
            for (KsolarAlarmDto ksolarAlarmDto : result) {
                if (!ObjectUtils.isEmpty(ksolarAlarmDto.getInverterId())) {
                    String startTime = ksolarAlarmDto.getSaveTime();
                    String recoverTime = ksolarAlarmDto.getRemoveTime();
                    String pattern = "yyyy-MM-dd HH:mm:ss";
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    Date startTimeL = sdf.parse(startTime);
                    Date recoverTimeL = sdf.parse(recoverTime);
                    HYGFJPInverterWarn hygfjpInverterWarn = hygfjpInverterWarnMapper.selectOne(new QueryWrapper<HYGFJPInverterWarn>()
                            .eq("sn_code", ksolarAlarmDto.getAlarmId())
                            .eq("start_time", startTimeL.getTime())
                            .eq("third_code", PVProducerInfoEnum.KSOLAR.getCode())
                            .eq("third_station_id", ksolarAlarmDto.getStationId())
                    );
                    if (ObjectUtils.isEmpty(hygfjpInverterWarn)) {
                        hygfjpInverterWarn = new HYGFJPInverterWarn();
                    }


                    hygfjpInverterWarn.setTime(System.currentTimeMillis());
                    hygfjpInverterWarn.setTimeLong(System.currentTimeMillis());
                    hygfjpInverterWarn.setSnCode(ksolarAlarmDto.getAlarmId());
                    hygfjpInverterWarn.setThirdStationId(ksolarAlarmDto.getStationId());
                    hygfjpInverterWarn.setLevel(KSolarConstant.alarmLevel.get(ksolarAlarmDto.getLevels()));
                    hygfjpInverterWarn.setContent(ksolarAlarmDto.getMessage());
                    hygfjpInverterWarn.setThirdCode(PVProducerInfoEnum.KSOLAR.getCode());
                    hygfjpInverterWarn.setTreatment(ksolarAlarmDto.getSolution());
                    hygfjpInverterWarn.setStartTime(startTimeL.getTime());
                    hygfjpInverterWarn.setRecoverTime(recoverTimeL.getTime());
                    hygfjpInverterWarn.setState(KSolarConstant.alarmstatus.get(ksolarAlarmDto.getStatus()));
                    if (ObjectUtils.isEmpty(hygfjpInverterWarn.getCreatedTime())) {
                        hygfjpInverterWarn.setCreatedTime(System.currentTimeMillis());
                        hygfjpInverterWarnMapper.insert(hygfjpInverterWarn);
                    } else {
                        hygfjpInverterWarnMapper.insert(hygfjpInverterWarn);
                    }
                }
            }
        }
    }
}
