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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
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
    JpInverterElectricityMapper jpInverterElectricityMapper;
    //北向请求工具封装
    @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
    private TdHYGFInverterDayGenerateMapper tdHYGFInverterDayGenerateMapper;
    @Autowired
    private TdHYGFInverterMonthGenerateMapper tdHYGFInverterMonthGenerateMapper;
    @Autowired
    private TdHYGFInverterYearGenerateMapper tdHYGFInverterYearGenerateMapper;
    @Autowired
    private TdHYGFStationMonthGenerateMapper TdHYGFStationMonthGenerateMapper;
    @Autowired
    private TdHYGFStationYearGenerateMapper TdHYGFStationYearGenerateMapper;
    @Autowired
    private TdHYGFStationAllGenerateMapper TdHYGFStationAllGenerateMapper;
    @Autowired
    private TdHYGFInverterTotalGenerateMapper tdHYGFInverterTotalGenerateMapper;
    @Autowired
    TdJpStationMapper tdJpStationMapper;
    @Autowired
    private HouseholdPvApiServiceImpl householdPvApiService;
	final static Logger logger = LoggerFactory.getLogger(GoLangDataAcquisitionServiceImpl.class);

	final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "${dataRequstScheduled.huawei}")
    @Override
    @Async
    public void stationList() {
    	long ts = System.currentTimeMillis();
    	logger.info("-------华为同步电站开始" + ts + "------- " + sdf.format(new Date()));
        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);
        }
        logger.info("-------华为同步电站结束" + ts + "------- " + sdf.format(new Date()));
    }


    @Scheduled(cron = "${dataRequstScheduled.huawei}")
    @Override
    @Async
    public void stationDetail() {
    	long ts = System.currentTimeMillis();
    	logger.info("-------华为同步电站详情开始" + ts + "------- " + sdf.format(new Date()));
        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
        );

        List<String> inverterSns = imasterInverterListMapper.getCollectIds();
        HashMap<String, Object> requestInfo1 = new HashMap<>();
        String collect = inverterSns.stream().collect(Collectors.joining(","));
        requestInfo1.put("sns", collect);
        requestInfo1.put("devTypeId", 1);
        requestInfo1.put("collectTime", System.currentTimeMillis());
        String requestParaminfo1 = JSON.toJSONString(requestInfo1);

        List<ImasterInverterListDetails> result4 = imasterUtils.getResPonseOther(ImasterConstant.collectorDetailUrl,
                GoLangConstant.requestPost,
                requestParaminfo1,
                ImasterConstant.resovleRule_data_page_records,
                ImasterInverterListDetails.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("三一硅能（株洲）有限公司");
            jpStation.setUserPhone("18511539874");
            jpStation.setOnGridType("自发自用");
            jpStation.setType("工商业");
            //jpStation.setOnGridTime(new Date("2023-05-22"));
//                jpStation.setRealTimePower();

            jpStation.setPrice(0.45);
            jpStation.setRatedPower(1735.440);
            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);
                }
            }

            //实时功率
            Double active_power = 0.0;
            for (ImasterInverterListDetails imasterInverterListDetails : result4) {
                active_power = active_power + (imasterInverterListDetails.getActive_power() != null ? imasterInverterListDetails.getActive_power() : 0.0);
            }
            if(active_power<= 0){
                active_power = jpInverterMapper.getHuaWeiStationCurrentPower();
            }
            jpStation.setRealTimePower(active_power);

            jpStation.setAccumulatedPower(imasterStationDetail.getTotal_power());


            jpStation.setCumulativeIncome(imasterStationDetail.getTotal_power() != null ? imasterStationDetail.getTotal_power() * 0.45 : 0.0);


            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()));
            jpStation.setRecDate(new Date());
            if (!ObjectUtils.isEmpty(jpStation.getSequenceNbr())) {
                jpStationMapper.updateById(jpStation);
            } else {
                jpStationMapper.insert(jpStation);
            }


            //增加td 电站区域公司，经销商绑定表
