package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.hygf.api.entity.JpCollector;
import com.yeejoin.amos.boot.module.hygf.api.entity.JpInverter;
import com.yeejoin.amos.boot.module.hygf.api.entity.TdHygfJpInvertorElecHistory;
import com.yeejoin.amos.boot.module.hygf.api.service.ITdHygfJpInvertorElecHistoryService;
import com.yeejoin.amos.boot.module.hygf.api.tdenginemapper.TdHygfJpInvertorElecHistoryMapper;
import com.yeejoin.amos.boot.module.hygf.api.util.TimeUtil;

/**
 * 户用光伏监盘逆变器电能历史表服务实现类
 *
 * @author system_generator
 * @date 2023-09-19
 */
@Service
public class TdHygfJpInvertorElecHistoryServiceImpl extends
		BaseService<TdHygfJpInvertorElecHistoryDto, TdHygfJpInvertorElecHistory, TdHygfJpInvertorElecHistoryMapper>
		implements ITdHygfJpInvertorElecHistoryService {

	@Autowired
	private JpInverterServiceImpl jpInvertorServiceImpl;

	/**
	 * 分页查询
	 */
	public Page<TdHygfJpInvertorElecHistoryDto> queryForTdHygfJpInvertorElecHistoryPage(
			Page<TdHygfJpInvertorElecHistoryDto> page) {
		return this.queryForPage(page, null, false);
	}

	/**
	 * 列表查询 示例
	 */
	public List<TdHygfJpInvertorElecHistoryDto> dayList(long id, Date day) {
		JpInverter invertor = jpInvertorServiceImpl.getById(id);
		if (invertor != null) {
			List<TdHygfJpInvertorElecHistoryDto> list = this.baseMapper.dayList(invertor.getSnCode(),
					invertor.getThirdStationId(), TimeUtil.getStartTimeOfDay(day), TimeUtil.getEndTimeOfDay(day));
			if (!list.isEmpty()) {
				list.forEach(i -> {
					i.setTimeFormat(TimeUtil.minuteFormat(i.getTime()));
				});
			}
			return list;
		}
		return new ArrayList<>();
	}

	/**
	 * 列表查询 示例
	 */
	public List<JpInvertorElecHistoryMonthDto> monthList(long id, Date month) {
		JpInverter invertor = jpInvertorServiceImpl.getById(id);
		Calendar cal = Calendar.getInstance();
		cal.setTime(month);
		String monthStr = String.valueOf(cal.get(Calendar.YEAR)) + "-" + String.valueOf(cal.get(Calendar.MONTH) + 1);
		if (invertor != null) {
            List<JpInvertorElecHistoryMonthDto> li=   this.baseMapper.monthList(invertor.getSnCode().trim(), invertor.getThirdStationId(), monthStr);

            List<JpInvertorElecHistoryMonthDto> lidata=new ArrayList<>();
                    List<String> list= dayReport(month);
            for (String s : list) {
                JpInvertorElecHistoryMonthDto da=null;
                for (JpInvertorElecHistoryMonthDto jpInvertorElecHistoryMonthDto : li) {
                    if(jpInvertorElecHistoryMonthDto.getDay().equals(s)){
                        da=jpInvertorElecHistoryMonthDto;
                        break;
                    }
                }
                if(da==null){
                    da=new JpInvertorElecHistoryMonthDto();
                    da.setDay(s);
                    da.setSnCode(invertor.getSnCode().trim());
                    da.setYearMonth(monthStr);
                    da.setUAcCurrent(null);
                    da.setUAcVoltage(null);
                    da.setVAcVoltage(null);
                    da.setVAcCurrent(null);
                    da.setWAcCurrent(null);
                    da.setWAcVoltage(null);
                }
                lidata.add(da) ;
            }


			return lidata;
		}
		return new ArrayList<>();
	}




    public static List<String> dayReport(Date month) {

        List<String> list=new ArrayList<>();

        Calendar cal = Calendar.getInstance();
        cal.setTime(month);//month 为指定月份任意日期
        int year = cal.get(Calendar.YEAR);
        int m = cal.get(Calendar.MONTH)+1;
        int dayNumOfMonth = getDaysByYearMonth(year, m);
        cal.set(Calendar.DAY_OF_MONTH, 1);// 从一号开始

        for (int i = 0; i < dayNumOfMonth; i++ ) {

            list.add(String.valueOf(i+1));
        }

        return list;
    }

    public static int getDaysByYearMonth(int year, int month) {

        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }
	/**
	 * 列表查询 示例
	 */
	public List<JpInvertorElecHistoryYearDto> yearList(long id, Date year) {
		JpInverter invertor = jpInvertorServiceImpl.getById(id);
		Calendar cal = Calendar.getInstance();
		cal.setTime(year);
		String yearStr = String.valueOf(cal.get(Calendar.YEAR));
		if (invertor != null) {
            List<JpInvertorElecHistoryYearDto> list=this.baseMapper.yearList(invertor.getSnCode().trim(), invertor.getThirdStationId(), yearStr);
            List<JpInvertorElecHistoryYearDto> lidata=new ArrayList<>();

            for (int i = 1; i < 13; i++) {
                JpInvertorElecHistoryYearDto da=null;
                for (JpInvertorElecHistoryYearDto jpInvertorElecHistoryYearDto : list) {
                    if(jpInvertorElecHistoryYearDto.getMonth().equals(String.valueOf(i))){
                        da=jpInvertorElecHistoryYearDto;
                        break;
                    }
                }
                if(da==null){
                    da=new JpInvertorElecHistoryYearDto();
                    da.setMonth(String.valueOf(i));
                    da.setSnCode(invertor.getSnCode().trim());
                    da.setYear(yearStr);
                    da.setUAcCurrent(null);
                    da.setUAcVoltage(null);
                    da.setVAcVoltage(null);
                    da.setVAcCurrent(null);
                    da.setWAcCurrent(null);
                    da.setWAcVoltage(null);
                }
                lidata.add(da) ;

            }
            return lidata;
		}
		return new ArrayList<>();
	}

	/**
	 * 列表查询 示例
	 */
	public List<JpInvertorElecHistoryAllDto> allList(long id) {
		JpInverter invertor = jpInvertorServiceImpl.getById(id);

		if (invertor != null) {
            List<JpInvertorElecHistoryAllDto> li=  this.baseMapper.allList(invertor.getSnCode().trim(), invertor.getThirdStationId());

            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            int monthStr = cal.get(Calendar.YEAR);
            List<JpInvertorElecHistoryAllDto> lidata=new ArrayList<>();
            for (int i = monthStr-5; i < monthStr+1; i++) {
                JpInvertorElecHistoryAllDto da=null;
                for (JpInvertorElecHistoryAllDto jpInvertorElecHistoryAllDto : li) {
                    if(jpInvertorElecHistoryAllDto.getYear().equals(String.valueOf(i))){
                        da=jpInvertorElecHistoryAllDto;
                        break;
                    }
                }
                if(da==null){
                    da=new JpInvertorElecHistoryAllDto();
                    da.setYear(String.valueOf(i));
                    da.setSnCode(invertor.getSnCode().trim());
                    da.setUAcCurrent(null);
                    da.setUAcVoltage(null);
                    da.setVAcVoltage(null);
                    da.setVAcCurrent(null);
                    da.setWAcCurrent(null);
                    da.setWAcVoltage(null);
                }
                lidata.add(da) ;

            }
            return lidata;
		}
		return new ArrayList<>();
	}

	@Async
	public Object syncData() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1);
		Date dayTime = cal.getTime();
		int day = cal.get(Calendar.DATE);
		int month = cal.get(Calendar.MONTH) + 1;
		int year = cal.get(Calendar.YEAR);
		// 月表
		List<Map<String, Object>> monthList = this.baseMapper.dayToMonth(TimeUtil.getStartTimeOfDay(dayTime),
				TimeUtil.getEndTimeOfDay(dayTime));
		for (int i = 0; i < monthList.size(); i++) {
			monthList.get(i).put("created_time", dayTime.getTime() + i);
			monthList.get(i).put("day", day);
			monthList.get(i).put("year_month", year + "-" + month);
            monthList.get(i).put("sn_code", monthList.get(i).get("sn_code").toString().trim());
		}
		if (!monthList.isEmpty()) {


            List<JpInvertorElecHistoryMonthDto> listold=   this.baseMapper.monthList(null, null, year + "-" + month);

            if(listold!=null) {

                for (Map<String, Object> map : monthList) {
                    for (JpInvertorElecHistoryMonthDto jpInvertorElecHistoryMonthDto : listold) {
                        if (map.get("third_station_id").toString().equals(jpInvertorElecHistoryMonthDto.getThirdStationId().trim())&&map.get("sn_code").toString().trim().equals(jpInvertorElecHistoryMonthDto.getSnCode().trim())&&map.get("day").toString().equals(jpInvertorElecHistoryMonthDto.getDay())) {
                            map.put("created_time", jpInvertorElecHistoryMonthDto.getCreatedTime());
                        }
                    }

                }
                this.baseMapper.updateMonth(monthList);
            }else{
                this.baseMapper.updateMonth(monthList);
            }



			// 年表
			List<Map<String, Object>> yearList = this.baseMapper.monthToYear(String.valueOf(year + "-" + month));
			List<JpInvertorElecHistoryYearDto> oldYearList = this.baseMapper.yearList(null, null, String.valueOf(year));
			for (int i = 0; i < yearList.size(); i++) {
				Map<String, Object> map = yearList.get(i);
				yearList.get(i).put("year", year);
				yearList.get(i).put("month", month);
				long time = dayTime.getTime() + i;
				for (JpInvertorElecHistoryYearDto dto : oldYearList) {
					if (dto.getThirdStationId() != null && dto.getSnCode() != null
							&& map.get("third_station_id") != null && map.get("sn_code") != null
							&& map.get("month") != null && map.get("year") != null
							&& dto.getThirdStationId().equals(map.get("third_station_id").toString())
							&& dto.getSnCode().trim().equals(map.get("sn_code").toString().trim())
							&& dto.getYear().equals(map.get("year").toString())
							&& dto.getMonth().equals(map.get("month").toString())) {
						time = dto.getCreatedTime();
						break;
					}
				}
				yearList.get(i).put("created_time", time);
			}
			if (!yearList.isEmpty()) {
				this.baseMapper.updateYear(yearList);
				// 总表
				List<Map<String, Object>> allList = this.baseMapper.yearToAll(String.valueOf(year));
				List<JpInvertorElecHistoryAllDto> oldAllList = this.baseMapper.allList(null, null);
				for (int i = 0; i < allList.size(); i++) {
					Map<String, Object> map = allList.get(i);
					allList.get(i).put("year", year);
					long time = dayTime.getTime() + i;
					for (JpInvertorElecHistoryAllDto dto : oldAllList) {
						if (dto.getThirdStationId() != null && dto.getSnCode() != null
								&& map.get("third_station_id") != null && map.get("sn_code") != null
								&& map.get("year") != null
								&& dto.getThirdStationId().equals(map.get("third_station_id").toString())
								&& dto.getSnCode().trim().equals(map.get("sn_code").toString().trim())
								&& dto.getYear().equals(map.get("year").toString())) {
							time = dto.getCreatedTime();
							break;
						}
					}
					allList.get(i).put("created_time", time);
				}
				if (!allList.isEmpty()) {
					this.baseMapper.updateAll(allList);
				}
			}
		}
		return null;
	}
}