package com.jsowell.quartz.task;

import com.jsowell.common.constant.Constants;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.PileStationInfo;
import com.jsowell.pile.domain.ykcCommond.PublishPileBillingTemplateCommand;
import com.jsowell.pile.domain.ykcCommond.StartChargingCommand;
import com.jsowell.pile.service.IPileStationInfoService;
import com.jsowell.pile.service.YKCPushCommandService;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.service.IOrderBasicInfoService;
import com.jsowell.pile.service.IPileBillingTemplateService;
import com.jsowell.pile.vo.web.BillingTemplateVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component("jsowellTask")
public class JsowellTask {

	private final Logger log = LoggerFactory.getLogger(JsowellTask.class);

	@Autowired
	private IOrderBasicInfoService orderBasicInfoService;

	@Autowired
	private IPileBillingTemplateService pileBillingTemplateService;

	@Autowired
	private YKCPushCommandService ykcPushCommandService;

	@Autowired
	private IPileStationInfoService pileStationInfoService;

	/**
	 * 关闭15分钟未支付的订单
	 * close15MinutesOfUnpaidOrders
	 */
	public void close15MinutesOfUnpaidOrders() {
		// log.info("关闭15分钟未支付的订单");
		orderBasicInfoService.close15MinutesOfUnpaidOrders();
	}

	/**
	 * 关闭启动失败的订单
	 * 订单支付成功，在15分钟内未启动，
	 */
	public void closeStartFailedOrder() {
		// 查询出最近2天支付成功，并且订单状态为未启动的订单
		String startTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.addDays(new Date(), -2));
		String endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date());
		orderBasicInfoService.closeStartFailedOrder(startTime, endTime);
	}

	/**
	 * 查询预约充电的订单并启动
	 */
	public void appointmentOrderStart() {
		// 查询出 已支付 设置预约充电 未启动 的订单
		LocalDateTime now = LocalDateTime.now();
		List<OrderBasicInfo> list = orderBasicInfoService.getAppointmentOrder(now);
		if (CollectionUtils.isEmpty(list)) {
			return;
		}
		log.info("待启动充电订单:{}", list);
		for (OrderBasicInfo orderInfo : list) {
			// 下发充电桩设置指令
			String pileSn = orderInfo.getPileSn();
			// 发送启动充电指令前，再次下发计费模板
			BillingTemplateVO billingTemplateVO = pileBillingTemplateService.selectBillingTemplateDetailByPileSn(pileSn);
			if (billingTemplateVO != null) {
				PublishPileBillingTemplateCommand command = PublishPileBillingTemplateCommand.builder()
						.billingTemplateVO(billingTemplateVO)
						.pileSn(pileSn)
						.build();
				ykcPushCommandService.pushPublishPileBillingTemplate(command);
			}
			// 发送启动指令
			String connectorCode = orderInfo.getConnectorCode();
			String transactionCode = orderInfo.getTransactionCode();
			BigDecimal payAmount = orderInfo.getPayAmount();

			if (StringUtils.isEmpty(pileSn) || StringUtils.isEmpty(connectorCode)) {
				log.warn("appointmentOrderStart-远程启动充电, 充电桩编号和枪口号不能为空");
				return;
			}
			log.info("appointmentOrderStart 远程启动充电, 桩号：{}, 枪口号：{}", pileSn, connectorCode);
			StartChargingCommand startChargingCommand = StartChargingCommand.builder()
					.pileSn(pileSn)
					.connectorCode(connectorCode)
					.transactionCode(transactionCode)
					.chargeAmount(payAmount)
					.build();
			ykcPushCommandService.pushStartChargingCommand(startChargingCommand);
		}
	}

	/**
	 * 计算站点订单报表
	 * jsowellTask.calculateTheSiteOrdersReport()
	 */
	public void calculateTheSiteOrdersReport() {
		// 查询出所有站点
		PileStationInfo pileStationInfo = new PileStationInfo();
		pileStationInfo.setDelFlag(Constants.ZERO);
		List<PileStationInfo> list = pileStationInfoService.selectPileStationInfoList(pileStationInfo);
		if (CollectionUtils.isEmpty(list)) {
			return;
		}
		// 计算每个站点前一天的报表
		for (PileStationInfo stationInfo : list) {
			try {
				orderBasicInfoService.generateDailyOrderReports(stationInfo.getId() + "");
			} catch (Exception e) {
				log.error("计算站点订单报表 发生异常 stationId:{}", stationInfo.getId(), e);
			}
		}
	}
}