//            TdJpStation tdJpStation = tdJpStationMapper.selectOne(new QueryWrapper<TdJpStation>().
//                    eq("third_code",PVProducerInfoEnum.HUAWEI.getCode()).
//                    eq("third_station_id",  imasterStationList.getPlantCode()));
//            //判断是否存在
//            if (ObjectUtils.isEmpty(tdJpStation)) {
//                tdJpStation = new TdJpStation();
//            }
//            tdJpStation.setAmosCompanyCode(jpStation.getAmosCompanyCode());
//            tdJpStation.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
//            tdJpStation.setThirdStationId( imasterStationList.getPlantCode());
//            tdJpStation.setThirdCode(PVProducerInfoEnum.HUAWEI.getCode());
//            tdJpStation.setIsDelete(jpStation.getIsDelete()?1:0);
//            tdJpStation.setStationName(jpStation.getName());
//            if (!ObjectUtils.isEmpty(tdJpStation.getCreatedTime())) {
//                tdJpStationMapper.insert(tdJpStation);
//            } else {
//                tdJpStation.setCreatedTime(System.currentTimeMillis());
//                tdJpStationMapper.insert(tdJpStation);
//            }







            HYGFJPStationPowerHistory hygfjpStationPowerHistory = new HYGFJPStationPowerHistory();
            hygfjpStationPowerHistory.setCreatedTime(System.currentTimeMillis());
            hygfjpStationPowerHistory.setThirdStationId(jpStation.getThirdStationId());
            // hygfjpStationPowerHistory.setPower(imasterStationDetail.getPower());
            hygfjpStationPowerHistory.setPower(jpStation.getRealTimePower());

            hygfjpStationPowerHistory.setThirdCode(jpStation.getThirdCode());
            hygfjpStationPowerHistory.setTime(System.currentTimeMillis());


            //新加
            hygfjpStationPowerHistory.setAmosCompanyCode(jpStation.getAmosCompanyCode());
            hygfjpStationPowerHistory.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
            hygfjpStationPowerHistory.setStationName(jpStation.getName());
            hygfjpStationPowerHistory.setStationState(jpStation.getState());





            hygfjpStationPowerHistoryMapper.insert(hygfjpStationPowerHistory);
            HYGFJPDayPower hygfjpDayPower = hygfjpDayPowerMapper.selectOne(
                    new QueryWrapper<HYGFJPDayPower>().
                            eq("third_station_id", imasterStationList.getPlantCode()).
                            eq("year_month_day", today).
                            eq("hour", hour)
            );
            if (ObjectUtils.isEmpty(hygfjpDayPower)) {
                hygfjpDayPower = new HYGFJPDayPower();
            }
            hygfjpDayPower.setThirdStationId(imasterStationList.getPlantCode());
            hygfjpDayPower.setHour(hour);
            hygfjpDayPower.setYearMonthDay(today);
            hygfjpDayPower.setPower(active_power);
            //新加
            hygfjpDayPower.setAmosCompanyCode(jpStation.getAmosCompanyCode());
            hygfjpDayPower.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
            hygfjpDayPower.setStationName(jpStation.getName());
            hygfjpDayPower.setStationState(jpStation.getState());

            if (ObjectUtils.isEmpty(hygfjpDayPower.getCreatedTime())) {
                hygfjpDayPower.setCreatedTime(System.currentTimeMillis());
                hygfjpDayPowerMapper.insert(hygfjpDayPower);
            } else {
                hygfjpDayPowerMapper.insert(hygfjpDayPower);
            }
            Date today1 = new Date();
            //户用场站日发电量
            TdHYGFStationMonthGenerate TdHYGFStationMonthGenerate = TdHYGFStationMonthGenerateMapper.selectOne(new QueryWrapper<TdHYGFStationMonthGenerate>()
                    .eq("third_station_id", jpStation.getThirdStationId())
                    .eq("day_time", DateUtil.format(today1, "yyyy-MM-dd"))
                    .eq("year_month", DateUtil.format(today1, "yyyy-MM")));
            if (ObjectUtils.isEmpty(TdHYGFStationMonthGenerate)) {
                TdHYGFStationMonthGenerate = new TdHYGFStationMonthGenerate();
            }

            TdHYGFStationMonthGenerate.setThirdStationId(jpStation.getThirdStationId());
            TdHYGFStationMonthGenerate.setDayTime(DateUtil.format(today1, "yyyy-MM-dd"));
            TdHYGFStationMonthGenerate.setYearMonth(DateUtil.format(today1, "yyyy-MM"));
            TdHYGFStationMonthGenerate.setGenerate(jpStation.getDayGenerate());
            TdHYGFStationMonthGenerate.setFullhour(jpStation.getDayGenerate() / jpStation.getCapacity());
            TdHYGFStationMonthGenerate.setIncome(jpStation.getDayIncome());
            //新加
            TdHYGFStationMonthGenerate.setAmosCompanyCode(jpStation.getAmosCompanyCode());
            TdHYGFStationMonthGenerate.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
            TdHYGFStationMonthGenerate.setStationName(jpStation.getName());
            TdHYGFStationMonthGenerate.setStationState(jpStation.getState());
            householdPvApiService.addTdHYGFStationDayGenerate(TdHYGFStationMonthGenerate,hour);
            if (ObjectUtils.isEmpty(TdHYGFStationMonthGenerate.getCreatedTime())) {
                TdHYGFStationMonthGenerate.setCreatedTime(System.currentTimeMillis());
                TdHYGFStationMonthGenerateMapper.insert(TdHYGFStationMonthGenerate);
            } else {
                TdHYGFStationMonthGenerateMapper.insert(TdHYGFStationMonthGenerate);
            }
            //户用场站月发电量
            TdHYGFStationYearGenerate TdHYGFStationYearGenerate = TdHYGFStationYearGenerateMapper.selectOne(new QueryWrapper<TdHYGFStationYearGenerate>()
                    .eq("third_station_id", jpStation.getThirdStationId())
                    .eq("month_time", DateUtil.format(today1, "yyyy-MM"))
                    .eq("year", DateUtil.format(today1, "yyyy")));
            if (ObjectUtils.isEmpty(TdHYGFStationYearGenerate)) {
                TdHYGFStationYearGenerate = new TdHYGFStationYearGenerate();
            }
            TdHYGFStationYearGenerate.setThirdStationId(jpStation.getThirdStationId());
            TdHYGFStationYearGenerate.setMonthTime(DateUtil.format(today1, "yyyy-MM"));
            TdHYGFStationYearGenerate.setYear(DateUtil.format(today1, "yyyy"));
            TdHYGFStationYearGenerate.setGenerate(jpStation.getMonthGenerate());
            TdHYGFStationYearGenerate.setFullhour(jpStation.getMonthGenerate() / jpStation.getCapacity());
            TdHYGFStationYearGenerate.setIncome(jpStation.getMonthIncome());
            //新加
            TdHYGFStationYearGenerate.setAmosCompanyCode(jpStation.getAmosCompanyCode());
            TdHYGFStationYearGenerate.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
            TdHYGFStationYearGenerate.setStationName(jpStation.getName());
            TdHYGFStationYearGenerate.setStationState(jpStation.getState());

            if (ObjectUtils.isEmpty(TdHYGFStationYearGenerate.getCreatedTime())) {
                TdHYGFStationYearGenerate.setCreatedTime(System.currentTimeMillis());
                TdHYGFStationYearGenerateMapper.insert(TdHYGFStationYearGenerate);
            } else {
                TdHYGFStationYearGenerateMapper.insert(TdHYGFStationYearGenerate);
            }
            //户用场站年发电量
            TdHYGFStationAllGenerate TdHYGFStationAllGenerate = TdHYGFStationAllGenerateMapper.selectOne(new QueryWrapper<TdHYGFStationAllGenerate>()
                    .eq("third_station_id", jpStation.getThirdStationId())
                    .eq("year_time", DateUtil.format(today1, "yyyy"))
                    .eq("year", DateUtil.format(today1, "yyyy")));
            if (ObjectUtils.isEmpty(TdHYGFStationAllGenerate)) {
                TdHYGFStationAllGenerate = new TdHYGFStationAllGenerate();
            }
            TdHYGFStationAllGenerate.setThirdStationId(jpStation.getThirdStationId());
            TdHYGFStationAllGenerate.setYearTime(DateUtil.format(today1, "yyyy"));
            TdHYGFStationAllGenerate.setYear(DateUtil.format(today1, "yyyy"));
            TdHYGFStationAllGenerate.setGenerate(jpStation.getYearGenerate());
            TdHYGFStationAllGenerate.setFullhour(jpStation.getYearGenerate() / jpStation.getCapacity());
            TdHYGFStationAllGenerate.setIncome(jpStation.getYearIncome());
            //新加
            TdHYGFStationAllGenerate.setAmosCompanyCode(jpStation.getAmosCompanyCode());
            TdHYGFStationAllGenerate.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
            TdHYGFStationAllGenerate.setStationName(jpStation.getName());
            TdHYGFStationAllGenerate.setStationState(jpStation.getState());

            if (ObjectUtils.isEmpty(TdHYGFStationAllGenerate.getCreatedTime())) {
                TdHYGFStationAllGenerate.setCreatedTime(System.currentTimeMillis());
                TdHYGFStationAllGenerateMapper.insert(TdHYGFStationAllGenerate);
            } else {
                TdHYGFStationAllGenerateMapper.insert(TdHYGFStationAllGenerate);
            }
        }
        this.inverterDetail(result4);
        logger.info("-------华为同步电站详情结束" + ts + "------- " + sdf.format(new Date()));
    }


    @Scheduled(cron = "${dataRequstScheduled.huawei}")
    @Override
    @Async
    public void collectorList() {
    	long ts = System.currentTimeMillis();
    	logger.info("-------华为同步采集器/逆变器开始" + ts + "------- " + sdf.format(new Date()));
        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("通信模块");
                //更新时间
                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());
                jpCollector.setRecDate(new Date());
                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);
            }
        }


        this.inverterList(result);
    	logger.info("-------华为同步采集器/逆变器结束" + ts + "------- " + sdf.format(new Date()));
    }

    @Override
    public void collectorDetail() {

    }


    // @Scheduled(cron = "${dataRequstScheduled.huawei}")
    @Override
    public void inverterList(List<ImasterCollectorList> result) {
        // 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);

            ImasterCollectorList da = result.get(j);

            ImasterInverterList imasterInverterList = new ImasterInverterList();
            BeanUtils.copyProperties(da, imasterInverterList);
            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<ImasterInverterListDetails> result) {
        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
        );
        Double active_power = 0.0;
        String third_station_id = null;
        for (int j = 0; j < result.size(); j++) {

            ImasterInverterListDetails inverterDetailDto = result.get(j);

            active_power = active_power + (inverterDetailDto.getActive_power() != null ? inverterDetailDto.getActive_power() : 0.0);

            //获取所有逆变器实时功率总和
            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);
            third_station_id = imasterInverterList.getStationCode();
            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.setCapacity(ImasterConstant.Capacity.get(imasterInverterList.getDevName()));
            jpInverter.setSnCode(imasterInverterList.getEsnCode().trim());
            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());
            jpInverter.setCurrentPower(inverterDetailDto.getActive_power());
            jpInverter.setName(imasterInverterList.getDevName().trim());
            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());
            jpInverter.setRecDate(new Date());
            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(jpInverter.getSnCode().trim());
            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);
            }

            //-----------------------户用光伏日报表----------------------
            TdHYGFInverterDayGenerate tdHYGFInverterDayGenerate = new TdHYGFInverterDayGenerate();
            tdHYGFInverterDayGenerate.setCreatedTime(System.currentTimeMillis());
            tdHYGFInverterDayGenerate.setThirdStationId(jpInverter.getThirdStationId());
            tdHYGFInverterDayGenerate.setSnCode(jpInverter.getSnCode());
            tdHYGFInverterDayGenerate.setName(jpInverter.getName());
            tdHYGFInverterDayGenerate.setWorkStatus(jpInverter.getState());
            //交流电压
            tdHYGFInverterDayGenerate.setDcv1(jpInverterElectricityR.getVoltage());
            tdHYGFInverterDayGenerate.setDcv2(jpInverterElectricityB.getVoltage());
            tdHYGFInverterDayGenerate.setDcv3(jpInverterElectricityC.getVoltage());
            //交流电流
