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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.api.householdapi.Utils.SunlightUtil;
import com.yeejoin.amos.api.householdapi.face.dto.Device;
import com.yeejoin.amos.api.householdapi.face.dto.SunlightDto;
import com.yeejoin.amos.api.householdapi.face.dto.SunlightWarm;
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.SunlightService;
import com.yeejoin.amos.openapi.enums.PVProducerInfoEnum;
import fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
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.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: tw
 * @createDate: 2024/3/4
 */
@Service
public class SunlightServiceImpl implements SunlightService {

	@Autowired
	SunlightMapper sunlightMapper;

	@Autowired
	private JpStationMapper jpStationMapper;
	@Autowired
	private JpCollectorMapper jpCollectorMapper;

	@Autowired
	private JpInverterMapper jpInverterMapper;

	// 监盘逆变器电量mapper
	@Autowired
	private JpInverterElectricityMapper jpInverterElectricityMapper;
	@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
	ApplicationContext applicationContext;
	// 户用光伏逆变器告警
	@Autowired
	private HYGFJPInverterWarnMapper hygfjpInverterWarnMapper;
	@Autowired
	SunlightUtil SunlightUtil;
	@Autowired
	private HYGFJPStationPowerHistoryMapper hygfjpStationPowerHistoryMapper;
	@Autowired
	TdJpStationMapper tdJpStationMapper;
	@Autowired
	private HYGFJPDayPowerMapper hygfjpDayPowerMapper;

	final static Logger logger = LoggerFactory.getLogger(SofarDataAcquisitionServiceImpl.class);

	final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	private HouseholdPvApiServiceImpl householdPvApiService;
	// td电站信息存储
	@Override
	@Scheduled(cron = "${dataRequstScheduled.Sunlight}")
	@Async
	public void stationList() {
		long ts = System.currentTimeMillis();
		logger.info("-------阳光同步电站/逆变器/采集器开始" + ts + "------- " + sdf.format(new Date()));
		Map<String, Object> bodyparam = new HashMap<>();
		bodyparam.put("ps_type", "1,3,4,5,6,7,8");
		bodyparam.put("size", 3000);
		bodyparam.put("curPage", 1);
		JSONObject data = SunlightUtil.getDataList(SunlightUtil.getPowerStationList, bodyparam);
		List<Sunlight> list = JSONArray.parseArray(JSON.toJSONString(data.get("pageList")), Sunlight.class);
		//删除多余的场站
		deleteYGMessage(data);
		this.stationDetail(data);

		for (Sunlight sunlight : list) {
			sunlight.setCreatedTime(System.currentTimeMillis());
			sunlightMapper.insert(sunlight);
		}
		logger.info("-------阳光同步电站/逆变器/采集器结束" + ts + "------- " + sdf.format(new Date()));
	}

	/**
	 * 删除多余的阳光场站
	 * @param data
	 */
	private void deleteYGMessage(JSONObject data) {
		// 所有场站信息
		List<SunlightDto> sunlightDtos = JSONArray.parseArray(JSON.toJSONString(data.get("pageList")), SunlightDto.class);
		if(CollectionUtil.isNotEmpty(sunlightDtos)){
			List<String> stationIds = new ArrayList<>();
			for (SunlightDto sunlightDto : sunlightDtos) {
				stationIds.add(sunlightDto.getPs_id().toString());
			}
			//场站
			QueryWrapper<JpStation> wrapper = new QueryWrapper<JpStation>().eq("third_code", PVProducerInfoEnum.YG.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.YG.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.YG.getCode());
			List<JpInverter> jpInverters = jpInverterMapper.selectList(wrapper2);
			if(CollectionUtil.isNotEmpty(jpInverters)){
				for (JpInverter jpInverter : jpInverters) {
					if(!stationIds.contains(jpInverter.getThirdStationId())){
						//删除多余数据
						jpInverterMapper.deleteById(jpInverter.getSequenceNbr());
					}
				}
			}
		}
	}

