/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.modules.nh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.AllArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springblade.common.utils.CommonUtil;
import org.springblade.common.utils.UnitUtil;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.modules.nh.factory.goodwe.dto.getinventersmoredetailinfobysn.D;
import org.springblade.modules.nh.pojo.dto.sync.DayEnergyDTO;
import org.springblade.modules.nh.pojo.dto.sync.MonthEnergyDTO;
import org.springblade.modules.nh.pojo.entity.MonitorEntryMonthStatEntity;
import org.springblade.modules.nh.pojo.entity.MonitorEntryYearStatEntity;
import org.springblade.modules.nh.pojo.vo.MonitorEntryYearStatVO;
import org.springblade.modules.nh.excel.MonitorEntryYearStatExcel;
import org.springblade.modules.nh.mapper.MonitorEntryYearStatMapper;
import org.springblade.modules.nh.service.IMonitorEntryYearStatService;
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.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 电站能量按年统计 服务实现类
 *
 * @author AlexWang
 * @since 2024-06-02
 */
@Service
@AllArgsConstructor
public class MonitorEntryYearStatServiceImpl extends ServiceImpl<MonitorEntryYearStatMapper, MonitorEntryYearStatEntity> implements IMonitorEntryYearStatService {

	private final BladeRedis bladeRedis;

	@Override
	public IPage<MonitorEntryYearStatVO> selectMonitorEntryYearStatPage(IPage<MonitorEntryYearStatVO> page, MonitorEntryYearStatVO monitorEntryYearStat) {
		return page.setRecords(baseMapper.selectMonitorEntryYearStatPage(page, monitorEntryYearStat));
	}


	@Override
	public List<MonitorEntryYearStatExcel> exportMonitorEntryYearStat(Wrapper<MonitorEntryYearStatEntity> queryWrapper) {
		List<MonitorEntryYearStatExcel> monitorEntryYearStatList = baseMapper.exportMonitorEntryYearStat(queryWrapper);
		//monitorEntryYearStatList.forEach(monitorEntryYearStat -> {
		//	monitorEntryYearStat.setTypeName(DictCache.getValue(DictEnum.YES_NO, MonitorEntryYearStat.getType()));
		//});
		return monitorEntryYearStatList;
	}

	@Override
	public void syncYearStatData(List<MonthEnergyDTO> monthEnergyDTOList) {
		if(CollectionUtil.isEmpty(monthEnergyDTOList)) return;

		List<MonitorEntryYearStatEntity> list = Lists.newArrayList();
		List<MonitorEntryYearStatEntity> updateYearStatList = Lists.newArrayList();
		for (MonthEnergyDTO item : monthEnergyDTOList) {
			Date now = new Date();
			double energy = UnitUtil.convEnergy(item.getValue(), item.getUnit());
			MonitorEntryYearStatEntity entity = new MonitorEntryYearStatEntity();
//`id`,`create_time`,`sync_time`,`update_time`,`sys_type`,`station_id`,`year`,`month`,`energy`
			entity.setCreateTime(now);
			entity.setSyncTime(now);
			entity.setUpdateTime(now);
			entity.setSysType(item.getSysType());
			entity.setOutStationId(item.getStationId());
			String time = item.getMonth();
			String[] splits = time.split("-");
			entity.setYear(Integer.valueOf(splits[0]));
			entity.setMonth(Integer.valueOf(splits[1]));
			entity.setEnergy(energy);

			LambdaQueryWrapper<MonitorEntryYearStatEntity> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper
					.eq(MonitorEntryYearStatEntity::getYear,entity.getYear())
					.eq(MonitorEntryYearStatEntity::getMonth,entity.getMonth())
					.eq(MonitorEntryYearStatEntity::getOutStationId,entity.getOutStationId());

//			List<MonitorEntryYearStatEntity> yearStatList = baseMapper.selectList(queryWrapper);


			if(this.count(queryWrapper)==0){
				list.add(entity);
			}else{
//				if(energy > 0){
					LambdaUpdateWrapper<MonitorEntryYearStatEntity> yearStatUpdateWrapper = new LambdaUpdateWrapper<>();
					yearStatUpdateWrapper
						.eq(MonitorEntryYearStatEntity::getOutStationId,entity.getOutStationId())
						.eq(MonitorEntryYearStatEntity::getYear,entity.getYear())
						.eq(MonitorEntryYearStatEntity::getMonth,entity.getMonth())
						.set(MonitorEntryYearStatEntity::getEnergy,energy)
						.set(MonitorEntryYearStatEntity::getSyncTime,new Date());
					this.update(yearStatUpdateWrapper);
//				}
			}
		}
		this.saveBatch(list,100);

//		if(CollectionUtil.isNotEmpty(updateYearStatList)){
//			this.updateBatchById(updateYearStatList);
//		}
	}

