package cn.iocoder.yudao.module.energy.service.match;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.asset.dal.dataobject.contract.ContractDO;
import cn.iocoder.yudao.module.asset.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.asset.dal.dataobject.vehicle.VehicleBaseDO;
import cn.iocoder.yudao.module.asset.dal.mysql.contract.ContractMapper;
import cn.iocoder.yudao.module.asset.dal.mysql.customer.CustomerMapper;
import cn.iocoder.yudao.module.asset.dal.mysql.vehicle.VehicleBaseMapper;
import cn.iocoder.yudao.module.energy.dal.dataobject.record.EnergyHydrogenRecordDO;
import cn.iocoder.yudao.module.energy.dal.mysql.record.EnergyHydrogenRecordMapper;
import cn.iocoder.yudao.module.energy.service.match.dto.MatchResultDTO;
import cn.iocoder.yudao.module.energy.service.match.vo.MatchResultVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 加氢记录匹配服务实现
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class HydrogenMatchServiceImpl implements HydrogenMatchService {

    @Resource
    private EnergyHydrogenRecordMapper hydrogenRecordMapper;

    @Resource
    private VehicleBaseMapper vehicleBaseMapper;

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private ContractMapper contractMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MatchResultDTO batchMatch(List<Long> recordIds) {
        MatchResultDTO result = new MatchResultDTO();

        for (Long recordId : recordIds) {
            EnergyHydrogenRecordDO record = hydrogenRecordMapper.selectById(recordId);
            if (record == null) {
                log.warn("[batchMatch] 记录不存在，recordId={}", recordId);
                result.setFailCount(result.getFailCount() + 1);
                result.getFailIds().add(recordId);
                continue;
            }

            // 执行匹配
            MatchResultVO matchResult = matchRecord(record);

            // 更新记录
            EnergyHydrogenRecordDO updateRecord = new EnergyHydrogenRecordDO();
            updateRecord.setId(recordId);
            updateRecord.setVehicleId(matchResult.getVehicleId());
            updateRecord.setCustomerId(matchResult.getCustomerId());
            updateRecord.setMatchStatus(matchResult.getMatchStatus());
            updateRecord.setUpdateTime(LocalDateTime.now());

            hydrogenRecordMapper.updateById(updateRecord);

            // 统计结果
            if (matchResult.getMatchStatus() == 0) {
                result.setSuccessCount(result.getSuccessCount() + 1);
                result.getSuccessIds().add(recordId);
                log.info("[batchMatch] 匹配成功，recordId={}, vehicleId={}, customerId={}, contractId={}",
                        recordId, matchResult.getVehicleId(), matchResult.getCustomerId(), matchResult.getContractId());
            } else {
                result.setFailCount(result.getFailCount() + 1);
                result.getFailIds().add(recordId);
                log.warn("[batchMatch] 匹配失败，recordId={}, status={}, message={}",
                        recordId, matchResult.getMatchStatus(), matchResult.getMatchMessage());
            }
        }

        return result;
    }

    @Override
    public MatchResultVO matchRecord(EnergyHydrogenRecordDO record) {
        MatchResultVO result = new MatchResultVO();

        // 1. 匹配车辆（通过车牌号）
        if (StrUtil.isNotBlank(record.getPlateNumber())) {
            VehicleBaseDO vehicle = vehicleBaseMapper.selectOne(
                    VehicleBaseDO::getPlateNo, record.getPlateNumber()
            );
            if (vehicle != null) {
                result.setVehicleId(vehicle.getId());
                log.debug("[matchRecord] 车辆匹配成功，plateNumber={}, vehicleId={}",
                        record.getPlateNumber(), vehicle.getId());
            }
        }

        // 2. 匹配客户
        // 2.1 如果车辆未匹配，尝试通过客户名称模糊匹配
        if (result.getCustomerId() == null && StrUtil.isNotBlank(record.getPlateNumber())) {
            // 注意：这里假设 plateNumber 字段可能包含客户信息，实际需要根据业务调整
            // 如果 Record 有独立的 customerName 字段，应该使用那个字段
            CustomerDO customer = customerMapper.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CustomerDO>()
                            .like(CustomerDO::getCustomerName, record.getPlateNumber())
                            .last("LIMIT 1")
            );
            if (customer != null) {
                result.setCustomerId(customer.getId());
                log.debug("[matchRecord] 客户匹配成功（通过名称），customerId={}", customer.getId());
            }
        }

        // 3. 匹配合同（通过客户ID）
        if (result.getCustomerId() != null) {
            ContractDO contract = contractMapper.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ContractDO>()
                            .eq(ContractDO::getCustomerId, result.getCustomerId())
                            .eq(ContractDO::getContractStatus, 2) // 2=进行中
                            .gt(ContractDO::getEndDate, record.getHydrogenDate())
                            .orderByDesc(ContractDO::getStartDate)
                            .last("LIMIT 1")
            );
            if (contract != null) {
                result.setContractId(contract.getId());
                log.debug("[matchRecord] 合同匹配成功，contractId={}", contract.getId());
            }
        }

        // 4. 判断匹配状态
        if (result.getVehicleId() != null && result.getCustomerId() != null && result.getContractId() != null) {
            result.setMatchStatus(0); // 完全匹配
            result.setMatchMessage("自动匹配成功");
        } else if (result.getCustomerId() != null) {
            result.setMatchStatus(1); // 部分匹配
            result.setMatchMessage("客户匹配成功，但缺少车辆或合同信息");
        } else {
            result.setMatchStatus(2); // 未匹配
            result.setMatchMessage("未找到匹配的客户");
        }

        return result;
    }

}