	// 电站数据如库，电站统计数据入库
	public void stationDetail(JSONObject data) {
		String hour = new Date().getHours() + ":00";
		// 所有场站信息
		List<SunlightDto> list = JSONArray.parseArray(JSON.toJSONString(data.get("pageList")), SunlightDto.class);

		// 业务表场站
		List<JpStation> jpStations = jpStationMapper
				.selectList(new QueryWrapper<JpStation>().eq("third_code", PVProducerInfoEnum.YG.getCode()));

		Map<String, JpStation> bodyparam = new HashMap<>();

		if (jpStations != null && jpStations.size() > 0) {
			for (JpStation jpStation : jpStations) {
				bodyparam.put(jpStation.getThirdStationId(), jpStation);
			}
		}

		// 封装电站数据
//        for (SunlightDto sunlightDto : list) {

		for (int i = 0; i < list.size(); i++) {
			SunlightDto sunlightDto = list.get(i);
//              if(i==160){
//                  System.out.println("22222");
//              }
			// System.out.println(i+"====================================================");
			JpStation jpStation = null;

			if (bodyparam.containsKey(sunlightDto.getPs_id().toString())) {
				jpStation = bodyparam.get(sunlightDto.getPs_id().toString());
			} else {
				jpStation = new JpStation();
			}

			jpStation.setThirdStationId(sunlightDto.getPs_id().toString());
			jpStation.setName(sunlightDto.getPs_name());
			jpStation.setAddress(sunlightDto.getPs_location());
			jpStation.setLongitude(("null".equals(sunlightDto.getLongitude()) || (sunlightDto.getLongitude() == null)
					|| "0.0".equals(sunlightDto.getLongitude())) ? null : sunlightDto.getLongitude().toString());
			jpStation.setLatitude(("null".equals(sunlightDto.getLatitude()) || (sunlightDto.getLatitude() == null)
					|| "0.0".equals(sunlightDto.getLatitude())) ? null : sunlightDto.getLatitude().toString());
			jpStation.setThirdCode(PVProducerInfoEnum.YG.getCode());
			// 并网类型
			jpStation.setOnGridType(SunlightUtil.intoNetWorkStatus.get(String.valueOf(sunlightDto.getConnect_type())));
			// 第三方厂商标识
			jpStation.setThirdCode(PVProducerInfoEnum.YG.getCode());
			jpStation.setRecDate(new Date());

			// 获取单个电站详情
			Map<String, Object> bodyparamf = new HashMap<>();
			bodyparamf.put("ps_id", sunlightDto.getPs_id().toString());
			JSONObject jsonObject = SunlightUtil.getdata(SunlightUtil.getPowerStationDetail, bodyparamf);

			jpStation.setRatedPower(jsonObject.get("design_capacity") != null
					? Double.valueOf(jsonObject.get("design_capacity").toString()) / 1000
					: null);// 额定功率
			jpStation.setUserName(jsonObject.get("ps_name") != null ? jsonObject.get("ps_name").toString() : null);// 业主姓名
			jpStation.setEmail(jsonObject.get("email") != null ? jsonObject.get("email").toString() : null);// 邮箱
			jpStation.setUserPhone(
					jsonObject.get("user_moble_tel") != null ? jsonObject.get("user_moble_tel").toString() : null);// 业主电话
			jpStation.setCreateTime(jsonObject.get("install_date") != null
					? DateUtil.parse(jsonObject.get("install_date") + "", "yyyy-MM-dd HH:mm:ss")
					: null); // 创建时间

			jpStation.setType("家庭户用");// 电站类型
//            jpStation.setArea();//地区
			jpStation.setPrice(1.0);// 上网电价
//            jpStation.setOnGridTime(); // 并网时间
//            jpStation.setAccessTime();// 接入平台时间
//            jpStation.setStationContact();// 电站联系人
//            jpStation.setModuleCount(); // 组件数量

			jpStation.setSnCode(sunlightDto.getPs_id().toString());// sncode

			try {
				try {
					Map<String, String> map = sunlightDto.getTotal_capcity();
					if (map != null && map.get("unit") != null && !map.get("unit").isEmpty()
							&& !"--".equals(map.get("value"))) {
						jpStation.setCapacity(SunlightUtil.zj.get(String.valueOf(map.get("unit")))
								* Double.valueOf(String.valueOf(map.get("value"))));// 装机容量
					}
				}catch (Exception e){
					jpStation.setCapacity(0.0);
				}

				try {
					Map<String, String> map1 = sunlightDto.getCurr_power();
					if (map1 != null && map1.get("unit") != null && !map1.get("unit").isEmpty()
							&& !"--".equals(map1.get("value"))) {
						jpStation.setRealTimePower(SunlightUtil.GL.get(String.valueOf(map1.get("unit")))
								* Double.valueOf(String.valueOf(map1.get("value"))));// 实时功率
					}
				}catch (Exception e){
					jpStation.setRealTimePower(0.0);
				}

				try {
					Map<String, String> map2 = sunlightDto.getToday_energy();
					if (map2 != null && map2.get("unit") != null && !map2.get("unit").isEmpty()
							&& !"--".equals(map2.get("value"))) {
						jpStation.setDayGenerate(SunlightUtil.fd.get(String.valueOf(map2.get("unit")))
								* Double.valueOf(String.valueOf(map2.get("value"))));// 日发电量
					}
				}catch (Exception e){
					jpStation.setDayGenerate(0.0);
				}


				try {
					Map<String, String> map3 = sunlightDto.getTotal_energy();
					if (map3 != null && map3.get("unit") != null && !map3.get("unit").isEmpty()
							&& !"--".equals(map3.get("value"))) {
						jpStation.setAccumulatedPower(SunlightUtil.fd.get(String.valueOf(map3.get("unit")))
								* Double.valueOf(String.valueOf(map3.get("value"))));// 累计发电量
					}
				}catch (Exception e){
					jpStation.setAccumulatedPower(0.0);
				}

				try {
					Map<String, String> map4 = sunlightDto.getToday_income();
					if (map4 != null && map4.get("unit") != null && !map4.get("unit").isEmpty()
							&& !"--".equals(map4.get("value"))) {
						jpStation.setDayIncome(SunlightUtil.sy.get(String.valueOf(map4.get("unit")))
								* Double.valueOf(String.valueOf(map4.get("value"))));// 日收益
					}

				}catch (Exception e){
					jpStation.setDayIncome(0.0);
				}

				Map<String, String> map5 = sunlightDto.getTotal_income();
				if (map5 != null && map5.get("unit") != null && !map5.get("unit").isEmpty()
						&& !"--".equals(map5.get("value"))) {
					if (!map5.get("unit").equals("")){
						try {
							jpStation.setCumulativeIncome(SunlightUtil.sy.get(String.valueOf(map5.get("unit")))
									* Double.valueOf(String.valueOf(map5.get("value"))));// 累计收益
						}catch (Exception e){
							//此处出现异常 直接赋值0.0 异常原因基本为厂商赋值问题
							jpStation.setCumulativeIncome(0.0);
						}

					}else {
						jpStation.setCumulativeIncome(0.0);
					}

				}

			} catch (Exception e) {
				e.printStackTrace();
				logger.error("阳光数据错误:" + com.alibaba.fastjson.JSONObject.toJSONString(sunlightDto));
			}

			// 0离线 1在线
			// 1故障 2告警 4正常
			if ("0".equals(sunlightDto.getPs_status().toString())) {
				jpStation.setState("离线");
			} else if ("1".equals(sunlightDto.getPs_status().toString())) {
				if ("1".equals(sunlightDto.getPs_fault_status().toString())
						|| "2".equals(sunlightDto.getPs_fault_status().toString())) {
					jpStation.setState("报警");
				} else if ("4".equals(sunlightDto.getPs_fault_status().toString())) {
					jpStation.setState("在线");
				} else {
					jpStation.setState("在线");
				}
			} else {
				jpStation.setState("在线");
			}

			// 获取电站下通讯模块
			Map<String, Object> bodyparamjp11 = new HashMap<>();
			List<String> lif11 = new ArrayList<>();
			lif11.add("22");
			bodyparamjp11.put("ps_id", sunlightDto.getPs_id().toString());
			bodyparamjp11.put("size", 3000);
			bodyparamjp11.put("curPage", 1);
			bodyparamjp11.put("device_type_list", lif11);
			JSONObject jsonObject1data11 = SunlightUtil.getDataList(SunlightUtil.getDeviceList, bodyparamjp11);
			List<Device> listdtx = JSONArray.parseArray(JSON.toJSONString(jsonObject1data11.get("pageList")),
					Device.class);
			// 获取电站下逆变器
			Map<String, Object> bodyparamjp = new HashMap<>();
			List<String> lif = new ArrayList<>();
			lif.add("1");
			bodyparamjp.put("ps_id", sunlightDto.getPs_id().toString());
			bodyparamjp.put("size", 3000);
			bodyparamjp.put("curPage", 1);
			bodyparamjp.put("device_type_list", lif);
			JSONObject jsonObject1data = SunlightUtil.getdata(SunlightUtil.getDeviceList, bodyparamjp);
			List<Device> listd = JSONArray.parseArray(JSON.toJSONString(jsonObject1data.get("pageList")), Device.class);

			// 获取电站，月发电量
			if (listd != null && listd.size() > 0) {
				Map<String, Object> bodyparamnb = new HashMap<>();
				List<String> li = new ArrayList<>();
				li.add(listd.get(0).getPs_key());
				Calendar calendar = Calendar.getInstance();
				int year = calendar.get(Calendar.YEAR);
				int month = calendar.get(Calendar.MONTH) + 1;
				bodyparamnb.put("ps_key_list", li);
				bodyparamnb.put("start_time", year + "" + (month < 10 ? "0" + month : month));
				bodyparamnb.put("end_time", year + "" + (month < 10 ? "0" + month : month));
				bodyparamnb.put("data_type", "4");
				bodyparamnb.put("order", "0");
				bodyparamnb.put("query_type", "2");
				bodyparamnb.put("data_point", "p1");

				JSONObject jsonObject1nb = SunlightUtil.getdata(SunlightUtil.getDevicePointsDayMonthYearDataList,
						bodyparamnb);

				JSONObject jsonObject22 = JSONUtil.parseObj(jsonObject1nb.get(listd.get(0).getPs_key()), true);
				List<Map> js = JSONArray.parseArray(JSON.toJSONString(jsonObject22.get("p1")), Map.class);
				// 月发电量
				jpStation.setMonthGenerate(
						js != null && js.get(0).get("4") != null ? Double.valueOf(js.get(0).get("4") + "") / 1000
								: null);
				// 月收益
				jpStation.setMonthIncome(
						js != null && js.get(0).get("4") != null ? Double.valueOf(js.get(0).get("4") + "") / 1000
								: null);
			}

			// 获取电站，年发电量
			if (listd != null && listd.size() > 0) {

				Map<String, Object> bodyparamnb = new HashMap<>();
				List<String> li = new ArrayList<>();
				li.add(listd.get(0).getPs_key());

				Calendar calendar = Calendar.getInstance();
				int year = calendar.get(Calendar.YEAR);
				int month = calendar.get(Calendar.MONTH) + 1;

				bodyparamnb.put("ps_key_list", li);
				bodyparamnb.put("start_time", year + "");
				bodyparamnb.put("end_time", year + "");
				bodyparamnb.put("data_type", "4");
				bodyparamnb.put("order", "0");
				bodyparamnb.put("query_type", "3");
				bodyparamnb.put("data_point", "p1");

				JSONObject jsonObject1nb = SunlightUtil.getdata(SunlightUtil.getDevicePointsDayMonthYearDataList,
						bodyparamnb);
				JSONObject jsonObject23 = JSONUtil.parseObj(jsonObject1nb.get(listd.get(0).getPs_key()), true);

				List<Map> js = JSONArray.parseArray(JSON.toJSONString(jsonObject23.get("p1")), Map.class);
				// 年发电量
				jpStation.setYearGenerate(js != null ? Double.valueOf(js.get(0).get("4") + "") / 1000 : null);
				// 年收益
				jpStation.setYearIncome(js != null ? Double.valueOf(js.get(0).get("4") + "") / 1000 : null);

				String today = DateUtil.today();

				HYGFJPDayPower hygfjpDayPower = hygfjpDayPowerMapper.selectOne(
						new QueryWrapper<HYGFJPDayPower>().eq("third_station_id", sunlightDto.getPs_id().toString())
								.eq("year_month_day", today).eq("hour", hour));
				if (ObjectUtils.isEmpty(hygfjpDayPower)) {
					hygfjpDayPower = new HYGFJPDayPower();
				}
				hygfjpDayPower.setThirdStationId(sunlightDto.getPs_id().toString());
				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);
				}

				HYGFJPStationPowerHistory hygfjpStationPowerHistory = new HYGFJPStationPowerHistory();
				hygfjpStationPowerHistory.setCreatedTime(System.currentTimeMillis());
				hygfjpStationPowerHistory.setThirdStationId(jpStation.getThirdStationId());
				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);

