package org.springblade.modules.nh.service.impl;

import cn.hutool.core.date.DateUnit;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.nh.factory.aiswei.dto.getinverterdatapagepro.GetInverterDataPageProR;
import org.springblade.modules.nh.mapper.DeviceMapper;
import org.springblade.modules.nh.pojo.dto.open.YXInverterDataDTO;
import org.springblade.modules.nh.pojo.dto.open.YXPowerStationDTO;
import org.springblade.modules.nh.pojo.entity.DeviceEntity;
import org.springblade.modules.nh.pojo.entity.InverterDataEntity;
import org.springblade.modules.nh.pojo.entity.MonitorInverterStatEntity;
import org.springblade.modules.nh.pojo.vo.InverterDataVO;
import org.springblade.modules.nh.excel.InverterDataExcel;
import org.springblade.modules.nh.mapper.InverterDataMapper;
import org.springblade.modules.nh.service.IInverterDataService;
import org.springblade.modules.nh.service.IPowerStationService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 逆变器数据表 服务实现类
 *
 * @author AlexWang
 * @since 2024-05-31
 */
@Service
@AllArgsConstructor
public class InverterDataServiceImpl extends ServiceImpl<InverterDataMapper, InverterDataEntity> implements IInverterDataService {

	private final DeviceMapper deviceMapper;

	@Override
	public IPage<InverterDataVO> selectInverterDataPage(IPage<InverterDataVO> page, InverterDataVO inverterData) {
		return page.setRecords(baseMapper.selectInverterDataPage(page, inverterData));
	}


	@Override
	public List<InverterDataExcel> exportInverterData(Wrapper<InverterDataEntity> queryWrapper) {
		List<InverterDataExcel> inverterDataList = baseMapper.exportInverterData(queryWrapper);
		//inverterDataList.forEach(inverterData -> {
		//	inverterData.setTypeName(DictCache.getValue(DictEnum.YES_NO, InverterData.getType()));
		//});
		return inverterDataList;
	}

	@Override
	public void updateDataFromInverterStat() {
		try{
			this.baseMapper.updateDataFromInverterStat();
		}catch (Exception e){
			log.error("updateDataFromInverterStat error:{}", e);
		}
		try{
			this.baseMapper.updateDeviceStateFromInverterStat();
		}catch (Exception e){
			log.error("updateDeviceStateFromInverterStat error:{}", e);
		}
	}

	@Override
	public void updateDeviceOutIds() {
		this.baseMapper.updateTxbOutStationId();
	}

	@Override
	public Double sumPacByStationId(Long stationId) {
		return this.baseMapper.sumPacByStationId(stationId);
	}

	@Override
	public void updateDataFromInverterStatByOutInverterId(String outDeviceId) {
		this.baseMapper.updateDataFromInverterStatByOutInverterId(outDeviceId);
	}

	@Override
	public IPage<YXInverterDataDTO> queryYXList(IPage<YXInverterDataDTO> page,String startTime, String endTime) {
		List<InverterDataVO> list = this.baseMapper.queryForYXList(page,startTime,endTime);
		List<YXInverterDataDTO> result = Lists.newArrayList();
		for(InverterDataVO item : list) {
			YXInverterDataDTO dto = BeanUtil.copyProperties(item, YXInverterDataDTO.class);

			DeviceEntity entity= deviceMapper.selectById(item.getDeviceId());
			if(entity!= null){
				dto.setSn(entity.getSn());
				dto.setFaultCode(entity.getFaultCode());
				dto.setAlarmName(entity.getAlarmName());
			}else{
				dto.setSn(item.getSn());
			}
			try{
				String pvStr = item.getPvModules();
				System.out.println(pvStr);
				if(StringUtil.isNoneBlank(pvStr)){
					List<Map<String,Object>> mapList = Lists.newArrayList();
					String[] pvArr= pvStr.split("\\|");
					for(int i=0;i<pvArr.length;i++){
						String[] pvData= StringUtil.split(pvArr[i],":");
						Map<String,Object> pvMap = Maps.newHashMap();
						pvMap.put("name","pv"+(i+1));
						pvMap.put("iPv",pvData[1]);
						pvMap.put("upv",pvData[0]);
						mapList.add(pvMap);
					}

					dto.setPvModuleMap(mapList);
				}
				String uvwStr = item.getUvwModules();
				System.out.println(uvwStr);
				if(StringUtil.isNoneBlank(uvwStr)){
					List<Map<String,Object>> map = Lists.newArrayList();
					String[] uvwArr= uvwStr.split("\\|");
					for(int i=0;i<uvwArr.length;i++){
						String[] pvData= uvwArr[i].split(":");
						Map<String,Object> pvMap = Maps.newHashMap();
						pvMap.put("name","ac"+(i+1));
						pvMap.put("uAc",pvData[0]);
						pvMap.put("iAc",pvData[1]);
						pvMap.put("fac",pvData[2]);
						map.add(pvMap);
					}
					dto.setUvwModulesMap(map);
				}
			}catch (Exception e){
				e.printStackTrace();
				log.error("Exception : "+e);

			}
			result.add(dto);
		};
		page.setRecords(result);
		return page;
	}

