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

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.api.householdapi.Utils.CalendarAdjust;
import com.yeejoin.amos.api.householdapi.Utils.ImasterUtils;
import com.yeejoin.amos.api.householdapi.constant.GoLangConstant;
import com.yeejoin.amos.api.householdapi.constant.ImasterConstant;

import com.yeejoin.amos.api.householdapi.face.dto.ImasterAlarmDto;
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.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.ImasterDataService;
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.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ImasterDataServiceImpl implements ImasterDataService {



    //北向请求工具封装
    @Autowired
    private ImasterUtils imasterUtils;

    //北向mapper
    @Autowired
    private ImasterStationMapper imasterStationMapper;

    //北向mapper
    @Autowired
    private ImasterCollectorListMapper imasterCollectorListMapper;

    //北向mapper
    @Autowired
    private ImasterInverterListMapper imasterInverterListMapper;

    //北向mapper
    @Autowired
    private ImasterInverterListDetailsMapper imasterInverterListDetailsMapper;

    //北向mapper
    @Autowired
    private ImasterStationDetailsMapper imasterStationDetailsMapper;

    //北向mapper
    @Autowired
    private ImasterInverterMonthMapper imasterInverterMonthMapper;

    //北向mapper
    @Autowired
    private ImasterInverterYearMapper imasterInverterYearMapper;

    //北向mapper
    @Autowired
    private ImasterStationMonthMapper imasterStationMonthMapper;

    //北向mapper
    @Autowired
    private ImasterStationYearMapper imasterStationYearMapper;




    //监盘场站mapper
    @Autowired
    private JpStationMapper jpStationMapper;
    //监盘采集器mapper
    @Autowired
    private JpCollectorMapper jpCollectorMapper;
    //监盘逆变器mapper
    @Autowired
    private JpInverterMapper jpInverterMapper;

    //户用光伏场站历史mapper
    @Autowired
    private HYGFJPStationPowerHistoryMapper hygfjpStationPowerHistoryMapper;
    //户用光伏逆变器历史mapper
    @Autowired
    private HYGFJPInverterHistoryMapper hygfjpInverterHistoryMapper;
    //户用光伏采集器历史mapper
    @Autowired
    private HYGFJPCollectorHistoryMapper hygfjpCollectorHistoryMapper;
    //户用光伏逆变器告警
    @Autowired
    private HYGFJPInverterWarnMapper hygfjpInverterWarnMapper;
    //户用光伏逆变器历史mapper
    @Autowired
    private HYGFJPInverterElecHistoryMapper hygfjpInverterElecHistoryMapper;
    //户用光伏日发电量
    @Autowired
    private HYGFJPDayPowerMapper hygfjpDayPowerMapper;

    //户用光伏日发电量
    @Autowired
    JpInverterElectricityMapper jpInverterElectricityMapper;


    @Scheduled(cron = "${dataRequstScheduled.huawei}")
    @Override
    public void stationList() {
        HashMap<String, Object> requestInfo = new HashMap<>();
        requestInfo.put("pageNo", 1);
        String requestParaminfo = JSON.toJSONString(requestInfo);
        List<ImasterStationList> result = imasterUtils.getResPonse(ImasterConstant.stationListUrl,
                GoLangConstant.requestPost,
                requestParaminfo,
                ImasterConstant.resovleRule_data_page_records,
                ImasterStationList.class
        );
        for (int i = 0; i < result.size(); i++) {
            ImasterStationList imasterStationList = result.get(i);
            imasterStationList.setCreatedTime(System.currentTimeMillis());
            imasterStationMapper.insert(imasterStationList);
        }
    }


    @Scheduled(cron = "${dataRequstScheduled.huawei}")
    @Override
    public void stationDetail() {

        List<String> stationList = imasterStationMapper.getStationIds();
        String today = DateUtil.today();
        String hour = new Date().getHours() + ":00";
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            HashMap<String, Object> requestInfo = new HashMap<>();
            requestInfo.put("stationCodes", stationList.stream().collect(Collectors.joining(",")));
            requestInfo.put("collectTime", System.currentTimeMillis());
            String requestParaminfo = JSON.toJSONString(requestInfo);
            List<ImasterStationDetail> result = imasterUtils.getResPonseOther(ImasterConstant.stationDetailUrl,
                    GoLangConstant.requestPost,
                    requestParaminfo,
                    ImasterConstant.resovleRule_data_page_records,
                    ImasterStationDetail.class
            );


        List<ImasterStationDetailsMonth> result2 = imasterUtils.getResPonseOther(ImasterConstant.stationDetailMonthUrl,
                GoLangConstant.requestPost,
                requestParaminfo,
                ImasterConstant.resovleRule_data_page_records,
                ImasterStationDetailsMonth.class
        );
        List<ImasterStationDetailsYear> result3 = imasterUtils.getResPonseOther(ImasterConstant.stationDetailYearUrl,
                GoLangConstant.requestPost,
                requestParaminfo,
                ImasterConstant.resovleRule_data_page_records,
                ImasterStationDetailsYear.class
        );

            for (int j = 0; j < result.size(); j++) {
                QueryWrapper<ImasterStationList> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("plant_code", result.get(j).getStationCode());
                queryWrapper.orderByDesc("created_time");
                List<ImasterStationList> imasterStationListAll = imasterStationMapper.selectList(queryWrapper);
                ImasterStationList imasterStationList = imasterStationListAll.get(0);
                ImasterStationDetail imasterStationDetail = result.get(j);
                imasterStationDetail.setStationCode(imasterStationList.getPlantCode());
                imasterStationDetail.setCreatedTime(System.currentTimeMillis());
                imasterStationDetailsMapper.insert(imasterStationDetail);
                JpStation jpStation = jpStationMapper.selectOne(new QueryWrapper<JpStation>().
                        eq("third_code", PVProducerInfoEnum.HUAWEI.getCode()).
                        eq("third_station_id", imasterStationList.getPlantCode()));
                //给户用光伏存储的数据赋值
                if (ObjectUtils.isEmpty(jpStation)) {
                    jpStation = new JpStation();
                }
                // jpStation.setSnCode(imasterStationDetail.getNmicode());
                jpStation.setCapacity(Double.valueOf(imasterStationList.getCapacity()));
                jpStation.setName(imasterStationList.getPlantName());
                // jpStation.setPrice(Double.valueOf(imasterStationDetail.getPrice()));
                jpStation.setAddress(imasterStationList.getPlantAddress());
                jpStation.setLongitude(imasterStationList.getLongitude());
                jpStation.setLatitude(imasterStationList.getLatitude());
                // jpStation.setUserName(imasterStationDetail.getUsername());
                // jpStation.setUserPhone(String.valueOf(imasterStationDetail.getUsermobile()));
                jpStation.setStationContact(imasterStationList.getContactPerson());
                // jpStation.setModuleCount(ObjectUtils.isEmpty(Math.toIntExact(imasterStationDetail.getModule()))?0:Math.toIntExact(imasterStationDetail.getModule()));
                //并网类型
                // jpStation.setState(ImasterConstant.stationStaus.get(String.valueOf(imasterStationDetail.getRealHealthState())));
                jpStation.setThirdStationId(imasterStationList.getPlantCode());
                jpStation.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
                // jpStation.setRealTimePower(imasterStationDetail.getPower());
                // jpStation.setOnGridType(GoLangConstant.intoNetWorkStatus.get(String.valueOf(imasterStationDetail.getStationtypenew())));
                jpStation.setDayGenerate(imasterStationDetail.getDay_power() );
                jpStation.setMonthGenerate(imasterStationDetail.getMonth_power() );
                // jpStation.setMonthGenerate(imasterStationDetail.getMonthPower());
                // jpStation.setYearGenerate(imasterStationDetail.getYearenergy());

                Long currentTime = System.currentTimeMillis();

                Long monthStart = CalendarAdjust.getMonthStartTime(currentTime, "GMT+8:00");
                Long yearStart = CalendarAdjust.getYearStartTime(currentTime, "GMT+8:00");

                // 获取年发电量  年收益
                for (ImasterStationDetailsYear imasterStationDetailsYear : result3
                ) {
                    if(imasterStationDetailsYear.getCollectTime().equals(String.valueOf(yearStart))) {
                        jpStation.setYearGenerate(imasterStationDetailsYear.getInverter_power());
                        jpStation.setYearIncome(imasterStationDetailsYear.getPower_profit());
                        imasterStationDetailsYear.setStationCode(imasterStationList.getPlantCode());
                        imasterStationDetailsYear.setCreatedTime(System.currentTimeMillis());
                        imasterStationYearMapper.insert(imasterStationDetailsYear);
                    }
                }


                // 获取月收益

                for (ImasterStationDetailsMonth imasterStationDetailsMonth: result2
                ) {
                    if(imasterStationDetailsMonth.getCollectTime().equals(String.valueOf(monthStart))) {
                        jpStation.setMonthIncome(imasterStationDetailsMonth.getPower_profit());
                        imasterStationDetailsMonth.setStationCode(imasterStationList.getPlantCode());
                        imasterStationDetailsMonth.setCreatedTime(System.currentTimeMillis());
                        imasterStationMonthMapper.insert(imasterStationDetailsMonth);
                    }
                }

                jpStation.setAccumulatedPower(imasterStationDetail.getTotal_power());
                jpStation.setDayIncome(imasterStationDetail.getDay_income());
                jpStation.setCumulativeIncome(imasterStationDetail.getTotal_income());
                jpStation.setState(ImasterConstant.stationStaus.get(String.valueOf(imasterStationDetail.getReal_health_state())));
                // jpStation.setDayIncome(imasterStationDetail.getDayIncome());
                // jpStation.setMonthIncome(imasterStationDetail.getMonthincome());
                // jpStation.setYearIncome(imasterStationDetail.getYearincome());
                // jpStation.setCumulativeIncome(imasterStationDetail.getTotalIncome());
                // jpStation.setArea(imasterStationDetail.getRegionstr());
                // jpStation.setEmail(imasterStationDetail.getUseremail());
                // jpStation.setOnGridTime(new Date(imasterStationDetail.getFispowertime()));
                // jpStation.setAccessTime(new Date(imasterStationDetail.getFisgeneratetime()));
                // jpStation.setCreateTime(new Date(imasterStationDetail.getCreatedate()));
                // jpStation.setRatedPower(Double.valueOf(imasterStationDetail.getInverterpower()));
                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(imasterStationDetail.getPower());
                hygfjpStationPowerHistory.setThirdCode(jpStation.getThirdCode());
                hygfjpStationPowerHistory.setTime(System.currentTimeMillis());
                hygfjpStationPowerHistoryMapper.insert(hygfjpStationPowerHistory);
                HYGFJPDayPower hygfjpDayPower = hygfjpDayPowerMapper.selectOne(
                        new QueryWrapper<HYGFJPDayPower>().
                                eq("tation_id", imasterStationList.getPlantCode()).
                                eq("year_month_day", today).
                                eq("hour", hour)
                );
                if (ObjectUtils.isEmpty(hygfjpDayPower)) {
                    hygfjpDayPower = new HYGFJPDayPower();
                }
                hygfjpDayPower.setTationId(imasterStationList.getPlantCode());
                hygfjpDayPower.setHour(hour);
                hygfjpDayPower.setYearMonthDay(today);
//                 hygfjpDayPower.setPower(imasterStationDetail.getPower());
                if (ObjectUtils.isEmpty(hygfjpDayPower.getCreatedTime())) {
                    hygfjpDayPower.setCreatedTime(System.currentTimeMillis());
                    hygfjpDayPowerMapper.insert(hygfjpDayPower);
                } else {
                    hygfjpDayPowerMapper.insert(hygfjpDayPower);
                }
            }
    }


    @Scheduled(cron = "${dataRequstScheduled.huawei}")
    @Override
    public void collectorList() {
        List<String> stationIds = imasterStationMapper.getStationIds();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            HashMap<String, Object> requestInfo = new HashMap<>();
            requestInfo.put("stationCodes", stationIds.stream().collect(Collectors.joining(",")));
            String requestParaminfo = JSON.toJSONString(requestInfo);
            List<ImasterCollectorList> result = imasterUtils.getResPonse(ImasterConstant.collectorListUrl,
                    GoLangConstant.requestPost,
                    requestParaminfo,
                    ImasterConstant.resovleRule_data_page_records,
                    ImasterCollectorList.class
            );
            for (int j = 0; j < result.size(); j++) {
                QueryWrapper<ImasterStationList> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("plant_code", result.get(j).getStationCode());
                queryWrapper.orderByDesc("created_time");
                List<ImasterStationList> imasterStationListAll = imasterStationMapper.selectList(queryWrapper);
                ImasterStationList imasterStationList = imasterStationListAll.get(0);

                ImasterCollectorList imasterCollectorList = result.get(j);
                imasterCollectorList.setStationName(imasterStationList.getPlantName());
                imasterCollectorList.setCreatedTime(System.currentTimeMillis());

                if(imasterCollectorList.getDevTypeId() == ImasterConstant.devTypeC) {
                    imasterCollectorListMapper.insert(imasterCollectorList);

                    JpCollector jpCollector = jpCollectorMapper.selectOne(new QueryWrapper<JpCollector>().
                            eq("third_station_id", imasterCollectorList.getStationCode()).
                            eq("third_code", PVProducerInfoEnum.HUAWEI.getCode()).
                            eq("sn_code", imasterCollectorList.getEsnCode()));
                    if (ObjectUtils.isEmpty(jpCollector)) {
                        jpCollector = new JpCollector();
                    }
                    //sn编码
                    jpCollector.setSnCode(imasterCollectorList.getEsnCode());
                    jpCollector.setAddr(imasterStationList.getPlantAddress());
                    jpCollector.setName(imasterCollectorList.getDevName());
                    //类型
                    // jpCollector.setType(collectorDetailDto.getModel());
                    //更新时间
                    jpCollector.setUpdateTime(new Date());
                    //出场日期
//                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()));
                    //第三方电站id
                    jpCollector.setThirdStationId(imasterCollectorList.getStationCode());
                    //第三方厂商标识
                    jpCollector.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
                    //第三方厂商标识
                    jpCollector.setState(ImasterConstant.inverterStaus.get("1"));

                    jpCollector.setStationName(imasterStationList.getPlantName());
                    jpCollector.setVersion(imasterCollectorList.getSoftwareVersion());
//                jpCollector.setAddr(collectorDetailDto.getAddr());
//                jpCollector.setName(collectorDetailDto.getName());
                    if (ObjectUtils.isEmpty(jpCollector.getSequenceNbr())) {
                        jpCollectorMapper.insert(jpCollector);
                    } else {
                        jpCollectorMapper.updateById(jpCollector);
                    }
                    // td-collector-history
                    HYGFJPCollectorHistory hygfjpCollectorHistory = new HYGFJPCollectorHistory();
                    hygfjpCollectorHistory.setTime(System.currentTimeMillis());
                    hygfjpCollectorHistory.setCreatedTime(System.currentTimeMillis());
                    hygfjpCollectorHistory.setSnCode(imasterCollectorList.getEsnCode());
                    // hygfjpCollectorHistory.setSignalStrength(Double.valueOf(collectorDetailDto.getRssiLevel()));
                    hygfjpCollectorHistory.setThirdStationId(imasterCollectorList.getStationCode());
                    hygfjpCollectorHistory.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
                    hygfjpCollectorHistoryMapper.insert(hygfjpCollectorHistory);
                }
            }
    }

    @Override
    public void collectorDetail() {

    }


    @Scheduled(cron = "${dataRequstScheduled.huawei}")
    @Override
    public void inverterList() {
        List<String> stationIds = imasterStationMapper.getStationIds();
        for (int i = 0; i < stationIds.size(); i++) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            HashMap<String, Object> requestInfo = new HashMap<>();
            requestInfo.put("stationCodes", stationIds.stream().collect(Collectors.joining(",")));
            String requestParaminfo = JSON.toJSONString(requestInfo);
            List<ImasterInverterList> result = imasterUtils.getResPonse(ImasterConstant.collectorListUrl,
                    GoLangConstant.requestPost,
                    requestParaminfo,
                    ImasterConstant.resovleRule_data_page_records,
                    ImasterInverterList.class
            );
            for (int j = 0; j < result.size(); j++) {
                QueryWrapper<ImasterStationList> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("plant_code", result.get(j).getStationCode());
                queryWrapper.orderByDesc("created_time");
                List<ImasterStationList> imasterStationListAll = imasterStationMapper.selectList(queryWrapper);
                ImasterStationList imasterStationList = imasterStationListAll.get(0);

                ImasterInverterList imasterInverterList = result.get(j);
                imasterInverterList.setStationName(imasterStationList.getPlantName());
                imasterInverterList.setAddr(imasterStationList.getPlantAddress());
                imasterInverterList.setCreatedTime(System.currentTimeMillis());
                if(imasterInverterList.getDevTypeId() == ImasterConstant.devTypeI) {
                    imasterInverterListMapper.insert(imasterInverterList);
                }
            }
        }
    }


    @Scheduled(cron = "${dataRequstScheduled.huawei}")
    @Override
    public void inverterDetail() {
        List<String> inverterSns = imasterInverterListMapper.getCollectIds();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            HashMap<String, Object> requestInfo = new HashMap<>();
            String collect = inverterSns.stream().collect(Collectors.joining(","));
            requestInfo.put("sns", collect);
            requestInfo.put("devTypeId", 1);
            requestInfo.put("collectTime", System.currentTimeMillis());

            String requestParaminfo = JSON.toJSONString(requestInfo);
            List<ImasterInverterListDetails> result = imasterUtils.getResPonseOther(ImasterConstant.collectorDetailUrl,
                    GoLangConstant.requestPost,
                    requestParaminfo,
                    ImasterConstant.resovleRule_data_page_records,
                    ImasterInverterListDetails.class
            );

            List<ImasterInverterMonth> result2 = imasterUtils.getResPonseOther(ImasterConstant.collectorDetailMonthUrl,
                    GoLangConstant.requestPost,
                    requestParaminfo,
                    ImasterConstant.resovleRule_data_page_records,
                    ImasterInverterMonth.class
            );
            List<ImasterInverterYear> result3 = imasterUtils.getResPonseOther(ImasterConstant.collectorDetailYearUrl,
                    GoLangConstant.requestPost,
                    requestParaminfo,
                    ImasterConstant.resovleRule_data_page_records,
                    ImasterInverterYear.class
            );

            for (int j = 0; j < result.size(); j++) {
                ImasterInverterListDetails inverterDetailDto = result.get(j);
                inverterDetailDto.setCreatedTime((System.currentTimeMillis()));
                imasterInverterListDetailsMapper.insert(result.get(j));

                QueryWrapper<ImasterInverterList> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("esn_code", result.get(j).getInverterId());
                queryWrapper.orderByDesc("created_time");
                List<ImasterInverterList> imasterInverterLists = imasterInverterListMapper.selectList(queryWrapper);
                ImasterInverterList imasterInverterList = imasterInverterLists.get(0);

                QueryWrapper<ImasterCollectorList> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("dev_name", imasterInverterList.getDevName());
                queryWrapper1.orderByDesc("created_time");
                List<ImasterCollectorList> collectorLists = imasterCollectorListMapper.selectList(queryWrapper1);
                ImasterCollectorList collectorList = collectorLists.get(0);

                JpInverter jpInverter = jpInverterMapper.selectOne(new QueryWrapper<JpInverter>().
                        eq("third_station_id", imasterInverterList.getStationCode()).
                        eq("third_code", PVProducerInfoEnum.HUAWEI.getCode()).
                        eq("sn_code", imasterInverterList.getEsnCode()));
                if (ObjectUtils.isEmpty(jpInverter)) {
                    jpInverter = new JpInverter();
                }
                jpInverter.setSnCode(imasterInverterList.getEsnCode());
                jpInverter.setAddr(imasterInverterList.getAddr());
                jpInverter.setCollectorSnCode(collectorList.getEsnCode());
                jpInverter.setCollectorId(String.valueOf(collectorList.getId()));
                jpInverter.setDayPowerGeneration(inverterDetailDto.getDay_cap() );
                jpInverter.setState(ImasterConstant.inverterStaus.get(String.valueOf(inverterDetailDto.getRun_state())));
                jpInverter.setTotalPowerGeneration(inverterDetailDto.getTotal_cap());
                Long currentTime = System.currentTimeMillis();

                Long monthStart = CalendarAdjust.getMonthStartTime(currentTime, "GMT+8:00");
                Long yearStart = CalendarAdjust.getYearStartTime(currentTime, "GMT+8:00");


                // 获取年发电量
                for (ImasterInverterYear imasterInverterYear : result3
                ) {
                    if(imasterInverterYear.getCollectTime().equals(String.valueOf(yearStart)) && inverterDetailDto.getInverterId().equals(imasterInverterYear.getInverterId())) {
                        jpInverter.setYearPowerGeneration(imasterInverterYear.getProduct_power());
                        imasterInverterYear.setCreatedTime(System.currentTimeMillis());
                        imasterInverterYearMapper.insert(imasterInverterYear);
                    }
                }


                // 获取月发电量

                for (ImasterInverterMonth imasterInverterMonth: result2
                ) {
                    if(imasterInverterMonth.getCollectTime().equals(String.valueOf(monthStart)) && inverterDetailDto.getInverterId().equals(imasterInverterMonth.getInverterId())) {
                        jpInverter.setMonthPowerGeneration(imasterInverterMonth.getProduct_power());
                        imasterInverterMonth.setCreatedTime(System.currentTimeMillis());
                        imasterInverterMonthMapper.insert(imasterInverterMonth);
                    }
                }



//                jpInverter.setCollectorId(inverterDetailDto.getCollectorId());
   //             jpInverter.setCollectorSnCode(inverterDetailDto.getCollectorsn());
                jpInverter.setUpdateTime(new Date());
//                jpInverter.setCurrentPower(inverterDetailDto.getPac());
//                jpInverter.setDayPowerGeneration(inverterDetailDto.getEToday());
//                jpInverter.setMonthPowerGeneration(inverterDetailDto.getEMonth() * GoLangConstant.mwhTokwh);
//                jpInverter.setYearPowerGeneration(inverterDetailDto.getEYear() * GoLangConstant.mwhTokwh);
//                jpInverter.setTotalPowerGeneration(inverterDetailDto.getETotal() * GoLangConstant.mwhTokwh);
//                jpInverter.setBrand(inverterDetailDto.getName());
//                jpInverter.setModel(inverterDetailDto.getProductModel());
//                jpInverter.setNationalStandard(inverterDetailDto.getNationalStandards());
                jpInverter.setVersion(imasterInverterList.getSoftwareVersion());
           //     jpInverter.setGenerationHours(String.valueOf(inverterDetailDto.getFullHour()));
                jpInverter.setId(String.valueOf(imasterInverterList.getId()));
               // jpInverter.setCapacity(inverterDetailDto.getPower().intValue());
                jpInverter.setThirdStationId(String.valueOf(imasterInverterList.getStationCode()));
                jpInverter.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
                jpInverter.setStationName(imasterInverterList.getStationName());
                if (!ObjectUtils.isEmpty(jpInverter.getSequenceNbr())) {
                    jpInverterMapper.updateById(jpInverter);
                } else {
                    jpInverterMapper.insert(jpInverter);
                }
                String jsonString = JSON.toJSONString(inverterDetailDto);
                Map<String, Object> hanlderResult = JSON.parseObject(jsonString, Map.class);

                JpInverterElectricity jpInverterElectricityR = jpInverterElectricityMapper.selectOne(new QueryWrapper<JpInverterElectricity>().
                        eq("sn_code", imasterInverterList.getEsnCode()).
                        eq("type", "交流").
                        eq("name", "A")
                );
                if (ObjectUtils.isEmpty(jpInverterElectricityR)) {
                    jpInverterElectricityR = new JpInverterElectricity();
                }
                jpInverterElectricityR.setInverterId(String.valueOf(imasterInverterList.getId()));
                jpInverterElectricityR.setSnCode(imasterInverterList.getEsnCode());
                jpInverterElectricityR.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
                jpInverterElectricityR.setThirdStationId(imasterInverterList.getStationCode());
                jpInverterElectricityR.setType("交流");
                jpInverterElectricityR.setName("A");
                jpInverterElectricityR.setVoltage(inverterDetailDto.getA_u());
                jpInverterElectricityR.setCurrent(inverterDetailDto.getA_i());
                if (ObjectUtils.isEmpty(jpInverterElectricityR.getSequenceNbr())) {
                    jpInverterElectricityMapper.insert(jpInverterElectricityR);
                } else {
                    jpInverterElectricityMapper.updateById(jpInverterElectricityR);
                }

                JpInverterElectricity jpInverterElectricityB = jpInverterElectricityMapper.selectOne(new QueryWrapper<JpInverterElectricity>().
                        eq("sn_code", imasterInverterList.getEsnCode()).
                        eq("type", "交流").
                        eq("name", "B")
                );
                if (ObjectUtils.isEmpty(jpInverterElectricityB)) {
                    jpInverterElectricityB = new JpInverterElectricity();
                }
                jpInverterElectricityB.setInverterId(String.valueOf(imasterInverterList.getId()));
                jpInverterElectricityB.setSnCode(imasterInverterList.getEsnCode());
                jpInverterElectricityB.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
                jpInverterElectricityB.setThirdStationId(imasterInverterList.getStationCode());
                jpInverterElectricityB.setType("交流");
                jpInverterElectricityB.setName("B");
                jpInverterElectricityB.setVoltage(inverterDetailDto.getB_u());
                jpInverterElectricityB.setCurrent(inverterDetailDto.getB_i());
                if (ObjectUtils.isEmpty(jpInverterElectricityB.getSequenceNbr())) {
                    jpInverterElectricityMapper.insert(jpInverterElectricityB);
                } else {
                    jpInverterElectricityMapper.updateById(jpInverterElectricityB);
                }

                JpInverterElectricity jpInverterElectricityC = jpInverterElectricityMapper.selectOne(new QueryWrapper<JpInverterElectricity>().
                        eq("sn_code", imasterInverterList.getEsnCode()).
                        eq("type", "交流").
                        eq("name", "C")
                );
                if (ObjectUtils.isEmpty(jpInverterElectricityC)) {
                    jpInverterElectricityC = new JpInverterElectricity();
                }
                jpInverterElectricityC.setInverterId(String.valueOf(imasterInverterList.getId()));
                jpInverterElectricityC.setSnCode(imasterInverterList.getEsnCode());
                jpInverterElectricityC.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
                jpInverterElectricityC.setThirdStationId(imasterInverterList.getStationCode());
                jpInverterElectricityC.setType("交流");
                jpInverterElectricityC.setName("C");
                jpInverterElectricityC.setVoltage(inverterDetailDto.getC_u());
                jpInverterElectricityC.setCurrent(inverterDetailDto.getC_i());
                if (ObjectUtils.isEmpty(jpInverterElectricityC.getSequenceNbr())) {
                    jpInverterElectricityMapper.insert(jpInverterElectricityC);
                } else {
                    jpInverterElectricityMapper.updateById(jpInverterElectricityC);
                }


                for (int k1 = 1; k1 < 29; k1++) {
                    JpInverterElectricity jpInverterElectricity = jpInverterElectricityMapper.selectOne(new QueryWrapper<JpInverterElectricity>().
                            eq("sn_code", imasterInverterList.getEsnCode()).
                            eq("type", "直流").
                            eq("name", "PV" + k1)
                    );
                    if (ObjectUtils.isEmpty(jpInverterElectricity)) {
                        jpInverterElectricity = new JpInverterElectricity();
                    }
                    jpInverterElectricity.setInverterId(String.valueOf(imasterInverterList.getId()));
                    jpInverterElectricity.setSnCode(imasterInverterList.getEsnCode());
                    jpInverterElectricity.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
                    jpInverterElectricity.setThirdStationId(String.valueOf(imasterInverterList.getStationCode()));
                    jpInverterElectricity.setType("直流");
                    jpInverterElectricity.setName("PV" + k1);
                    jpInverterElectricity.setVoltage(Double.valueOf(hanlderResult.get("pv" + k1 + "_u").toString()));
                    jpInverterElectricity.setCurrent(Double.valueOf(hanlderResult.get("pv" + k1 + "_i").toString()));
                    // jpInverterElectricity.setPower(Double.valueOf(hanlderResult.get("pow" + k1).toString()));
                    if (ObjectUtils.isEmpty(jpInverterElectricity.getSequenceNbr())) {
                        jpInverterElectricityMapper.insert(jpInverterElectricity);
                    } else {
                        jpInverterElectricityMapper.updateById(jpInverterElectricity);
                    }
                }
                HYGFJPInverterElecHistory hygfjpInverterElecHistory = new HYGFJPInverterElecHistory();
                hygfjpInverterElecHistory.setThirdStationId(String.valueOf(imasterInverterList.getStationCode()));
                hygfjpInverterElecHistory.setCreatedTime(System.currentTimeMillis());
                hygfjpInverterElecHistory.setSnCode(imasterInverterList.getEsnCode());
                hygfjpInverterElecHistory.setUAcCurrent(inverterDetailDto.getA_i());
                hygfjpInverterElecHistory.setVAcCurrent(inverterDetailDto.getB_i());
                hygfjpInverterElecHistory.setWAcCurrent(inverterDetailDto.getC_i());
                hygfjpInverterElecHistory.setUAcVoltage(inverterDetailDto.getA_u());
                hygfjpInverterElecHistory.setVAcVoltage(inverterDetailDto.getB_u());
                hygfjpInverterElecHistory.setWAcVoltage(inverterDetailDto.getC_u());
                hygfjpInverterElecHistory.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
                hygfjpInverterElecHistory.setTime(System.currentTimeMillis());
                hygfjpInverterElecHistoryMapper.insert(hygfjpInverterElecHistory);
                // 逆变器历史
                String today = DateUtil.today();
                HYGFJPInverterHistory hygfjpInverterHistory = hygfjpInverterHistoryMapper.selectOne(new QueryWrapper<HYGFJPInverterHistory>().eq("sn_code", imasterInverterList.getEsnCode()).eq("date", today));
                if (ObjectUtils.isEmpty(hygfjpInverterHistory)) {
                    hygfjpInverterHistory = new HYGFJPInverterHistory();
                }
                hygfjpInverterHistory.setDate(today);
                hygfjpInverterHistory.setThirdStationId(String.valueOf(imasterInverterList.getStationCode()));
                hygfjpInverterHistory.setInverterId(String.valueOf(imasterInverterList.getId()));
                hygfjpInverterHistory.setSnCode(imasterInverterList.getEsnCode());
                hygfjpInverterHistory.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
                // hygfjpInverterHistory.setGenerationHours(inverterDetailDto.getFullHour());
                 hygfjpInverterHistory.setPowerGeneration(inverterDetailDto.getDay_cap());
                if (ObjectUtils.isEmpty(hygfjpInverterHistory.getCreatedTime())) {
                    hygfjpInverterHistory.setCreatedTime(System.currentTimeMillis());
                    hygfjpInverterHistoryMapper.insert(hygfjpInverterHistory);
                } else {
                    hygfjpInverterHistoryMapper.insert(hygfjpInverterHistory);
                }
            }
    }


    @Scheduled(cron = "${dataRequstScheduled.huawei}")
    @Override
    public void inverAlramInfo() {

        List<String> inverterSns = imasterInverterListMapper.getCollectIds();
        for (int i = 0; i < inverterSns.size(); i++) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            HashMap<String, Object> requestInfo = new HashMap<>();

            requestInfo.put("sns", inverterSns.stream().collect(Collectors.joining(",")));
            requestInfo.put("language", "zh_CN  ");
            requestInfo.put("devTypes", 1);
            requestInfo.put("beginTime", DateUtil.today());
            requestInfo.put("endTime", DateUtil.today());
            String requestParaminfo = JSON.toJSONString(requestInfo);
            List<ImasterAlarmDto> result = imasterUtils.getResPonse(ImasterConstant.alarmListUrl,
                    GoLangConstant.requestPost,
                    requestParaminfo,
                    ImasterConstant.resovleRule_data_page_records,
                    ImasterAlarmDto.class
            );
            for (int j = 0; j < result.size(); j++) {
                ImasterAlarmDto alarmDto = result.get(j);
                if (!ObjectUtils.isEmpty(alarmDto.getEsnCode())) {
                    HYGFJPInverterWarn hygfjpInverterWarn = hygfjpInverterWarnMapper.selectOne(new QueryWrapper<HYGFJPInverterWarn>()
                            .eq("sn_code", alarmDto.getEsnCode())
                            .eq("start_time", alarmDto.getRaiseTime())
                            .eq("third_station_id", String.valueOf(alarmDto.getStationCode()))
                    );
                    if (ObjectUtils.isEmpty(hygfjpInverterWarn)) {
                        hygfjpInverterWarn = new HYGFJPInverterWarn();
                    }
                    hygfjpInverterWarn.setTime(System.currentTimeMillis());
                    hygfjpInverterWarn.setTimeLong(System.currentTimeMillis());
                    hygfjpInverterWarn.setSnCode(alarmDto.getEsnCode());
                    hygfjpInverterWarn.setThirdStationId(String.valueOf(alarmDto.getStationCode()));
                    hygfjpInverterWarn.setLevel(ImasterConstant.alarmLevel.get(alarmDto.getLev().toString()));
                    hygfjpInverterWarn.setContent(alarmDto.getAlarmName());
                    hygfjpInverterWarn.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
                    hygfjpInverterWarn.setTreatment(alarmDto.getDevName());
                    hygfjpInverterWarn.setStartTime(alarmDto.getRaiseTime());
                    hygfjpInverterWarn.setState(ImasterConstant.alarmstatus.get(alarmDto.getStatus().toString()));
                    if (ObjectUtils.isEmpty(hygfjpInverterWarn.getCreatedTime())) {
                        hygfjpInverterWarn.setCreatedTime(System.currentTimeMillis());
                        hygfjpInverterWarnMapper.insert(hygfjpInverterWarn);
                    } else {
                        hygfjpInverterWarnMapper.insert(hygfjpInverterWarn);
                    }
                }
            }
        }
    }
}
