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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapBuilder;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.api.householdapi.Utils.RedisUtils;
import com.yeejoin.amos.api.householdapi.Utils.TanYinApiUtils;
import com.yeejoin.amos.api.householdapi.constant.TanYinConstant;
import com.yeejoin.amos.api.householdapi.face.dto.SunlightDto;
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.HYGFJPDayPower;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.HYGFJPInverterElecHistory;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.HYGFJPInverterHistory;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.HYGFJPInverterWarn;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.HYGFJPStationPowerHistory;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.TanYinAlramInfo;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.TanYinCustomerInfo;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.TanYinInveterInfo;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.TanYinStationInfo;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.TdHYGFInverterDayGenerate;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.TdHYGFInverterMonthGenerate;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.TdHYGFInverterTotalGenerate;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.TdHYGFInverterYearGenerate;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.TdHYGFStationAllGenerate;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.TdHYGFStationMonthGenerate;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.tdeingine.TdHYGFStationYearGenerate;
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.HYGFJPCollectorHistoryMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.HYGFJPDayPowerMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.HYGFJPInverterElecHistoryMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.HYGFJPInverterHistoryMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.HYGFJPInverterWarnMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.HYGFJPStationPowerHistoryMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TanYinAlramInfoMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TanYinCustomerInfoMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TanYinInveterInfoMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TanYinStationInfoMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TdHYGFInverterDayGenerateMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TdHYGFInverterMonthGenerateMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TdHYGFInverterTotalGenerateMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TdHYGFInverterYearGenerateMapper;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TdJpStationMapper;
import com.yeejoin.amos.api.householdapi.face.service.TanYinDataAcquisitionService;
import com.yeejoin.amos.openapi.enums.PVProducerInfoEnum;
import fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 碳银业务类
 * <p>
 * ProjectName: amos-boot-zx-biz
 * PackageName: com.yeejoin.amos.api.householdapi.face.service.impl
 *
 * @author yangyang
 * @version v1.0
 * @date 2024/7/15 10:15
 */
@Component
@Slf4j
public class TanYinDataAcquisitionServiceImpl implements TanYinDataAcquisitionService {

    @Value ("${tanYin.api.apiUrl:}")
    private String apiUrl;

    @Resource (type = TanYinApiUtils.class)
    private TanYinApiUtils tanYinApiUtils;

    @Resource (type = TanYinCustomerInfoMapper.class)
    private TanYinCustomerInfoMapper tanYinCustomerInfoMapper;

    @Resource (type = TanYinStationInfoMapper.class)
    private TanYinStationInfoMapper tanYinStationInfoMapper;

    @Resource (type = TanYinInveterInfoMapper.class)
    private TanYinInveterInfoMapper tanYinInveterInfoMapper;

    @Resource (type = TanYinAlramInfoMapper.class)
    private TanYinAlramInfoMapper tanYinAlramInfoMapper;

    @Autowired
    private JpStationMapper jpStationMapper;

    @Autowired
    private HYGFJPStationPowerHistoryMapper hygfjpStationPowerHistoryMapper;

    @Autowired
    private HYGFJPInverterHistoryMapper hygfjpInverterHistoryMapper;

    @Autowired
    private HYGFJPCollectorHistoryMapper hygfjpCollectorHistoryMapper;

    @Autowired
    private HYGFJPInverterWarnMapper hygfjpInverterWarnMapper;

    @Autowired
    private HYGFJPInverterElecHistoryMapper hygfjpInverterElecHistoryMapper;

    @Autowired
    private HYGFJPDayPowerMapper hygfjpDayPowerMapper;

    @Autowired
    private JpCollectorMapper jpCollectorMapper;

    @Autowired
    private JpInverterMapper jpInverterMapper;

    @Autowired
    private JpInverterElectricityMapper jpInverterElectricityMapper;

    @Autowired
    private TdHYGFInverterDayGenerateMapper tdHYGFInverterDayGenerateMapper;

    @Autowired
    private TdHYGFInverterMonthGenerateMapper tdHYGFInverterMonthGenerateMapper;

    @Autowired
    private TdHYGFInverterYearGenerateMapper tdHYGFInverterYearGenerateMapper;

    @Autowired
    private com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TdHYGFStationMonthGenerateMapper TdHYGFStationMonthGenerateMapper;

    @Autowired
    private com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TdHYGFStationYearGenerateMapper TdHYGFStationYearGenerateMapper;

    @Autowired
    private com.yeejoin.amos.api.householdapi.face.orm.mapper.tdengine.TdHYGFStationAllGenerateMapper TdHYGFStationAllGenerateMapper;

    @Autowired
    private TdHYGFInverterTotalGenerateMapper tdHYGFInverterTotalGenerateMapper;

    @Autowired
    private TdJpStationMapper tdJpStationMapper;

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

    private final static String pageNo = "1";