	@Override
	public void syncFromScheduler(MonitorInverterStatEntity inverterStat) {
		if(StringUtil.isBlank(inverterStat.getOutInverterId())) return;
		Date now = new Date();
		LambdaUpdateWrapper<InverterDataEntity> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper
			.eq(InverterDataEntity::getOutDeviceId,inverterStat.getOutInverterId())
			.set(InverterDataEntity::getSyncTime,now);
		if(inverterStat.getPwHour()!=null){
			updateWrapper.set(InverterDataEntity::getPwHour,inverterStat.getPwHour());
		}
		if(inverterStat.getEtd()!=null){
			updateWrapper.set(InverterDataEntity::getEtd,inverterStat.getEtd());
		}
		if(inverterStat.getEtm()!=null){
			updateWrapper.set(InverterDataEntity::getEtm,inverterStat.getEtm());
		}
		if(inverterStat.getEty()!=null){
			updateWrapper.set(InverterDataEntity::getEty,inverterStat.getEty());
		}
		if(inverterStat.getEto()!=null){
			updateWrapper.set(InverterDataEntity::getEto,inverterStat.getEto());
		}
		if(inverterStat.getPac()!=null){
			updateWrapper.set(InverterDataEntity::getPac,inverterStat.getPac());
		}
		if(inverterStat.getFac()!=null){
			updateWrapper.set(InverterDataEntity::getFac,inverterStat.getFac());
		}
		if(inverterStat.getDcPac()!=null){
			updateWrapper.set(InverterDataEntity::getDcPac,inverterStat.getDcPac());
		}
		if(inverterStat.getTemperature()!=null){
			updateWrapper.set(InverterDataEntity::getTemperature,inverterStat.getTemperature());
		}
		if(inverterStat.getReactivePower()!=null){
			updateWrapper.set(InverterDataEntity::getReactivePower,inverterStat.getReactivePower());
		}
		if(StringUtil.isNotBlank(inverterStat.getReactivePowerStr())){
			updateWrapper.set(InverterDataEntity::getReactivePowerStr,inverterStat.getReactivePowerStr());
		}
		if(inverterStat.getApparentPower()!=null){
			updateWrapper.set(InverterDataEntity::getApparentPower,inverterStat.getApparentPower());
		}
		if(StringUtil.isNotBlank(inverterStat.getApparentPowerStr())){
			updateWrapper.set(InverterDataEntity::getApparentPowerStr,inverterStat.getApparentPowerStr());
		}
		if(inverterStat.getCollectorSn()!=null){
			updateWrapper.set(InverterDataEntity::getCollectorSn,inverterStat.getCollectorSn());
		}
		if(inverterStat.getRealPower()!=null){
			updateWrapper.set(InverterDataEntity::getRealPower,inverterStat.getRealPower());
		}
		if(inverterStat.getPowerFactor()!=null){
			updateWrapper.set(InverterDataEntity::getPowerFactor,inverterStat.getPowerFactor());
		}
		if(StringUtil.isNotBlank(inverterStat.getPvModules())){
			updateWrapper.set(InverterDataEntity::getPvModules,inverterStat.getPvModules());
		}
		if(StringUtil.isNotBlank(inverterStat.getAcModules())){
			updateWrapper.set(InverterDataEntity::getUvwModules,inverterStat.getAcModules());
		}
//		if(inverterStat.getUpdateShelfEndTime()!=null){
//			updateWrapper.set(InverterDataEntity::get,inverterStat.getUpdateShelfEndTime());
//		}
		this.update(updateWrapper);

		LambdaUpdateWrapper<DeviceEntity> updateWrapper2 = new LambdaUpdateWrapper<>();
		updateWrapper2.eq(DeviceEntity::getOutDeviceId,inverterStat.getOutInverterId())
				.set(DeviceEntity::getUpdateTime,now);
		if(inverterStat.getState()!=null){
			updateWrapper2.set(DeviceEntity::getStatus,inverterStat.getState());
		}
		if(inverterStat.getUpdateShelfEndTime()!=null){
			updateWrapper2.set(DeviceEntity::getWarrantyExpires,inverterStat.getUpdateShelfEndTime());
			if(now.before(inverterStat.getUpdateShelfEndTime())){
				updateWrapper2.set(DeviceEntity::getWarrantyFlag,1);
			}else{
				updateWrapper2.set(DeviceEntity::getWarrantyFlag,0);
			}
		}
		deviceMapper.update(updateWrapper2);
	}

	@Override
	public void syncFromSchedulerList(List<MonitorInverterStatEntity> inverterStatList) {
		inverterStatList.forEach(e->{
			this.syncFromScheduler(e);
		});
	}

	@Override
	public void syncAisweiInverterDatail(List<GetInverterDataPageProR> list) {
		list.forEach(r->{
			//va1~3 ac电压  ia1~3 ac电流
			String  rstStr = CommonUtil.assembleIUData("va","ia",3,r);
			//v1~5 pv电压  i1~5 pv电流
			String  pvStr = CommonUtil.assembleIUData("v","i",5,r);
			syncInverterIU(null,r.getSn(),pvStr,null,rstStr);
		});
	}

	@Override
	public void syncInverterIU(String outInverterId, String sn, String pvStr, String mpptStr, String uvwStr) {
		if(StringUtil.isBlank(outInverterId) && StringUtil.isBlank(sn)) return;

		LambdaUpdateWrapper<InverterDataEntity> updateWrapper = new LambdaUpdateWrapper<>();
		if(StringUtil.isNotBlank(outInverterId)){
			updateWrapper.eq(InverterDataEntity::getOutDeviceId,outInverterId);
		}
		if(StringUtil.isNotBlank(sn)){
			updateWrapper.eq(InverterDataEntity::getSn,sn);
		}
		updateWrapper.set(InverterDataEntity::getPvModules,pvStr)
			.set(InverterDataEntity::getMpptModules,mpptStr)
			.set(InverterDataEntity::getUvwModules,uvwStr);

		this.update(updateWrapper);
	}
}