//                tdHYGFInverterDayGenerate.setDcv4(inverterDetailDto.getUAc4());
            tdHYGFInverterDayGenerate.setDcc1(jpInverterElectricityR.getCurrent());
            tdHYGFInverterDayGenerate.setDcc2(jpInverterElectricityB.getCurrent());
            tdHYGFInverterDayGenerate.setDcc3(jpInverterElectricityC.getCurrent());
//                tdHYGFInverterDayGenerate.setDcc4(inverterDetailDto.getIAc4());
            //直流电压
            tdHYGFInverterDayGenerate.setAcv1(Double.valueOf(hanlderResult.get("pv1_u").toString()));
            tdHYGFInverterDayGenerate.setAcv2(Double.valueOf(hanlderResult.get("pv2_u").toString()));
            tdHYGFInverterDayGenerate.setAcv3(Double.valueOf(hanlderResult.get("pv3_u").toString()));
            tdHYGFInverterDayGenerate.setAcv4(Double.valueOf(hanlderResult.get("pv4_u").toString()));
            //直流电流
            tdHYGFInverterDayGenerate.setAcc1(Double.valueOf(hanlderResult.get("pv1_i").toString()));
            tdHYGFInverterDayGenerate.setAcc2(Double.valueOf(hanlderResult.get("pv2_i").toString()));
            tdHYGFInverterDayGenerate.setAcc3(Double.valueOf(hanlderResult.get("pv3_i").toString()));
            tdHYGFInverterDayGenerate.setAcc4(Double.valueOf(hanlderResult.get("pv4_i").toString()));

            tdHYGFInverterDayGenerate.setPv1(null);
            tdHYGFInverterDayGenerate.setPv2(null);
            tdHYGFInverterDayGenerate.setPv3(null);
            tdHYGFInverterDayGenerate.setPv4(null);
            //功率
            tdHYGFInverterDayGenerate.setTotalPower(jpInverter.getCurrentPower());
            //频率
            tdHYGFInverterDayGenerate.setFrequency(String.valueOf(inverterDetailDto.getElec_freq()));
            //功率因数
            tdHYGFInverterDayGenerate.setPowerFactor(inverterDetailDto.getPower_factor());
            tdHYGFInverterDayGenerate.setDayGen(jpInverter.getDayPowerGeneration());
            tdHYGFInverterDayGenerate.setMonthGen(jpInverter.getMonthPowerGeneration());
            tdHYGFInverterDayGenerate.setYearGen(jpInverter.getYearPowerGeneration());
            tdHYGFInverterDayGenerate.setTotalGen(jpInverter.getTotalPowerGeneration());
            tdHYGFInverterDayGenerate.setIgbtTemp(inverterDetailDto.getTemperature());
            tdHYGFInverterDayGenerate.setIncome(null);
            tdHYGFInverterDayGenerate.setFullhour(jpInverter.getDayPowerGeneration() / jpInverter.getCapacity());
            //电站区域经销商，
            JpStation jpStation = jpStationMapper.selectOne(new QueryWrapper<JpStation>().
                    eq("third_code",PVProducerInfoEnum.HUAWEI.getCode()).
                    eq("third_station_id", String.valueOf(jpInverter.getThirdStationId())));

            if(jpStation!=null){
                tdHYGFInverterDayGenerate.setAmosCompanyCode(jpStation.getAmosCompanyCode());
                tdHYGFInverterDayGenerate.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
                tdHYGFInverterDayGenerate.setStationName(jpStation.getName());
                tdHYGFInverterDayGenerate.setStationState(jpStation.getState());

            }

            tdHYGFInverterDayGenerateMapper.insert(tdHYGFInverterDayGenerate);
            //户用场站月发电量
            Date today1 = new Date();
            TdHYGFInverterMonthGenerate tdHYGFInverterMonthGenerate = tdHYGFInverterMonthGenerateMapper.selectOne(new QueryWrapper<TdHYGFInverterMonthGenerate>()
                    .eq("third_station_id", jpInverter.getThirdStationId())
                    .eq("sn_code", jpInverter.getSnCode())
                    .eq("day_time", DateUtil.format(today1, "yyyy-MM-dd"))
                    .eq("year_month", DateUtil.format(today1, "yyyy-MM")));
            if (ObjectUtils.isEmpty(tdHYGFInverterMonthGenerate)) {
                tdHYGFInverterMonthGenerate = new TdHYGFInverterMonthGenerate();
            }
            tdHYGFInverterMonthGenerate.setThirdStationId(jpInverter.getThirdStationId());
            tdHYGFInverterMonthGenerate.setSnCode(jpInverter.getSnCode().trim());
            tdHYGFInverterMonthGenerate.setDayTime(DateUtil.format(today1, "yyyy-MM-dd"));
            tdHYGFInverterMonthGenerate.setYearMonth(DateUtil.format(today1, "yyyy-MM"));
            tdHYGFInverterMonthGenerate.setGenerate(jpInverter.getDayPowerGeneration());
            tdHYGFInverterMonthGenerate.setFullhour(jpInverter.getDayPowerGeneration() / jpInverter.getCapacity());
            tdHYGFInverterMonthGenerate.setName(jpInverter.getName());

            //新加
            if(jpStation!=null){
                tdHYGFInverterMonthGenerate.setAmosCompanyCode(jpStation.getAmosCompanyCode());
                tdHYGFInverterMonthGenerate.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
                tdHYGFInverterMonthGenerate.setStationName(jpStation.getName());
                tdHYGFInverterMonthGenerate.setStationState(jpStation.getState());

            }

            if (ObjectUtils.isEmpty(tdHYGFInverterMonthGenerate.getCreatedTime())) {
                tdHYGFInverterMonthGenerate.setCreatedTime(System.currentTimeMillis());
                tdHYGFInverterMonthGenerateMapper.insert(tdHYGFInverterMonthGenerate);
            } else {
                tdHYGFInverterMonthGenerateMapper.insert(tdHYGFInverterMonthGenerate);
            }
            //户用场站年发电量
            TdHYGFInverterYearGenerate tdHYGFInverterYearGenerate = tdHYGFInverterYearGenerateMapper.selectOne(new QueryWrapper<TdHYGFInverterYearGenerate>()
                    .eq("third_station_id", jpInverter.getThirdStationId())
                    .eq("sn_code", jpInverter.getSnCode())
                    .eq("month_time", DateUtil.format(today1, "yyyy-MM"))
                    .eq("year", DateUtil.format(today1, "yyyy")));
            if (ObjectUtils.isEmpty(tdHYGFInverterYearGenerate)) {
                tdHYGFInverterYearGenerate = new TdHYGFInverterYearGenerate();
            }
            tdHYGFInverterYearGenerate.setThirdStationId(jpInverter.getThirdStationId());
            tdHYGFInverterYearGenerate.setSnCode(jpInverter.getSnCode().trim());
            tdHYGFInverterYearGenerate.setMonthTime(DateUtil.format(today1, "yyyy-MM"));
            tdHYGFInverterYearGenerate.setYear(DateUtil.format(today1, "yyyy"));
            tdHYGFInverterYearGenerate.setGenerate(jpInverter.getMonthPowerGeneration());
            tdHYGFInverterYearGenerate.setFullhour(jpInverter.getMonthPowerGeneration() / jpInverter.getCapacity());
            tdHYGFInverterYearGenerate.setName(jpInverter.getName());

            //新加
            if(jpStation!=null){
                tdHYGFInverterYearGenerate.setAmosCompanyCode(jpStation.getAmosCompanyCode());
                tdHYGFInverterYearGenerate.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
                tdHYGFInverterYearGenerate.setStationName(jpStation.getName());
                tdHYGFInverterYearGenerate.setStationState(jpStation.getState());

            }

            if (ObjectUtils.isEmpty(tdHYGFInverterYearGenerate.getCreatedTime())) {
                tdHYGFInverterYearGenerate.setCreatedTime(System.currentTimeMillis());
                tdHYGFInverterYearGenerateMapper.insert(tdHYGFInverterYearGenerate);
            } else {
                tdHYGFInverterYearGenerateMapper.insert(tdHYGFInverterYearGenerate);
            }
            //户用场站年发电量
            TdHYGFInverterTotalGenerate tdHYGFInverterTotalGenerate = tdHYGFInverterTotalGenerateMapper.selectOne(new QueryWrapper<TdHYGFInverterTotalGenerate>()
                    .eq("third_station_id", jpInverter.getThirdStationId())
                    .eq("sn_code", jpInverter.getSnCode())
                    .eq("year_time", DateUtil.format(today1, "yyyy"))
                    .eq("year", DateUtil.format(today1, "yyyy")));
            if (ObjectUtils.isEmpty(tdHYGFInverterTotalGenerate)) {
                tdHYGFInverterTotalGenerate = new TdHYGFInverterTotalGenerate();
            }
            tdHYGFInverterTotalGenerate.setThirdStationId(jpInverter.getThirdStationId());
            tdHYGFInverterTotalGenerate.setSnCode(jpInverter.getSnCode().trim());
            tdHYGFInverterTotalGenerate.setYearTime(DateUtil.format(today1, "yyyy"));
            tdHYGFInverterTotalGenerate.setYear(DateUtil.format(today1, "yyyy"));
            tdHYGFInverterTotalGenerate.setGenerate(jpInverter.getYearPowerGeneration());
            tdHYGFInverterTotalGenerate.setFullhour(jpInverter.getYearPowerGeneration() / jpInverter.getCapacity());
            tdHYGFInverterTotalGenerate.setName(jpInverter.getName());
            //新加
            if(jpStation!=null){
                tdHYGFInverterTotalGenerate.setAmosCompanyCode(jpStation.getAmosCompanyCode());
                tdHYGFInverterTotalGenerate.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
                tdHYGFInverterTotalGenerate.setStationName(jpStation.getName());
                tdHYGFInverterTotalGenerate.setStationState(jpStation.getState());

            }
            if (ObjectUtils.isEmpty(tdHYGFInverterTotalGenerate.getCreatedTime())) {
                tdHYGFInverterTotalGenerate.setCreatedTime(System.currentTimeMillis());
                tdHYGFInverterTotalGenerateMapper.insert(tdHYGFInverterTotalGenerate);
            } else {
                tdHYGFInverterTotalGenerateMapper.insert(tdHYGFInverterTotalGenerate);
            }
        }