    private final static String pageSize = "999";
    @Autowired
    private HouseholdPvApiServiceImpl householdPvApiService;
    /**
     * 每隔 10分钟通过并网时间段同步碳银对应范围内的项目信息
     *
     * @param
     * @return {@link }
     * @throws
     * @author yangyang
     * @date 2024/7/17 13:56
     */
    @Scheduled (cron = "${dataRequestScheduled.tanYin}")
    @Override
    public void customerInfoList() {
        try {
            String startDate = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String endDate = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            log.info("-------碳银同步项目信息开始: {} ------- ", sdf.format(new Date()));
            Map<String, Object> params = MapBuilder.<String, Object>create()
                                                   .put("pageNo", pageNo)
                                                   .put("pageSize", pageSize)// 每页行数
                                                   .put("startDate", startDate)// 开始时间 YYYY-MM-dd
                                                   .put("endDate", endDate)// 结束时间 YYYY-MM-dd
                                                   .build();
            PageInfo<TanYinCustomerInfo> tanYinCustomerInfos = tanYinApiUtils.postPage("客户信息", apiUrl + TanYinConstant.customerInfoUrl, JSON.toJSONString(params), null, TanYinCustomerInfo.class);
            if (tanYinCustomerInfos == null || CollectionUtils.isEmpty(tanYinCustomerInfos.getList())) {
                log.warn("-------碳银同步项目信息结束: 未获取到项目信息 ------- ");
                return;
            }
            for (TanYinCustomerInfo tanYinCustomerInfo : tanYinCustomerInfos.getList()) {
                TanYinCustomerInfo oldTanYinCustomerInfo = tanYinCustomerInfoMapper.selectOne(new QueryWrapper<TanYinCustomerInfo>().eq("project_no", tanYinCustomerInfo.getProjectNo()).eq("customer_id_no", tanYinCustomerInfo.getCustomerIdNo()).eq("customer_phone", tanYinCustomerInfo.getCustomerPhone()).orderByDesc("create_time").last("limit 1"));
                if (oldTanYinCustomerInfo == null) {
                    tanYinCustomerInfo.setCreateTime(System.currentTimeMillis());
                    tanYinCustomerInfoMapper.insert(tanYinCustomerInfo);
                } else {
                    tanYinCustomerInfo.setCreateTime(oldTanYinCustomerInfo.getCreateTime());
                    tanYinCustomerInfoMapper.insert(tanYinCustomerInfo);
                }
            }
            log.info("-------碳银同步项目信息结束: {} ------- ", sdf.format(new Date()));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("-------碳银同步项目信息异常: {} ------- ", e);
        }
    }

