package com.huatek.busi.task.transformer;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.entity.BusiOfflineTransformerBrand;
import com.huatek.busi.entity.IecBydworkParam;
import com.huatek.busi.service.BusiTransformerLoadService;
import com.huatek.busi.service.IecBydworkParamService;
import com.huatek.busi.service.transformer.BusiOfflineTransformerBrandService;
import com.huatek.busi.task.base.AbstractBusiTaskExecutor;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: TransformerLoadRateTask
 * @FullClassPath: com.huatek.busi.task.TransformerLoadRateTask
 * @Description: 变压器负荷率任务
 * @author: Arno
 * @date: Sep 3, 2019 4:00:51 PM
 * @version: 1.0
 */

@Slf4j
@Component("transformerLoadRateTask")
public class TransformerLoadRateTask extends AbstractBusiTaskExecutor{
	/** @Fields busiOfflineTransformerBrandService : 变压器标牌服务 */
	@Autowired
	public BusiOfflineTransformerBrandService busiOfflineTransformerBrandService;
	@Autowired
	private IecBydworkParamService iecBydworkParamService;
	@Autowired
	private BusiTransformerLoadService busiTransformerLoadService;

	@Override
	public void execute() {
		List<BusiOfflineTransformerBrand> transformerlist = this.getTransformerlist();
		LocalDate startDate =  LocalDate.now();
		LocalDate newDate = startDate.plusDays(-1);
		if (!transformerlist.isEmpty()) {
			for(BusiOfflineTransformerBrand barnd : transformerlist){
				String siteId = barnd.getSiteId();
				String mainTreeId = barnd.getMainEquipmentId();
				String ratedCapacity  = barnd.getRatedCapacity();
				if(StringUtils.isNoneBlank(ratedCapacity)){
					Double loadRate = calcLoad(siteId, mainTreeId, ratedCapacity,newDate);
					log.debug("---->>日期：{}, 变压器：{}, 负荷率{} ", newDate,  barnd.getTransformerName(), new DecimalFormat("0.00%").format(loadRate)  );
					busiTransformerLoadService.saveOrUpdateLoad(siteId, mainTreeId, barnd.getId(), newDate, loadRate.toString());
				}
			}
		}
			//testDemo(newDate);
	}

	@Override
    public void execute(String params) {
        LocalDate day = toLocalDate(params);
        execute(day);
    }

	@Override
    public void execute(LocalDate day) {
		List<BusiOfflineTransformerBrand> transformerlist = this.getTransformerlist();
		LocalDate startDate =  day;
		LocalDate newDate = startDate.plusDays(-1);
		if (!transformerlist.isEmpty()) {
			for(BusiOfflineTransformerBrand barnd : transformerlist){
				String siteId = barnd.getSiteId();
				String mainTreeId = barnd.getMainEquipmentId();
				String ratedCapacity  = barnd.getRatedCapacity();
				if(StringUtils.isNoneBlank(ratedCapacity)){
					Double loadRate = calcLoad(siteId, mainTreeId, ratedCapacity,newDate);
					log.debug("---->>日期：{}, 变压器：{}, 负荷率{} ", newDate,  barnd.getTransformerName(), new DecimalFormat("0.00%").format(loadRate)  );
					busiTransformerLoadService.saveOrUpdateLoad(siteId, mainTreeId, barnd.getId(), newDate, loadRate.toString());
				}
			}
		}
    }
	
//	private void testDemo(LocalDate newDate) {
//		BusiOfflineTransformerBrand barnd = busiOfflineTransformerBrandService.getByPK("3d30f5c700dd407b8b27598a34c2e4cd");
//		String siteId = barnd.getSiteId();
//		String mainTreeId = barnd.getMainEquipmentId();
//		String ratedCapacity  = barnd.getRatedCapacity();
//		Double loadRate = calcLoad(siteId, mainTreeId, ratedCapacity);
//		BusiTransformerLoad load = new BusiTransformerLoad();
//		load.setLoadRate(loadRate.toString());
//		load.setLoadTime(newDate);
//		load.setMainTreeId(mainTreeId);
//		load.setEquipmentId(barnd.getId());
//		load.setSiteId(siteId);
//		load.setId(Uuid.getUUID());
//		busiTransformerLoadService.saveLoad(load);
//	}