//        JpStation jpStation1 = jpStationMapper.selectOne(new QueryWrapper<JpStation>().
//                eq("third_code", PVProducerInfoEnum.HUAWEI.getCode()).
//                eq("third_station_id",third_station_id));
//
//        jpStation1.setRealTimePower(active_power);
//        jpStationMapper.updateById(jpStation1);
    }

    @Scheduled(cron = "${dataRequstScheduled.huawei}")
    @Override
    @Async
    public void inverAlramInfo() {
    	long ts = System.currentTimeMillis();
    	logger.info("-------华为同步告警开始" + ts + "------- " + sdf.format(new Date()));
        List<String> inverterSns = imasterInverterListMapper.getCollectIds();
        if (CollectionUtil.isEmpty(inverterSns)){
            logger.warn("-------没有逆变器，跳过告警-------");
            return;
        }
        //   for (int i = 0; i < inverterSns.size(); i++) {
//            try {
//                TimeUnit.MINUTES.sleep(3);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
        HashMap<String, Object> requestInfo = new HashMap<>();
        // 获取今天的日期
        LocalDate today = LocalDate.now();
        // 将 LocalDate 转换为 LocalDateTime，设置时间为零点
        LocalDateTime midnight = today.atStartOfDay();
        // 将 LocalDateTime 转换为 Date
        Date date = Date.from(midnight.atZone(ZoneId.systemDefault()).toInstant());

        // 获取今天零点的时间戳（毫秒）
        long todayTimestamp = date.getTime();
        requestInfo.put("sns", inverterSns.stream().collect(Collectors.joining(",")));
        requestInfo.put("language", "zh_CN");
        requestInfo.put("devTypes", "1");
        requestInfo.put("beginTime", todayTimestamp);
        requestInfo.put("endTime", System.currentTimeMillis());
        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.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.setRecoverTime(null);
                hygfjpInverterWarn.setTimeLong(null);


                //电站区域经销商，
                JpStation jpStation = jpStationMapper.selectOne(new QueryWrapper<JpStation>().
                        eq("third_code", PVProducerInfoEnum.HUAWEI.getCode()).
                        eq("third_station_id", String.valueOf(alarmDto.getStationCode())));

                if(jpStation!=null){
                    hygfjpInverterWarn.setAmosCompanyCode(jpStation.getAmosCompanyCode());
                    hygfjpInverterWarn.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
                    hygfjpInverterWarn.setStationName(jpStation.getName());
                    hygfjpInverterWarn.setStationState(jpStation.getState());

                }


                hygfjpInverterWarn.setState(ImasterConstant.alarmstatus.get(alarmDto.getStatus().toString()));
                if (ObjectUtils.isEmpty(hygfjpInverterWarn.getCreatedTime())) {
                    hygfjpInverterWarn.setCreatedTime(System.currentTimeMillis());
                    hygfjpInverterWarnMapper.insert(hygfjpInverterWarn);
                } else {
                    hygfjpInverterWarnMapper.insert(hygfjpInverterWarn);
                }
            }
        }
        // }
    	logger.info("-------华为同步告警结束" + ts + "------- " + sdf.format(new Date()));
    }
}
