package com.ruoyi.ss.billEleRecord.service.impl;

import com.ruoyi.ss.billEleRecord.domain.BillEleRecord;
import com.ruoyi.ss.billEleRecord.service.BillEleRecordConverter;
import com.ruoyi.ss.billEleRecord.service.BillEleRecordService;
import com.ruoyi.ss.device.domain.vo.DeviceVO;
import com.ruoyi.ss.suit.domain.enums.SuitFeeType;
import com.ruoyi.ss.transactionBill.domain.vo.TransactionBillVO;
import com.ruoyi.ss.transactionBill.utils.RechargeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author wjh
 * 2025/1/4
 */
@Service
public class BillEleRecordConverterImpl implements BillEleRecordConverter {

    @Autowired
    private BillEleRecordService billEleRecordService;

    @Override
    public BillEleRecord toPo(TransactionBillVO bill, DeviceVO device, LocalDateTime time, LocalDateTime chargeTime) {
        if (device == null || bill == null) {
            return null;
        }
        if (!SuitFeeType.TIMING_COUNT.getType().equals(bill.getSuitFeeType())) {
            return null;
        }

        // 计费时间
        LocalDateTime timeStart = chargeTime.withMinute(0).withSecond(0);
        LocalDateTime timeEnd = chargeTime.withMinute(59).withSecond(59);
        if (bill.getSuitStartTime() != null && timeStart.isBefore(bill.getSuitStartTime())) {
            timeStart = bill.getSuitStartTime();
        }
        if (bill.getSuitEndTime() != null && timeEnd.isAfter(bill.getSuitEndTime())) {
            timeEnd = bill.getSuitEndTime();
        }

        // 当前时间段的单价（元/度）
        BigDecimal price = RechargeUtils.getGearAmount(bill, chargeTime.getHour());

        // 查询订单在最大记录的用电量
        BigDecimal maxEle = billEleRecordService.selectMaxEleByBillId(bill.getBillId());
        if (maxEle == null) {
            maxEle = bill.getSuitStartEle();
        }

        BillEleRecord po = new BillEleRecord();
        po.setBillId(bill.getBillId());
        po.setTotalEle(device.getTotalElectriQuantity());
        po.setUsedEle(device.getTotalElectriQuantity().subtract(maxEle));
        po.setRecordTime(time);
        po.setTimeStart(timeStart);
        po.setTimeEnd(timeEnd);
        po.setPrice(price);
        po.setTotalPrice(po.getPrice().multiply(po.getUsedEle()));

        return po;
    }
}