	/**
	 * @Title: getTransformerlist
	 * @Description: 获取变压器列表
	 * @createDate: Aug 30, 2019 1:24:54 PM
	 * @return List<BusiOfflineTransformerBrand>
	 */
	private List<BusiOfflineTransformerBrand> getTransformerlist() {
		return busiOfflineTransformerBrandService.findAll();
	}
	public static Date localDate2Date(LocalDate localDate) {
        if(null == localDate) {
            return null;
        }
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }
	
	public Double calcLoad(String siteId, String eqmCode,  String ratedCapacity,LocalDate date){
		
//		Date start = DateUtil.getStartDate();
//		Date end = DateUtil.getEndDate();
//		Date end2 =DateUtil.getCurrentDate();
		
		Date start = localDate2Date(date);
		Date end = DateUtil.getEndDate(date);
		Date end2 =DateUtil.getCurrentDate(date);
		
		log.info("----------------开始时间："+start);
		log.info("----------------结束时间end："+end);
		log.info("----------------结束时间end2："+end2);
		
		double loadRate = 0d; 
		double total = 0d;
		double totalCapacity = Double.parseDouble(ratedCapacity) *1000d*1000d*24d*60d*60d;
		
		log.info("----------------标牌额定容量："+ratedCapacity);
		log.info("----------------转化公式 ratedCapacity*1000d*1000d*24d*60d*60d");
		log.info("----------------转化成秒后的容量："+totalCapacity);
		
//		List<IecBydworkParam> list = new ArrayList<>();
//		List<IecBydworkParam> list1 = iecBydworkParamService.getWorks("1", siteId, eqmCode, start, start);
//		if(CollectionUtils.isNotEmpty(list1)){
//			list.addAll(list1);
//		}
//		List<IecBydworkParam> list2 = iecBydworkParamService.getWorks("2", siteId, eqmCode, start, end2);
//		if(CollectionUtils.isNotEmpty(list2)){
//			list.addAll(list2);
//		}
//		List<IecBydworkParam> list3 = iecBydworkParamService.getWorks("3", siteId, eqmCode, start, end2);
//		if(CollectionUtils.isNotEmpty(list3)){
//			list.addAll(list3);
//		}
		
		List<IecBydworkParam> list = iecBydworkParamService.getIecBydworkParamWorks(siteId, eqmCode, start, end2);
//		if(CollectionUtils.isNotEmpty(list3)){
//			list.addAll(list3);
//		}

		
		long shichang=0;
		if(CollectionUtils.isNotEmpty(list)){
			for (IecBydworkParam iecBydworkParam : list) {
				double higthCurrent = iecBydworkParam.getHigthCurrent().doubleValue();
				double higthVoltage = iecBydworkParam.getHigthVoltage().doubleValue();
				double diffSeconds;
				if(iecBydworkParam.getStopTime().getTime() > end.getTime()){
					diffSeconds = calcDiffSeconds(iecBydworkParam.getStopTime(), end2);
					shichang+=diffSeconds;
					total+=diffSeconds*higthCurrent*higthVoltage;
				}else{
					diffSeconds = calcDiffSeconds(iecBydworkParam.getStopTime(), iecBydworkParam.getStartTime());
					shichang+=diffSeconds;
					total+=diffSeconds*higthCurrent*higthVoltage;
				}
				log.info("----------------工作时长："+diffSeconds+",电流："+higthCurrent+",电压："+higthVoltage);
			}
			log.info("---------------------------总时长:"+shichang);
			log.info("总功率：{}",total);
			log.info("总容量：{}",totalCapacity);
			
			loadRate =total/totalCapacity;
			log.info("负荷：{}",loadRate);
		}
		return new BigDecimal(loadRate).setScale(4, RoundingMode.UP).doubleValue();
	}
	
	
	public double calcDiffSeconds (Date begin, Date end){
		long from = end.getTime();
		long to =begin.getTime();
		long l = to - from;
		double hours = (l)/1000d;
		return hours;
	}
	
//    public static void main(String[] args)
//    {
//        log.info(new BigDecimal(0.002364345566222).setScale(4, RoundingMode.UP).doubleValue());
//    }
}