				// 增加td 电站区域公司，经销商绑定表
//                TdJpStation tdJpStation = tdJpStationMapper.selectOne(new QueryWrapper<TdJpStation>().
//                        eq("third_code", PVProducerInfoEnum.YG.getCode()).
//                        eq("third_station_id",  jpStation.getThirdStationId()));
//                //判断是否存在
//                if (ObjectUtils.isEmpty(tdJpStation)) {
//                    tdJpStation = new TdJpStation();
//                }
//                tdJpStation.setAmosCompanyCode(jpStation.getAmosCompanyCode());
//                tdJpStation.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
//                tdJpStation.setThirdStationId( jpStation.getThirdStationId());
//                tdJpStation.setThirdCode( PVProducerInfoEnum.YG.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);
//                }
			}
			JpStation jpStationOld = jpStationMapper.selectOne(
					new LambdaQueryWrapper<JpStation>().eq(JpStation::getThirdStationId, jpStation.getThirdStationId())
							.eq(JpStation::getThirdCode, PVProducerInfoEnum.YG.getCode()));

			if (jpStationOld != null) {
				jpStation.setSequenceNbr(jpStationOld.getSequenceNbr());
				jpStationMapper.updateById(jpStation);
			} else {
				jpStationMapper.insert(jpStation);
			}

			if (CollectionUtil.isNotEmpty(listd)) {
				this.setJpInverte(listd, jpStation, listdtx);
			}

			if (CollectionUtil.isNotEmpty(listdtx)) {
				this.collectorDetail(listdtx, jpStation);
			}

			// 电站报表
			// 户用场站日发电量
			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() == null || jpStation.getCapacity() == null) ? null :

							(jpStation.getCapacity() <= 0.0 ? null
									: 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()

					(jpStation.getMonthGenerate() == null || jpStation.getCapacity() == null) ? null :

							(jpStation.getCapacity() <= 0.0 ? null
									: 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()
					(jpStation.getYearGenerate() == null || jpStation.getCapacity() == null) ? null
							: (jpStation.getCapacity() <= 0.0 ? null
									: 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);
			}
		}

	}

	// 逆变器数据入库，逆变器参数入库
	public void setJpInverte(List<Device> devices, JpStation jpStation, List<Device> devicestx) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					for (Device device : devices) {
						if (device != null) {
							// 获取逆变器信息存库
							JpInverter jpInverter = jpInverterMapper.selectOne(
									new QueryWrapper<JpInverter>().eq("sn_code", device.getDevice_sn().toString())
											.eq("third_code", PVProducerInfoEnum.YG.getCode()));
							if (ObjectUtils.isEmpty(jpInverter)) {
								jpInverter = new JpInverter();
							}
							// 品牌
							jpInverter.setBrand(device.getFactory_name());
							jpInverter.setSnCode(device.getDevice_sn());
							jpInverter.setId(device.getUuid().toString());

							// 0离线 1在线
							// 1故障 2告警 4正常
							if ("0".equals(device.getDev_status())) {
								jpInverter.setState("离线");
							} else if ("1".equals(device.getDev_status())) {
								if ("1".equals(device.getDev_fault_status())
										|| "2".equals(device.getDev_fault_status())) {
									jpInverter.setState("报警");
								} else if ("4".equals(device.getDev_fault_status())) {
									jpInverter.setState("在线");
								} else {
									jpInverter.setState("在线");
								}
							} else {
								jpInverter.setState("在线");
							}
							// logger.error("阳光数据解析(逆变器),无法获取状态:" +
							// com.alibaba.fastjson.JSONObject.toJSONString(device));
							jpInverter.setUpdateTime(new Date());
							jpInverter.setDayPowerGeneration(jpStation.getDayGenerate());
							jpInverter.setMonthPowerGeneration(jpStation.getMonthGenerate());
							jpInverter.setYearPowerGeneration(jpStation.getYearGenerate());
							jpInverter.setTotalPowerGeneration(jpStation.getAccumulatedPower());
							jpInverter.setThirdStationId(jpStation.getThirdStationId());
							jpInverter.setThirdCode(PVProducerInfoEnum.YG.getCode());
							jpInverter.setName(device.getDevice_name());
							jpInverter.setStationName(jpStation.getName());
							jpInverter.setAddr(jpStation.getAddress());
							jpInverter.setModel(device.getDevice_model_code());
							jpInverter.setCapacity(jpStation.getCapacity());
							jpInverter.setCurrentPower(jpStation.getRealTimePower());
							jpInverter.setRatedPower(jpStation.getRatedPower());
							jpInverter.setFisTimeStr(device.getGrid_connection_date());

							if (devicestx != null) {

								for (Device devicestx1 : devicestx) {
									if (devicestx1.getDevice_code().equals(device.getCommunication_dev_sn())) {
										// 采集器id
										jpInverter.setCollectorId(devicestx1.getUuid().toString());
										// 采集器sn编码
										jpInverter.setCollectorSnCode(device.getCommunication_dev_sn());
										break;
									}
								}
							}
//            // 国标
//            jpInverter.setNationalStandard(inverterDetailDto.getNationalStandards());
//            // 满发小时数
//            jpInverter.setGenerationHours(String.valueOf(inverterDetailDto.getFullHour()));
//            //版本
//            jpInverter.setVersion(device.getDevice_model_code());
							if (!ObjectUtils.isEmpty(jpInverter.getSequenceNbr())) {
								jpInverterMapper.updateById(jpInverter);
							} else {
								if (StringUtils.isNotEmpty(jpInverter.getSnCode())) {
									jpInverterMapper.insert(jpInverter);
								}
							}
							// 逆变器指标信息
							Map<String, Object> bodyparamnb = new HashMap<>();
							List<String> li = new ArrayList<>();
							li.add(device.getPs_key());
							bodyparamnb.put("ps_key_list", li);

							JSONObject jsonObject1nb = SunlightUtil.getdata(SunlightUtil.getPVInverterRealTimeData,
									bodyparamnb);

							List<Map> js = JSONArray
									.parseArray(JSON.toJSONString(jsonObject1nb.get("device_point_list")), Map.class);

							if (js != null && js.size() > 0) {
								Map jsd = JSONUtil.parseObj(js.get(0).get("device_point"));
								List<String> liname = new ArrayList<>();
								liname.add("AC1");// A 相电压
								liname.add("AC2");// B 相电压
								liname.add("AC3");// C 相电压
								liname.add("PV1");// 直流电压 1
								liname.add("PV2");// 直流电压 2
								liname.add("PV3");// 直流电压 3
								liname.add("PV4");// 直流电压 4
								liname.add("PV5");// 直流电压 5
								liname.add("PV6");// 直流电压 6
								liname.add("PV7");// 直流电压 7
								liname.add("PV8");// 直流电压 8
								liname.add("PV9");// 直流电压 9
								liname.add("PV10");// 直流电压 10
								for (int i = 0; i < liname.size(); i++) {

									JpInverterElectricity jpInverterElectricity = jpInverterElectricityMapper
											.selectOne(new QueryWrapper<JpInverterElectricity>()
													.eq("sn_code", jpInverter.getSnCode())
													.eq("third_code", PVProducerInfoEnum.YG.getCode())
													.eq("name", liname.get(i)));
									if (ObjectUtils.isEmpty(jpInverterElectricity)) {
										jpInverterElectricity = new JpInverterElectricity();
									}
									jpInverterElectricity.setInverterId(jpInverter.getId());
									jpInverterElectricity.setSnCode(jpInverter.getSnCode());
									jpInverterElectricity.setThirdCode(PVProducerInfoEnum.YG.getCode());
									jpInverterElectricity.setThirdStationId(jpInverter.getThirdStationId());

									if (i > 2) {
										jpInverterElectricity.setType("直流");
									} else {
										jpInverterElectricity.setType("交流");
									}

									jpInverterElectricity.setName(liname.get(i));

									String voltage = null;
									String current = null;
									switch (liname.get(i)) {
									case "AC1":
										voltage = jsd.get("p18") != null ? jsd.get("p18").toString() : null;
										current = jsd.get("p21") != null ? jsd.get("p21").toString() : null;
										break;

									case "AC2":
										voltage = jsd.get("p19") != null ? jsd.get("p19").toString() : null;
										current = jsd.get("p22") != null ? jsd.get("p22").toString() : null;
										break;
									case "AC3":
										voltage = jsd.get("p20") != null ? jsd.get("p20").toString() : null;
										current = jsd.get("p23") != null ? jsd.get("p23").toString() : null;
										break;
									case "PV1":
										voltage = jsd.get("p5") != null ? jsd.get("p5").toString() : null;
										current = jsd.get("p6") != null ? jsd.get("p6").toString() : null;
										break;
									case "PV2":
										voltage = jsd.get("p7") != null ? jsd.get("p7").toString() : null;
										current = jsd.get("p8") != null ? jsd.get("p8").toString() : null;
										break;
									case "PV3":
										voltage = jsd.get("p9") != null ? jsd.get("p9").toString() : null;
										current = jsd.get("p10") != null ? jsd.get("p10").toString() : null;
										break;
									case "PV4":
										voltage = jsd.get("p45") != null ? jsd.get("p45").toString() : null;
										current = jsd.get("") != null ? jsd.get("").toString() : null;
										break;
									case "PV5":
										voltage = jsd.get("p47") != null ? jsd.get("p47").toString() : null;
										current = jsd.get("p46") != null ? jsd.get("p46").toString() : null;
										break;
									case "PV6":
										voltage = jsd.get("p49") != null ? jsd.get("p49").toString() : null;
										current = jsd.get("p48") != null ? jsd.get("p48").toString() : null;
										break;
									case "PV7":
										voltage = jsd.get("p51") != null ? jsd.get("p51").toString() : null;
										current = jsd.get("p50") != null ? jsd.get("p50").toString() : null;
										break;
									case "PV8":
										voltage = jsd.get("p53") != null ? jsd.get("p53").toString() : null;
										current = jsd.get("p52") != null ? jsd.get("p52").toString() : null;
										break;
									case "PV9":
										voltage = jsd.get("p55") != null ? jsd.get("p55").toString() : null;
										current = jsd.get("p54") != null ? jsd.get("p54").toString() : null;
										break;
									case "PV10":
										voltage = jsd.get("p57") != null ? jsd.get("p57").toString() : null;
										current = jsd.get("p58") != null ? jsd.get("p58").toString() : null;
										break;
									default:
									}
									jpInverterElectricity.setVoltage(voltage != null ? Double.valueOf(voltage) : null);
									jpInverterElectricity.setCurrent(current != null ? Double.valueOf(current) : null);
									jpInverterElectricity.setPower(null);
									if (ObjectUtils.isEmpty(jpInverterElectricity.getSequenceNbr())) {
										jpInverterElectricityMapper.insert(jpInverterElectricity);
									} else {
										jpInverterElectricityMapper.updateById(jpInverterElectricity);
									}
								}
								// 逆变器报表
								// -----------------------户用光伏日报表----------------------
								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(
										jsd.get("p18") != null ? Double.valueOf(jsd.get("p18").toString()) : null);
								tdHYGFInverterDayGenerate.setDcv2(
										jsd.get("p19") != null ? Double.valueOf(jsd.get("p19").toString()) : null);
								tdHYGFInverterDayGenerate.setDcv3(
										jsd.get("p20") != null ? Double.valueOf(jsd.get("p20").toString()) : null);
								// 交流电流
								tdHYGFInverterDayGenerate.setDcc1(
										jsd.get("p21") != null ? Double.valueOf(jsd.get("p21").toString()) : null);
								tdHYGFInverterDayGenerate.setDcc2(
										jsd.get("p22") != null ? Double.valueOf(jsd.get("p22").toString()) : null);
								tdHYGFInverterDayGenerate.setDcc3(
										jsd.get("p23") != null ? Double.valueOf(jsd.get("p23").toString()) : null);
								// 直流电压
								tdHYGFInverterDayGenerate.setAcv1(
										jsd.get("p5") != null ? Double.valueOf(jsd.get("p5").toString()) : null);
								tdHYGFInverterDayGenerate.setAcv2(
										jsd.get("p7") != null ? Double.valueOf(jsd.get("p7").toString()) : null);
								tdHYGFInverterDayGenerate.setAcv3(
										jsd.get("p9") != null ? Double.valueOf(jsd.get("p9").toString()) : null);
								tdHYGFInverterDayGenerate.setAcv4(
										jsd.get("p45") != null ? Double.valueOf(jsd.get("p45").toString()) : null);
								// 直流电流
								tdHYGFInverterDayGenerate.setAcc1(
										jsd.get("p6") != null ? Double.valueOf(jsd.get("p6").toString()) : null);
								tdHYGFInverterDayGenerate.setAcc2(
										jsd.get("p8") != null ? Double.valueOf(jsd.get("p8").toString()) : null);
								tdHYGFInverterDayGenerate.setAcc3(
										jsd.get("p10") != null ? Double.valueOf(jsd.get("p10").toString()) : null);
								tdHYGFInverterDayGenerate.setAcc4(
										jsd.get("p46") != null ? Double.valueOf(jsd.get("p46").toString()) : null);

								tdHYGFInverterDayGenerate.setPv1(null);
								tdHYGFInverterDayGenerate.setPv2(null);
								tdHYGFInverterDayGenerate.setPv3(null);
								tdHYGFInverterDayGenerate.setPv4(null);
								// 功率
								tdHYGFInverterDayGenerate.setTotalPower(jpInverter.getCurrentPower());
//                                    //频率
								tdHYGFInverterDayGenerate.setFrequency(String.valueOf(jsd.get("p27")));
//                                    //功率因数
								tdHYGFInverterDayGenerate.setPowerFactor(1.0);
								tdHYGFInverterDayGenerate.setDayGen(jpInverter.getDayPowerGeneration());
								tdHYGFInverterDayGenerate.setMonthGen(jpInverter.getMonthPowerGeneration());
								tdHYGFInverterDayGenerate.setYearGen(jpInverter.getYearPowerGeneration());
								tdHYGFInverterDayGenerate.setTotalGen(jpInverter.getTotalPowerGeneration());
								tdHYGFInverterDayGenerate
										.setIgbtTemp(ObjectUtils.isEmpty(jpInverter.getIgbtTemperature()) ? null
												: Double.valueOf(jpInverter.getIgbtTemperature()));
								tdHYGFInverterDayGenerate.setIncome(null);
								tdHYGFInverterDayGenerate.setFullhour(
										(jpInverter.getDayPowerGeneration() == null || jpInverter.getCapacity() == null)
												? null
												: (jpInverter.getCapacity() <= 0.0 ? null
														: jpInverter.getDayPowerGeneration()
																/ jpInverter.getCapacity()));

								// 电站区域经销商，
								JpStation jpStation = jpStationMapper.selectOne(new QueryWrapper<JpStation>()
										.eq("third_code", PVProducerInfoEnum.YG.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.setName(jpInverter.getName());
								tdHYGFInverterMonthGenerate.setFullhour(
										(jpInverter.getDayPowerGeneration() == null || jpInverter.getCapacity() == null)
												? null
												: (jpInverter.getCapacity() <= 0.0 ? null
														: jpInverter.getDayPowerGeneration()
																/ jpInverter.getCapacity()));

								// 新加
								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.setName(jpInverter.getName());
								tdHYGFInverterYearGenerate.setFullhour((jpInverter.getMonthPowerGeneration() == null
										|| jpInverter.getCapacity() == null)
												? null
												: (jpInverter.getCapacity() <= 0.0 ? null
														: jpInverter.getMonthPowerGeneration()
																/ jpInverter.getCapacity()));
								// 新加
								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(0.0d);
								tdHYGFInverterTotalGenerate.setName(jpInverter.getName());
								tdHYGFInverterTotalGenerate.setFullhour((jpInverter.getYearPowerGeneration() == null
										|| jpInverter.getCapacity() == null)
												? null
												: (jpInverter.getCapacity() <= 0.0 ? null
														: jpInverter.getYearPowerGeneration()
																/ jpInverter.getCapacity()));

								// 新加
								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);
								}
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}).start();

	}

	@Async
	public void collectorDetail(List<Device> devices, JpStation jpStation) {

		for (Device device : devices) {
			JpCollector jpCollector = jpCollectorMapper
					.selectOne(new QueryWrapper<JpCollector>().eq("third_station_id", jpStation.getThirdStationId())
							.eq("third_code", PVProducerInfoEnum.YG.getCode()).eq("sn_code", device.getDevice_sn()));
			if (ObjectUtils.isEmpty(jpCollector)) {
				jpCollector = new JpCollector();
			}
			// sn编码
			jpCollector.setSnCode(device.getDevice_sn());
			jpCollector.setAddr(jpStation.getAddress());
			jpCollector.setName(device.getDevice_name());
			// 类型
			jpCollector.setType("通信模块");
			// 更新时间
			jpCollector.setUpdateTime(new Date());
			// 出场日期
//                jpCollector.setDischargeDate(new Date(collectorDetailDto.getFactoryTime()));
//                //生产日期
//                jpCollector.setProductDate(new Date(collectorDetailDto.getFactordyTime()));
//                //数据上传间隔
//                jpCollector.setDataPeriod(collectorDetailDto.getDataUploadCycle());
//                //本次上电时间
//                jpCollector.setThisWorkTime(new DateTime(collectorDetailDto.getCurrentWorkingTime()));
//                //累计工作时间
//                jpCollector.setTotalWorkTime(new DateTime(collectorDetailDto.getTotalWorkingTime()));
			// 第三方电站id
			jpCollector.setThirdStationId(jpStation.getThirdStationId());
			// 第三方厂商标识
			jpCollector.setThirdCode(PVProducerInfoEnum.YG.getCode());
			if (device.getGetPs_fault_status() != null) {
				if (device.getGetPs_fault_status() > 2) {
					jpCollector.setState(SunlightUtil.zt.get(device.getDev_status() + ""));
				} else {
					jpCollector.setState("报警");// 电站状态
				}
			} else {
				// 如果获取不了逆变器状态 并且逆变器没状态就默认离线
				if (jpCollector.getState() == null) {
					jpCollector.setState("离线");
				}
			}
			jpCollector.setStationName(jpStation.getName());
			// jpCollector.setVersion(imasterCollectorList.getSoftwareVersion());
			jpCollector.setRecDate(new Date());
			if (ObjectUtils.isEmpty(jpCollector.getSequenceNbr())) {
				jpCollectorMapper.insert(jpCollector);
			} else {
				jpCollectorMapper.updateById(jpCollector);
			}
		}
	}

	@Scheduled(cron = "${dataRequstScheduled.Sunlight}")
	@Override
	@Async
	public void inverAlramInfo() {
		long ts = System.currentTimeMillis();
		logger.info("-------阳光同步告警开始" + ts + "------- " + sdf.format(new Date()));
		// 获取所有未处理告警
		Map<String, Object> bodyparamf = new HashMap<>();
		bodyparamf.put("size", 1000);
		bodyparamf.put("curPage", 1);
		JSONObject jsonObject = SunlightUtil.getDataList(SunlightUtil.getFaultAlarmInfo, bodyparamf);
		List<SunlightWarm> listd = jsonObject.get("pageList") != null
				? JSONArray.parseArray(JSON.toJSONString(jsonObject.get("pageList")), SunlightWarm.class)
				: null;
		// 获取系统未处理的告警
		List<String> li = new ArrayList<>();
		li.add(SunlightUtil.alarmstatus.get("4"));
		li.add(SunlightUtil.alarmstatus.get("5"));
		List<HYGFJPInverterWarn> hygfjpInverterWarnlist = hygfjpInverterWarnMapper
				.selectList(new QueryWrapper<HYGFJPInverterWarn>().notIn("`state`", li).eq("third_code",
						PVProducerInfoEnum.YG.getCode()));
		Map<String, HYGFJPInverterWarn> bodyparam = new HashMap<>();
		if (hygfjpInverterWarnlist != null && hygfjpInverterWarnlist.size() > 0) {
			bodyparam = hygfjpInverterWarnlist.stream()
					.collect(Collectors.toMap(HYGFJPInverterWarn::getWarnId, Function.identity(),(value1, value2) -> value1));
		}
		// 获取所有逆变器
		List<JpInverter> jpInverter = jpInverterMapper
				.selectList(new QueryWrapper<JpInverter>().eq("third_code", PVProducerInfoEnum.YG.getCode()));
		Map<String, String> jpInverterbodyparam = new HashMap<>();
		if (jpInverter != null && jpInverter.size() > 0) {
			jpInverterbodyparam = jpInverter.stream()
					.collect(Collectors.toMap(JpInverter::getId, JpInverter::getSnCode,(value1, value2) -> value1));
		}
		if (listd != null && !listd.isEmpty()) {
			for (SunlightWarm sunlightWarm : listd) {
				// 告警已存在
				if (!bodyparam.isEmpty() && bodyparam.containsKey(sunlightWarm.getFault_code())) {
					bodyparam.remove(sunlightWarm.getFault_code());
				} else {
					// 告警不存在，新增
					HYGFJPInverterWarn hygfjpInverterWarn = new HYGFJPInverterWarn();
					hygfjpInverterWarn.setTime(System.currentTimeMillis());
					hygfjpInverterWarn.setSnCode(!jpInverterbodyparam.isEmpty()
							&& jpInverterbodyparam.containsKey(sunlightWarm.getUuid().toString())
									? jpInverterbodyparam.get(sunlightWarm.getUuid().toString())
									: null);
					hygfjpInverterWarn.setThirdStationId(sunlightWarm.getPs_id().toString());
					hygfjpInverterWarn.setLevel(SunlightUtil.alarmLevel.get(sunlightWarm.getFault_level().toString()));
					hygfjpInverterWarn.setContent(sunlightWarm.getFault_name());
					hygfjpInverterWarn.setThirdCode(PVProducerInfoEnum.YG.getCode());
					hygfjpInverterWarn.setTreatment(sunlightWarm.getFault_desc());
					hygfjpInverterWarn.setStartTime(
							DateUtil.parse(sunlightWarm.getCreate_time(), DatePattern.NORM_DATETIME_PATTERN).getTime());
					hygfjpInverterWarn
							.setState(SunlightUtil.alarmstatus.get(sunlightWarm.getProcess_status().toString()));
					hygfjpInverterWarn.setTimeLong(null);
					hygfjpInverterWarn.setRecoverTime(null);
					hygfjpInverterWarn.setTimeLong(null);
					hygfjpInverterWarn.setWarnId(sunlightWarm.getFault_code());
					// 电站区域经销商，
					JpStation jpStation = jpStationMapper
							.selectOne(new QueryWrapper<JpStation>().eq("third_code", PVProducerInfoEnum.YG.getCode())
									.eq("third_station_id", sunlightWarm.getPs_id().toString()));
					if (jpStation != null) {
						hygfjpInverterWarn.setAmosCompanyCode(jpStation.getAmosCompanyCode());
						hygfjpInverterWarn.setRegionalCompaniesCode(jpStation.getRegionalCompaniesCode());
						hygfjpInverterWarn.setStationName(jpStation.getName());
						hygfjpInverterWarn.setStationState(jpStation.getState());
					}
					try {
						TimeUnit.MINUTES.sleep(1);
						hygfjpInverterWarn.setCreatedTime(System.currentTimeMillis());
						hygfjpInverterWarnMapper.insert(hygfjpInverterWarn);
					} catch (Exception e) {
						e.printStackTrace();
						hygfjpInverterWarnMapper.insert(hygfjpInverterWarn);
					}

				}
			}
		}

		// 更新td已消除告警，由于第三方获取会出现请求次数超限，状态只能手动修改，没有消除时间，

		if (!bodyparam.isEmpty()) {
			Object[] ids = bodyparam.keySet().toArray();
			for (Object id : ids) {
//               Map<String, Object> bodyparamfx=new HashMap<>();
//               bodyparamfx.put("size", 1000);
//               bodyparamfx.put("curPage",1);
//               bodyparamfx.put("process_status",9);
//               bodyparamfx.put("fault_code",id);
//               JSONObject jsonObjectx = SunlightUtil.getdata(
//                       SunlightUtil.getFaultAlarmInfo,
//                       bodyparamfx
//               );
//               List<SunlightWarm> listx = JSONArray.parseArray(JSON.toJSONString(jsonObjectx.get("pageList")), SunlightWarm.class );

//               if(listx!=null&&!listx.isEmpty()){
//                   SunlightWarm sunlightWarm=listx.get(0);
				HYGFJPInverterWarn hygfjpInverterWarn = bodyparam.get(id);
//
//                   if (StringUtils.isNotBlank(sunlightWarm.getOver_time())) {
//                       hygfjpInverterWarn.setRecoverTime(DateUtil.parse(sunlightWarm.getOver_time(), DatePattern.NORM_DATETIME_PATTERN).getTime());
//                   }
//                   if (!ObjectUtils.isEmpty(hygfjpInverterWarn.getStartTime()) && !ObjectUtils.isEmpty(hygfjpInverterWarn.getRecoverTime())) {
//                       hygfjpInverterWarn.setTimeLong(hygfjpInverterWarn.getRecoverTime() - hygfjpInverterWarn.getStartTime());
//                   }

				// hygfjpInverterWarn.setState(SunlightUtil.alarmstatus.get(sunlightWarm.getProcess_status()));
				hygfjpInverterWarn.setState(SunlightUtil.alarmstatus.get("5"));
				hygfjpInverterWarnMapper.insert(hygfjpInverterWarn);
//               }
			}
		}
		logger.info("-------阳光同步告警结束" + ts + "------- " + sdf.format(new Date()));
	}

}