    /**
     * 每隔 10分钟通过项目编号同步碳银对应电站信息
     *
     * @param
     * @return {@link }
     * @throws
     * @author yangyang
     * @date 2024/7/17 13:57
     */
    @Scheduled (cron = "${dataRequestScheduled.tanYin}")
    @Async
    @Override
    public void stationList() {
        long ts = System.currentTimeMillis();
        log.info("-------碳银同步电站开始: {} ------- ", ts);
        List<String> projectNos = tanYinCustomerInfoMapper.listProjectNo();
        String powerDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (CollectionUtils.isEmpty(projectNos)) {
            log.warn("-------碳银同步电站结束: 未同步到项目信息 -------");
            return;
        }
        List<List<String>> projectNoLists = ListUtil.partition(projectNos, 200);// 每次最多 200个
        List<TanYinStationInfo> tanYinStationInfos = new ArrayList<>();
        for (List<String> projectNoList : projectNoLists) {
            Map<String, Object> params = MapBuilder.<String, Object>create().put("projectNoList", projectNoList).put("powerDate", powerDate).build();
            List<TanYinStationInfo> tanYinStationInfoList = tanYinApiUtils.post("电站基本信息", apiUrl + TanYinConstant.stationListUrl, params, null, TanYinStationInfo.class);
            if (!CollectionUtils.isEmpty(tanYinStationInfoList)) {
                tanYinStationInfos.addAll(tanYinStationInfoList);
            }
        }
        if (CollectionUtils.isEmpty(tanYinStationInfos)) {
            log.warn("-------碳银同步电站结束: 未同步到电站基本信息 -------");
            return;
        }
        List<String> stationIds = tanYinStationInfos.stream().map(TanYinStationInfo::getProjectNo).collect(Collectors.toList());
        //删除多余的场站
        deleteTyMessage(stationIds);
        List<JpStation> jpStations = jpStationMapper.selectList(new QueryWrapper<JpStation>().eq("third_code", PVProducerInfoEnum.TANYIN.getCode()).in("third_station_id", stationIds));
        Map<String, JpStation> jpStationMap = jpStations.stream().collect(Collectors.toMap(JpStation::getThirdStationId, Function.identity()));

        List<TanYinInveterInfo> tanYinInveterInfos = new ArrayList();

        for (TanYinStationInfo tanYinStationInfo : tanYinStationInfos) {
            tanYinStationInfo.setCreateTime(System.currentTimeMillis());
            tanYinStationInfoMapper.insert(tanYinStationInfo);

            List<TanYinStationInfo.InverterListDTO> inverterList = tanYinStationInfo.getInverterList();
            for (TanYinStationInfo.InverterListDTO inverterListDTO : inverterList) {
                TanYinInveterInfo tanYinInveterInfo = new TanYinInveterInfo();
                tanYinInveterInfo.setProjectNo(tanYinStationInfo.getProjectNo());
                tanYinInveterInfo.setDeviceName(inverterListDTO.getDeviceName());
                tanYinInveterInfo.setSn(inverterListDTO.getSn());
                tanYinInveterInfo.setSupplier(inverterListDTO.getSupplier());
                tanYinInveterInfo.setCreateTime(System.currentTimeMillis());
                tanYinInveterInfos.add(tanYinInveterInfo);
            }

            String stationId = tanYinStationInfo.getProjectNo();
            JpStation jpStation = jpStationMap.get(stationId);
            // 给户用光伏存储的数据赋值
            if (ObjectUtils.isEmpty(jpStation)) {
                jpStation = new JpStation();
            }
            jpStation.setCapacity(Double.valueOf(tanYinStationInfo.getCapacitySize()));// 装机容量
            jpStation.setAddress(tanYinStationInfo.getProvince() + tanYinStationInfo.getCity() + tanYinStationInfo.getArea() + tanYinStationInfo.getCompleteAddress());
            jpStation.setLongitude(tanYinStationInfo.getLongitude());
            jpStation.setLatitude(tanYinStationInfo.getLatitude());
            jpStation.setUserName(tanYinStationInfo.getCustomerName());
            jpStation.setUserPhone(String.valueOf(tanYinStationInfo.getCustomerPhone()));
            jpStation.setStationContact(tanYinStationInfo.getProvince() + tanYinStationInfo.getCity() + tanYinStationInfo.getArea() + tanYinStationInfo.getCompleteAddress());
            jpStation.setName(tanYinStationInfo.getCustomerName());
            jpStation.setThirdCode(PVProducerInfoEnum.TANYIN.getCode());
            jpStation.setThirdStationId(tanYinStationInfo.getProjectNo());
            jpStation.setDayGenerate(Double.parseDouble(tanYinStationInfo.getDayPower()));
            jpStation.setMonthGenerate(Double.parseDouble(tanYinStationInfo.getMonthPower()));
            jpStation.setYearGenerate(Double.parseDouble(tanYinStationInfo.getYearPower()));
            jpStation.setAccumulatedPower(Double.parseDouble(tanYinStationInfo.getTotalPower()));
            // 并网类型
            // jpStation.setSnCode(golangStationDetail.getNmicode());
            jpStation.setPrice(0.45);
            // jpStation.setModuleCount(ObjectUtils.isEmpty(Math.toIntExact(golangStationDetail.getModule())) ? 0 : Math.toIntExact(golangStationDetail.getModule()));
            jpStation.setOnGridType(TanYinConstant.intoNetWorkStatus.get("0")); // 没有该字段默认写死
            // 去tanyin_customer_info 查询并网时间
            TanYinCustomerInfo tanYinCustomerInfo = tanYinCustomerInfoMapper.selectOne(new QueryWrapper<TanYinCustomerInfo>().eq("project_no", tanYinStationInfo.getProjectNo()).eq("customer_id_no", tanYinStationInfo.getCustomerIdNo()).eq("customer_phone", tanYinStationInfo.getCustomerPhone()).orderByDesc("create_time").last(" limit 1"));
            // 收益 = 发电量 * 0.45 @wujiang 确认过
            jpStation.setOnGridTime(tanYinCustomerInfo != null ? new Date(tanYinCustomerInfo.getElectricContractPass()) : null);
            jpStation.setDayIncome(tanYinStationInfo.getDayPower() != null ? Double.parseDouble(tanYinStationInfo.getDayPower()) * 0.45 : 0.0);
            jpStation.setMonthIncome(tanYinStationInfo.getMonthPower() != null ? Double.parseDouble(tanYinStationInfo.getMonthPower()) * 0.45 : 0.0);
            jpStation.setYearIncome(tanYinStationInfo.getYearPower() != null ? Double.parseDouble(tanYinStationInfo.getYearPower()) * 0.45 : 0.0);
            jpStation.setCumulativeIncome(tanYinStationInfo.getTotalPower() != null ? Double.parseDouble(tanYinStationInfo.getTotalPower()) * 0.45 : 0.0);
            jpStation.setArea(tanYinStationInfo.getArea());
            jpStation.setState("在线");
            // jpStation.setEmail();
            // jpStation.setCreateTime();
            // jpStation.setRatedPower();
            jpStation.setType("家庭户用");
            jpStation.setRecDate(new Date());
            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(Double.parseDouble(tanYinStationInfo.getTotalPower()));
            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);

            String today = DateUtil.today();
            String hour = new Date().getHours() + ":00";
            HYGFJPDayPower hygfjpDayPower = hygfjpDayPowerMapper.selectOne(
                    new QueryWrapper<HYGFJPDayPower>().eq("third_station_id", stationId)
                                                      .eq("year_month_day", today).eq("hour", hour));
            if (ObjectUtils.isEmpty(hygfjpDayPower)) {
                hygfjpDayPower = new HYGFJPDayPower();
            }
            hygfjpDayPower.setThirdStationId(stationId);
            hygfjpDayPower.setHour(hour);
            hygfjpDayPower.setYearMonthDay(today);
            hygfjpDayPower.setPower(jpStation.getRealTimePower());
            // 新加
            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", stationId).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(stationId);
            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", stationId).eq("month_time", DateUtil.format(today1, "yyyy-MM")).eq("year", DateUtil.format(today1, "yyyy")));
            if (ObjectUtils.isEmpty(TdHYGFStationYearGenerate)) {
                TdHYGFStationYearGenerate = new TdHYGFStationYearGenerate();
            }
            TdHYGFStationYearGenerate.setThirdStationId(stationId);
            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", stationId).eq("year_time", DateUtil.format(today1, "yyyy")).eq("year", DateUtil.format(today1, "yyyy")));
            if (ObjectUtils.isEmpty(TdHYGFStationAllGenerate)) {
                TdHYGFStationAllGenerate = new TdHYGFStationAllGenerate();
            }
            TdHYGFStationAllGenerate.setThirdStationId(stationId);
            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);
            }
        }

        log.info("-------碳银同步电站结束: {} ------- " + ts + "------- " + sdf.format(new Date()));

        log.info("-------碳银同步逆变器开始: {} ------- " + ts + "------- " + sdf.format(new Date()));
        inverterList(tanYinInveterInfos);
        log.info("-------碳银同步逆变器结束: {} ------- " + ts + "------- " + sdf.format(new Date()));

    }

    private void deleteTyMessage(List<String> stationIds) {
        // 所有场站信息
        if(CollectionUtil.isNotEmpty(stationIds)){
            //场站
            QueryWrapper<JpStation> wrapper = new QueryWrapper<JpStation>().eq("third_code", PVProducerInfoEnum.TANYIN.getCode());
            List<JpStation> jpStations = jpStationMapper.selectList(wrapper);
            if(CollectionUtil.isNotEmpty(jpStations)){
                for (JpStation jpStation : jpStations) {
                    if(!stationIds.contains(jpStation.getThirdStationId())){
                        //删除多余数据
                        jpStationMapper.deleteById(jpStation.getSequenceNbr());
                    }
                }
            }
            //采集器
            QueryWrapper<JpCollector> wrapper1 = new QueryWrapper<JpCollector>().eq("third_code", PVProducerInfoEnum.TANYIN.getCode());
            List<JpCollector> jpCollectors = jpCollectorMapper.selectList(wrapper1);
            if(CollectionUtil.isNotEmpty(jpCollectors)){
                for (JpCollector jpCollector : jpCollectors) {
                    if(!stationIds.contains(jpCollector.getThirdStationId())){
                        //删除多余数据
                        jpCollectorMapper.deleteById(jpCollector.getSequenceNbr());
                    }
                }
            }
            //逆变器
            QueryWrapper<JpInverter> wrapper2 = new QueryWrapper<JpInverter>().eq("third_code", PVProducerInfoEnum.TANYIN.getCode());
            List<JpInverter> jpInverters = jpInverterMapper.selectList(wrapper2);
            if(CollectionUtil.isNotEmpty(jpInverters)){
                for (JpInverter jpInverter : jpInverters) {
                    if(!stationIds.contains(jpInverter.getThirdStationId())){
                        //删除多余数据
                        jpInverterMapper.deleteById(jpInverter.getSequenceNbr());
                    }
                }
            }
        }
    }

    @Override
    public void inverterList() {

    }

    @Scheduled (cron = "${dataRequestScheduled.tanYin.warn}")
    @Override
    public void inverAlramInfo() {
        log.info("-------碳银同步逆变器告警开始: {} ------- ", sdf.format(new Date()));
        // region 先获取逆变器数据
        List<JpInverter> jpInverters = jpInverterMapper.selectList(new QueryWrapper<JpInverter>().eq("third_code", PVProducerInfoEnum.TANYIN.getCode()));
        if (CollectionUtils.isEmpty(jpInverters)) {
            log.warn("-------碳银同步逆变器告警结束: 未获取到逆变器信息 ------- ");
            return;
        }
        List<String> stationIds = jpInverters.stream().map(JpInverter::getThirdStationId).collect(Collectors.toList());
        List<JpStation> jpStations = jpStationMapper.selectList(new QueryWrapper<JpStation>().eq("third_code", PVProducerInfoEnum.TANYIN.getCode()).in("third_station_id", stationIds));
        Map<String, JpStation> jpStationMap = jpStations.stream().collect(Collectors.toMap(JpStation::getThirdStationId, Function.identity()));
        for (JpInverter inverter : jpInverters) {
            JpStation jpStation = jpStationMap.get(inverter.getThirdStationId());
            if (jpStation == null) {
                continue;
            }
            this.inverAlramInfo(inverter, jpStation);
        }
        log.info("-------碳银同步逆变器告警结束: {} ------- ", sdf.format(new Date()));
    }

    @Async
    public void inverAlramInfo(JpInverter jpInverter, JpStation jpStation) {
        if (jpInverter == null || StringUtils.isEmpty(jpInverter.getSnCode())) {
            return;
        }
        String startDate;
        if (jpInverter.getUpdateTime() != null) {
            startDate = new SimpleDateFormat("yyyy-MM-dd").format(jpInverter.getUpdateTime());
        } else {
            startDate = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        String endDate = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Map<String, Object> params = MapBuilder.<String, Object>create()
                                               .put("sn", jpInverter.getSnCode())
                                               .put("pageNo", pageNo)
                                               .put("pageSize", pageSize)
                                               .put("startDate", startDate)
                                               .put("endDate", endDate).build();
        PageInfo<TanYinAlramInfo> tanYinInveterInfo = tanYinApiUtils.postPage("电站逆变器故障信息", apiUrl + TanYinConstant.inverterAlramUrl, JSON.toJSONString(params), null, TanYinAlramInfo.class);
        if (tanYinInveterInfo == null || CollectionUtils.isEmpty(tanYinInveterInfo.getList())) {
            log.warn("-------碳银同步电站逆变器故障信息结束: 未获取到逆变器故障信息 ------- ");
            return;
        }
        List<TanYinAlramInfo> tanYinAlramInfos = new ArrayList<>();
        tanYinAlramInfos.addAll(tanYinInveterInfo.getList());
        if (tanYinInveterInfo.getPages() > 1) {
            for (int pageNum = 2; pageNum < tanYinInveterInfo.getPages(); pageNum++) {
                params.put("pageNo", pageNum);
                PageInfo<TanYinAlramInfo> tanYinInveterInfoPage = tanYinApiUtils.postPage("电站逆变器故障信息", apiUrl + TanYinConstant.inverterAlramUrl, JSON.toJSONString(params), null, TanYinAlramInfo.class);
                tanYinAlramInfos.addAll(tanYinInveterInfoPage.getList());
            }
        }
        for (TanYinAlramInfo tanYinAlramInfo : tanYinAlramInfos) {
            tanYinAlramInfo.setCreateTime(System.currentTimeMillis());
            tanYinAlramInfoMapper.insert(tanYinAlramInfo);

            HYGFJPInverterWarn hygfjpInverterWarn = hygfjpInverterWarnMapper
                    .selectOne(new QueryWrapper<HYGFJPInverterWarn>().eq("sn_code", tanYinAlramInfo.getSn())
                                                                     .eq("warn_id", tanYinAlramInfo.getId())
                                                                     .eq("third_station_id", String.valueOf(tanYinAlramInfo.getProjectNo()))
                                                                     .orderByDesc("created_time").last("limit 1")
                    );
            if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isEmpty(hygfjpInverterWarn)) {
                hygfjpInverterWarn = new HYGFJPInverterWarn();
            }
            // 做查询
            hygfjpInverterWarn.setTime(System.currentTimeMillis());
            hygfjpInverterWarn.setSnCode(tanYinAlramInfo.getSn());
            hygfjpInverterWarn.setThirdStationId(jpStation.getThirdStationId());
            hygfjpInverterWarn.setLevel(tanYinAlramInfo.getLevel());
            hygfjpInverterWarn.setWarnId(tanYinAlramInfo.getId());
            hygfjpInverterWarn.setAmosCompanyCode(jpStation.getAmosCompanyCode());
            hygfjpInverterWarn.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
            hygfjpInverterWarn.setStationName(jpStation.getName());
            hygfjpInverterWarn.setStationState(jpStation.getState());
            hygfjpInverterWarn.setThirdCode(PVProducerInfoEnum.TANYIN.getCode());
            hygfjpInverterWarn.setContent(tanYinAlramInfo.getContent());
            hygfjpInverterWarn.setTreatment(tanYinAlramInfo.getSolution());
            hygfjpInverterWarn.setState(tanYinAlramInfo.getStatus());
            if (!ObjectUtils.isEmpty(tanYinAlramInfo.getFaultEndTime())) {
                Date faultEndTimeDt = Date.from(LocalDate.parse(tanYinAlramInfo.getFaultEndTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay(ZoneId.systemDefault()).toInstant());
                hygfjpInverterWarn.setRecoverTime(faultEndTimeDt.getTime());
            }
            if (!ObjectUtils.isEmpty(tanYinAlramInfo.getFaultOccurTime())) {
                Date faultOccurTimeDt = Date.from(LocalDate.parse(tanYinAlramInfo.getFaultOccurTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay(ZoneId.systemDefault()).toInstant());
                hygfjpInverterWarn.setStartTime(faultOccurTimeDt.getTime());
            }
            hygfjpInverterWarn.setTimeLong(null);
            if ((!ObjectUtils.isEmpty(tanYinAlramInfo.getFaultOccurTime())) && (!ObjectUtils.isEmpty(tanYinAlramInfo.getFaultEndTime()))) {
                hygfjpInverterWarn.setTimeLong(this.convertDate(hygfjpInverterWarn.getRecoverTime()) - this.convertDate(hygfjpInverterWarn.getStartTime()));
            }
            if (ObjectUtils.isEmpty(hygfjpInverterWarn.getCreatedTime())) {
                hygfjpInverterWarn.setCreatedTime(System.currentTimeMillis());
                hygfjpInverterWarnMapper.insert(hygfjpInverterWarn);
            } else {
                hygfjpInverterWarnMapper.insert(hygfjpInverterWarn);
            }
        }
    }


    public void inverterList(List<TanYinInveterInfo> tanYinInveterInfos) {
        if (CollectionUtils.isEmpty(tanYinInveterInfos)) {
            return;
        }
        List<String> stationIds = tanYinInveterInfos.stream().map(TanYinInveterInfo::getProjectNo).collect(Collectors.toList());
        List<JpStation> jpStations = jpStationMapper.selectList(new QueryWrapper<JpStation>().eq("third_code", PVProducerInfoEnum.TANYIN.getCode()).in("third_station_id", stationIds));
        Map<String, JpStation> jpStationMap = jpStations.stream().collect(Collectors.toMap(JpStation::getThirdStationId, Function.identity()));

        List<String> sns = tanYinInveterInfos.stream().map(TanYinInveterInfo::getSn).distinct().collect(Collectors.toList());
        List<List<String>> snLists = ListUtil.partition(sns, 200);// 最多 200 个
        JSONObject tanYinInveterInfoResultMap = new JSONObject();
        for (List<String> snList : snLists) {
            Map<String, Object> params = MapBuilder.<String, Object>create().put("snList", snList).build();
            JSONObject tanYinInveterInfoResult = tanYinApiUtils.post("电站逆变器信息", apiUrl + TanYinConstant.inverterListUrl, params, null, JSONObject.class);
            if (CollectionUtils.isEmpty(tanYinInveterInfoResult)) {
                continue;
            }
            tanYinInveterInfoResultMap.putAll(tanYinInveterInfoResult);
        }
        for (TanYinInveterInfo tanYinInveterInfo : tanYinInveterInfos) {
            // region 逆变器信息
            JSONObject tanYinInveterInfoResultJson = tanYinInveterInfoResultMap.getJSONObject(tanYinInveterInfo.getSn());
            //处理空指针问题
            if(Objects.isNull(tanYinInveterInfoResultJson)){
                continue;
            }
            TanYinInveterInfo tanYinInveterInfoDTO = tanYinInveterInfoResultJson.toJavaObject(TanYinInveterInfo.class);
            tanYinInveterInfoDTO.setProjectNo(tanYinInveterInfo.getProjectNo());
            tanYinInveterInfoDTO.setDeviceName(tanYinInveterInfo.getDeviceName());
            tanYinInveterInfoDTO.setSn(tanYinInveterInfo.getSn());
            tanYinInveterInfoDTO.setSupplier(tanYinInveterInfo.getSupplier());
            tanYinInveterInfoDTO.setCreateTime(System.currentTimeMillis());
            tanYinInveterInfoMapper.insert(tanYinInveterInfoDTO);
            // endregion
            JpInverter jpInverter = jpInverterMapper.selectOne(
                    new QueryWrapper<JpInverter>().eq("third_station_id", tanYinInveterInfo.getProjectNo())
                                                  .eq("third_code", PVProducerInfoEnum.TANYIN.getCode())
                                                  .eq("sn_code", tanYinInveterInfo.getSn()));
            if (org.springframework.util.ObjectUtils.isEmpty(jpInverter)) {
                jpInverter = new JpInverter();
            }
            jpInverter.setBrand(tanYinInveterInfoDTO.getSupplier().toString());
            jpInverter.setSnCode(tanYinInveterInfo.getSn());
            jpInverter.setId(tanYinInveterInfo.getIdString());
            jpInverter.setThirdStationId(tanYinInveterInfo.getProjectNo());
            jpInverter.setThirdCode(PVProducerInfoEnum.TANYIN.getCode());
            // 0、离线 1、在线 2、异常
            jpInverter.setState(TanYinConstant.stationStatus.get(tanYinInveterInfoDTO.getStatus()));
            jpInverter.setRecDate(new Date());
            jpInverter.setUpdateTime(tanYinInveterInfoDTO.getGmtCreate() != null ? new Date(Long.parseLong(tanYinInveterInfoDTO.getGmtCreate())) : new Date());
            JpStation jpStation = jpStationMap.get(tanYinInveterInfo.getProjectNo());
            if (jpStation != null) {
                if (!"离线".equals(jpStation.getState()) && !"异常".equals(jpStation.getState())) {
                    jpStation.setState(TanYinConstant.stationStatus.get(tanYinInveterInfoDTO.getStatus()));
                    jpStationMapper.updateById(jpStation);
                    jpStationMap.put(tanYinInveterInfo.getProjectNo(), jpStation);
                }
                // 逆变器没有就空着
                jpInverter.setMonthPowerGeneration(jpStation.getMonthGenerate());
                jpInverter.setYearPowerGeneration(jpStation.getYearGenerate());
                jpInverter.setStationName(jpStation.getName());
                jpInverter.setAddr(jpStation.getAddress());
                jpInverter.setCapacity(jpStation.getCapacity());
            }
            jpInverter.setCurrentPower(Double.parseDouble(tanYinInveterInfoDTO.getWatt()));
            jpInverter.setDayPowerGeneration(Double.parseDouble(tanYinInveterInfoDTO.getDailyEnergy()));
            jpInverter.setTotalPowerGeneration(Double.parseDouble(tanYinInveterInfoDTO.getTotalEnergy()));
            jpInverter.setModel(tanYinInveterInfoDTO.getDeviceName());
            jpInverter.setName(tanYinInveterInfoDTO.getDeviceName());
            if (!ObjectUtils.isEmpty(jpInverter.getSequenceNbr())) {
                jpInverterMapper.updateById(jpInverter);
            } else {
                jpInverterMapper.insert(jpInverter);
            }
            // region 解析电站逆变器信息
            // 确认先按照 vol1, amp1 这样入库
            for (int k = 0; k <= 15; k++) {
                String name = "vol" + k;
                JpInverterElectricity jpInverterElectricity = jpInverterElectricityMapper
                        .selectOne(new QueryWrapper<JpInverterElectricity>()
                                .eq("sn_code", tanYinInveterInfoDTO.getSn())
                                .eq("name", name));
                if (org.springframework.util.ObjectUtils.isEmpty(jpInverterElectricity)) {
                    jpInverterElectricity = new JpInverterElectricity();
                }
                jpInverterElectricity.setInverterId(jpInverter.getId());
                jpInverterElectricity.setSnCode(tanYinInveterInfoDTO.getSn());
                jpInverterElectricity.setThirdCode(PVProducerInfoEnum.TANYIN.getCode());
                jpInverterElectricity.setThirdStationId(jpInverter.getThirdStationId());
                // jpInverterElectricity.setType("交流");
                // jpInverterElectricity.setFrequency();// 频率
                // jpInverterElectricity.setPower();// 功率
                jpInverterElectricity.setName(name);
                if (tanYinInveterInfoResultJson.get(name) != null && !"".equals(tanYinInveterInfoResultJson.get(name))) {
                    jpInverterElectricity.setVoltage(Double.valueOf(tanYinInveterInfoResultJson.get(name).toString())); // 电压
                }
                // jpInverterElectricity.setCurrent(Double.valueOf(hanlderResult.get("amp" + k).toString()));//  电流
                if (org.springframework.util.ObjectUtils.isEmpty(jpInverterElectricity.getSequenceNbr())) {
                    jpInverterElectricityMapper.insert(jpInverterElectricity);
                } else {
                    jpInverterElectricityMapper.updateById(jpInverterElectricity);
                }
            }

            for (int n = 0; n < 15; n++) {
                String name = "amp" + n;
                JpInverterElectricity jpInverterElectricity = jpInverterElectricityMapper
                        .selectOne(new QueryWrapper<JpInverterElectricity>()
                                .eq("sn_code", tanYinInveterInfoDTO.getSn())
                                .eq("name", name));
                if (org.springframework.util.ObjectUtils.isEmpty(jpInverterElectricity)) {
                    jpInverterElectricity = new JpInverterElectricity();
                }
                jpInverterElectricity.setInverterId(jpInverter.getId());
                jpInverterElectricity.setSnCode(tanYinInveterInfoDTO.getSn());
                jpInverterElectricity.setThirdCode(PVProducerInfoEnum.TANYIN.getCode());
                jpInverterElectricity.setThirdStationId(jpInverter.getThirdStationId());
                // jpInverterElectricity.setType("直流");
                jpInverterElectricity.setName(name);
                // jpInverterElectricity.setVoltage(Double.valueOf(hanlderResult.get("vpv" + k1).toString()));
                if (tanYinInveterInfoResultJson.get(name) != null && !"".equals(tanYinInveterInfoResultJson.get(name))) {
                    jpInverterElectricity.setCurrent(Double.valueOf(tanYinInveterInfoResultJson.get(name).toString()));
                }
//                    jpInverterElectricity.setPower(Double.valueOf(hanlderResult.get("pow" + k1).toString()));
                if (org.springframework.util.ObjectUtils.isEmpty(jpInverterElectricity.getSequenceNbr())) {
                    jpInverterElectricityMapper.insert(jpInverterElectricity);
                } else {
                    jpInverterElectricityMapper.updateById(jpInverterElectricity);
                }
            }
            // endregion
            HYGFJPInverterElecHistory hygfjpInverterElecHistory = new HYGFJPInverterElecHistory();
            hygfjpInverterElecHistory.setThirdStationId(jpInverter.getThirdStationId());
            hygfjpInverterElecHistory.setCreatedTime(System.currentTimeMillis());
            hygfjpInverterElecHistory.setSnCode(tanYinInveterInfoDTO.getSn());
            // hygfjpInverterElecHistory.setUAcCurrent(goodWeInverterCurrentDataDto.getD().getIac1());
            // hygfjpInverterElecHistory.setVAcCurrent(goodWeInverterCurrentDataDto.getD().getIac2());
            // hygfjpInverterElecHistory.setWAcCurrent(goodWeInverterCurrentDataDto.getD().getIac3());
            // hygfjpInverterElecHistory.setUAcVoltage(goodWeInverterCurrentDataDto.getD().getVac1());
            // hygfjpInverterElecHistory.setVAcVoltage(goodWeInverterCurrentDataDto.getD().getVac2());
            // hygfjpInverterElecHistory.setWAcVoltage(goodWeInverterCurrentDataDto.getD().getVac3());
            hygfjpInverterElecHistory.setThirdCode(PVProducerInfoEnum.TANYIN.getCode());
            hygfjpInverterElecHistory.setTime(System.currentTimeMillis());
            hygfjpInverterElecHistoryMapper.insert(hygfjpInverterElecHistory);
            // 逆变器历史
            String today = DateUtil.today();
            HYGFJPInverterHistory hygfjpInverterHistory = hygfjpInverterHistoryMapper
                    .selectOne(new QueryWrapper<HYGFJPInverterHistory>()
                            .eq("sn_code", tanYinInveterInfoDTO.getSn()).eq("date", today));
            if (org.springframework.util.ObjectUtils.isEmpty(hygfjpInverterHistory)) {
                hygfjpInverterHistory = new HYGFJPInverterHistory();
            }
            hygfjpInverterHistory.setDate(today);
            hygfjpInverterHistory.setThirdStationId(jpInverter.getThirdStationId());
            hygfjpInverterHistory.setInverterId(jpInverter.getId());
            hygfjpInverterHistory.setSnCode(tanYinInveterInfoDTO.getSn());
            hygfjpInverterHistory.setThirdCode(PVProducerInfoEnum.TANYIN.getCode());
            if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(jpInverter.getCapacity())
                    && com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(jpInverter.getDayPowerGeneration())) {
                hygfjpInverterHistory
                        .setGenerationHours(jpInverter.getDayPowerGeneration() / jpInverter.getCapacity());
            }

            hygfjpInverterHistory.setPowerGeneration(tanYinInveterInfoDTO.getWatt() != null ? Double.parseDouble(tanYinInveterInfoDTO.getWatt()) : null);
            if (org.springframework.util.ObjectUtils.isEmpty(hygfjpInverterHistory.getCreatedTime())) {
                hygfjpInverterHistory.setCreatedTime(System.currentTimeMillis());
                hygfjpInverterHistoryMapper.insert(hygfjpInverterHistory);
            } else {
                hygfjpInverterHistoryMapper.insert(hygfjpInverterHistory);
            }

            // -----------------------户用光伏日报表----------------------
            TdHYGFInverterDayGenerate tdHYGFInverterDayGenerate = new TdHYGFInverterDayGenerate();
            tdHYGFInverterDayGenerate.setCreatedTime(System.currentTimeMillis());
            tdHYGFInverterDayGenerate.setName(jpInverter.getName());
            tdHYGFInverterDayGenerate.setThirdStationId(String.valueOf(jpInverter.getThirdStationId()));
            tdHYGFInverterDayGenerate.setSnCode(jpInverter.getSnCode().trim());
            tdHYGFInverterDayGenerate.setWorkStatus(jpInverter.getState());
            tdHYGFInverterDayGenerate.setDayGen(jpInverter.getDayPowerGeneration());

            tdHYGFInverterDayGenerate.setMonthGen(jpInverter.getMonthPowerGeneration());
            tdHYGFInverterDayGenerate.setYearGen(jpInverter.getYearPowerGeneration());
            tdHYGFInverterDayGenerate.setTotalGen(jpInverter.getTotalPowerGeneration());
            tdHYGFInverterDayGenerate.setIgbtTemp(Double.parseDouble(tanYinInveterInfoDTO.getTemperature()));
            tdHYGFInverterDayGenerate.setIncome(null);
            if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(jpInverter.getCapacity())
                    && com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(jpInverter.getDayPowerGeneration())) {
                tdHYGFInverterDayGenerate
                        .setFullhour(jpInverter.getDayPowerGeneration() / jpInverter.getCapacity());
            }

            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 (org.springframework.util.ObjectUtils.isEmpty(tdHYGFInverterMonthGenerate)) {
                tdHYGFInverterMonthGenerate = new TdHYGFInverterMonthGenerate();
            }
            tdHYGFInverterMonthGenerate.setThirdStationId(jpInverter.getThirdStationId());
            tdHYGFInverterMonthGenerate.setSnCode(jpInverter.getSnCode().trim());
            tdHYGFInverterMonthGenerate.setName(jpInverter.getName());
            tdHYGFInverterMonthGenerate.setDayTime(DateUtil.format(today1, "yyyy-MM-dd"));
            tdHYGFInverterMonthGenerate.setYearMonth(DateUtil.format(today1, "yyyy-MM"));
            tdHYGFInverterMonthGenerate.setGenerate(jpInverter.getDayPowerGeneration());

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

            }

            if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(jpInverter.getCapacity())
                    && com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(jpInverter.getDayPowerGeneration())) {
                tdHYGFInverterMonthGenerate
                        .setFullhour(jpInverter.getDayPowerGeneration() / jpInverter.getCapacity());
            }

            if (org.springframework.util.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 (org.springframework.util.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());
            if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(jpInverter.getCapacity())
                    && com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(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 (org.springframework.util.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 (org.springframework.util.ObjectUtils.isEmpty(tdHYGFInverterTotalGenerate)) {
                tdHYGFInverterTotalGenerate = new TdHYGFInverterTotalGenerate();
            }
            tdHYGFInverterTotalGenerate.setThirdStationId(jpInverter.getThirdStationId());
            tdHYGFInverterTotalGenerate.setName(null == jpInverter.getName() ? null : jpInverter.getName());
            tdHYGFInverterTotalGenerate.setSnCode(jpInverter.getSnCode().trim());
            tdHYGFInverterTotalGenerate.setYearTime(DateUtil.format(today1, "yyyy"));
            tdHYGFInverterTotalGenerate.setYear(DateUtil.format(today1, "yyyy"));
            tdHYGFInverterTotalGenerate.setGenerate(jpInverter.getYearPowerGeneration());
            if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(jpInverter.getCapacity())
                    && com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(jpInverter.getYearPowerGeneration())) {
                tdHYGFInverterTotalGenerate
                        .setFullhour(jpInverter.getYearPowerGeneration() / jpInverter.getCapacity());
            }
            // 新加
            if (jpStation != null) {
                tdHYGFInverterTotalGenerate.setAmosCompanyCode(jpStation.getAmosCompanyCode());
                tdHYGFInverterTotalGenerate.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
                tdHYGFInverterTotalGenerate.setStationName(jpStation.getName());
                tdHYGFInverterTotalGenerate.setStationState(jpStation.getState());

            }
            if (org.springframework.util.ObjectUtils.isEmpty(tdHYGFInverterTotalGenerate.getCreatedTime())) {
                tdHYGFInverterTotalGenerate.setCreatedTime(System.currentTimeMillis());
                tdHYGFInverterTotalGenerateMapper.insert(tdHYGFInverterTotalGenerate);
            } else {
                tdHYGFInverterTotalGenerateMapper.insert(tdHYGFInverterTotalGenerate);
            }

        }

    }

    private Long convertDate(Long input) {
        Date date = DateUtil.date(input);
        return DateUtil.parse(DateUtil.format(date, DatePattern.NORM_DATETIME_PATTERN)).getTime();
    }
}