	@Override
	public String getFirstMonth(String outId) {
		LambdaQueryWrapper<MonitorEntryYearStatEntity> query2 = new LambdaQueryWrapper<>();
		query2.eq(MonitorEntryYearStatEntity::getOutStationId,outId)
			.gt(MonitorEntryYearStatEntity::getEnergy,0D)
			.orderByAsc(MonitorEntryYearStatEntity::getYear,MonitorEntryYearStatEntity::getMonth)
			.last("limit 1");
		MonitorEntryYearStatEntity yearStatEntity = getOne(query2);
		if(yearStatEntity==null){
			return null;
		}
		String month = yearStatEntity.getYear()+"-"+String.format("%02d", yearStatEntity.getMonth());
		return month;
	}

	@Override
	public List<MonitorEntryYearStatEntity> listYearByEntry(String outStationId, Integer year) {
		String LIST_YEAR_ENTRY = "list_year_entry_"+year+"_key:";
		String LIST_YEAR_TIME_ENTRY = "list_year_entry_time_"+year+"_key";

		if(CommonUtil.isOutTime(bladeRedis.get(LIST_YEAR_TIME_ENTRY),12*60)){
			bladeRedis.del(LIST_YEAR_ENTRY);
			LambdaQueryWrapper<MonitorEntryYearStatEntity> query2 = new LambdaQueryWrapper<>();
			query2.eq(MonitorEntryYearStatEntity::getYear,year)
				.orderByDesc(MonitorEntryYearStatEntity::getOutStationId)
				.orderByAsc(MonitorEntryYearStatEntity::getMonth);
			List<MonitorEntryYearStatEntity> totalList = list(query2);
			List<MonitorEntryYearStatEntity> yearStatList = Lists.newArrayList();
			String tempStationId = null;
			for(MonitorEntryYearStatEntity item : totalList){
				if(tempStationId==null){
					tempStationId = item.getOutStationId();
				}
				if(!item.getOutStationId().equals(tempStationId) && yearStatList.size() > 0){
					bladeRedis.hSet(LIST_YEAR_ENTRY,tempStationId,yearStatList);
					tempStationId = item.getOutStationId();
					yearStatList = Lists.newArrayList();
				}
				yearStatList.add(item);
			}
			if(yearStatList.size() > 0){
				bladeRedis.hSet(LIST_YEAR_ENTRY,tempStationId,yearStatList);
			}
			bladeRedis.set(LIST_YEAR_TIME_ENTRY,System.currentTimeMillis());
		}
		List<MonitorEntryYearStatEntity> ret = null;
		if(outStationId.contains(",")){
			String[] splits = outStationId.split(",");
			for (String outId : splits) {
				List<MonitorEntryYearStatEntity> tempList = bladeRedis.hGet(LIST_YEAR_ENTRY,outId);
				if(CollectionUtil.isNotEmpty(tempList)){
					if(ret==null){
						ret = tempList;
					}else{
						for(int i=1;i<=12;i++){
							MonitorEntryYearStatEntity yearStat = getMonthFromList(ret,i);
							MonitorEntryYearStatEntity nextYear = getMonthFromList(tempList,i);
							if(nextYear!=null){
								if(yearStat==null){
									ret.add(nextYear);
								}else{
									yearStat.setEnergy(yearStat.getEnergy()+nextYear.getEnergy());
								}
							}
						}
					}
				}
			}
		}else{
			ret = bladeRedis.hGet(LIST_YEAR_ENTRY,outStationId);
		}

		return ret!=null?ret:Lists.newArrayList();
	}

	private MonitorEntryYearStatEntity getMonthFromList(List<MonitorEntryYearStatEntity> list,int month){
		if(CollectionUtil.isEmpty(list)){
			return null;
		}
		MonitorEntryYearStatEntity ret = null;
		for(MonitorEntryYearStatEntity item : list){
			if(item.getMonth()==month){
				ret = item;
				break;
			}
		}
		return ret;
	}
}
