package com.zsElectric.boot.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsElectric.boot.business.converter.BannerInfoConverter;
import com.zsElectric.boot.business.mapper.*;
import com.zsElectric.boot.business.model.entity.*;
import com.zsElectric.boot.business.model.query.StationInfoQuery;
import com.zsElectric.boot.business.model.vo.*;
import com.zsElectric.boot.business.model.vo.applet.AppChargingCostVO;
import com.zsElectric.boot.business.model.vo.applet.AppStationSearchVO;
import com.zsElectric.boot.business.model.vo.applet.AppletConnectorDetailVO;
import com.zsElectric.boot.business.service.AppletHomeService;
import com.zsElectric.boot.charging.entity.*;
import com.zsElectric.boot.charging.mapper.ThirdPartyChargeStatusMapper;
import com.zsElectric.boot.charging.mapper.ThirdPartyConnectorInfoMapper;
import com.zsElectric.boot.charging.mapper.ThirdPartyEquipmentPricePolicyMapper;
import com.zsElectric.boot.charging.mapper.ThirdPartyPolicyInfoMapper;
import com.zsElectric.boot.security.util.SecurityUtils;
import com.zsElectric.boot.system.mapper.DictItemMapper;
import com.zsElectric.boot.system.model.entity.DictItem;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class AppletHomeServiceImpl implements AppletHomeService {

    private final ThirdPartyStationInfoMapper thirdPartyStationInfoMapper;
    private final UserFirmMapper userFirmMapper;
    private final UserAccountMapper userAccountMapper;
    private final BannerInfoMapper bannerInfoMapper;
    private final BannerInfoConverter bannerInfoConverter;
    private final ThirdPartyConnectorInfoMapper thirdPartyConnectorInfoMapper;
    private final ThirdPartyEquipmentInfoMapper thirdPartyEquipmentInfoMapper;
    private final ThirdPartyEquipmentPricePolicyMapper thirdPartyEquipmentPricePolicyMapper;
    private final ThirdPartyPolicyInfoMapper thirdPartyPolicyInfoMapper;
    private final PolicyFeeMapper policyFeeMapper;
    private final ThirdPartyChargeStatusMapper thirdPartyChargeStatusMapper;
    private final ChargeOrderInfoMapper chargeOrderInfoMapper;
    private final DiscountsActivityMapper discountsActivityMapper;
    private final DictItemMapper dictItemMapper;

    /**
     * 时间格式化器 HHmmss
     */
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HHmmss");
    
    /**
     * 默认运营费字典编码
     */
    private static final String DEFAULT_OP_FEE_DICT_CODE = "default_op_fee";

    @Override
    public IPage<StationInfoVO> getStationInfoPage(StationInfoQuery queryParams) {
        
        // 查询用户是否为企业用户，获取企业ID
        Long firmId = null;
        boolean isFirmUser = false;
        if (queryParams.getUserId() != null) {
            UserFirm userFirm = userFirmMapper.selectOne(
                    new LambdaQueryWrapper<UserFirm>()
                            .eq(UserFirm::getUserId, queryParams.getUserId())
                            .last("LIMIT 1")
            );
            if (userFirm != null) {
                firmId = userFirm.getFirmId();
                isFirmUser = true;
            }
        }
        
        // 获取当前时间(HHmmss格式)
        String currentTime = LocalTime.now().format(TIME_FORMATTER);
        
        // 构建分页对象
        Page<StationInfoVO> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());
        
        // 执行查询
        IPage<StationInfoVO> resultPage = thirdPartyStationInfoMapper.selectAppletStationInfoPage(
                page, queryParams, currentTime, firmId
        );
        
        // 设置是否企业用户标识
        // 只有当用户属于企业且企业有设置价格时，才标记为企业用户
        final boolean finalIsFirmUser = isFirmUser;
        resultPage.getRecords().forEach(vo -> {
            // 如果是企业用户但企业价为null，说明该企业未设置价格，firmUser应为false
            boolean hasFirmPrice = vo.getEnterprisePrice() != null;
            vo.setFirmUser(finalIsFirmUser && hasFirmPrice);
        });
        
        return resultPage;
    }

    @Override
    public List<StationInfoMapVO> getStationInfoMapList(BigDecimal longitude, BigDecimal latitude) {
        // 获取当前时间(HHmmss格式)
        String currentTime = LocalTime.now().format(TIME_FORMATTER);
        
        // 查询站点列表（按距离排序）
        return thirdPartyStationInfoMapper.selectStationMapList(
                longitude, latitude, currentTime
        );
    }

    @Override
    public List<BannerInfoVO> getBannerList(Integer location) {
        // 查询启用状态的Banner，按排序字段降序
        List<BannerInfo> bannerList = bannerInfoMapper.selectList(
                new LambdaQueryWrapper<BannerInfo>()
                        .eq(BannerInfo::getStatus, 1)
                        .eq(BannerInfo::getLocation, location)
                        .orderByDesc(BannerInfo::getSort)
        );
        return bannerInfoConverter.toVO(bannerList);
    }

    @Override
    public AppletStationDetailVO getStationDetail(Long stationId, BigDecimal longitude, BigDecimal latitude) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        
        // 查询用户是否为企业用户，获取企业ID
        Long firmId = null;
        boolean isFirmUser = false;
        if (userId != null) {
            UserFirm userFirm = userFirmMapper.selectOne(
                    new LambdaQueryWrapper<UserFirm>()
                            .eq(UserFirm::getUserId, userId)
                            .last("LIMIT 1")
            );
            if (userFirm != null) {
                firmId = userFirm.getFirmId();
                isFirmUser = true;
            }
        }
        
        // 获取当前时间(HHmmss格式)
        String currentTime = LocalTime.now().format(TIME_FORMATTER);
        
        // 查询站点详情基本信息
        AppletStationDetailVO result = thirdPartyStationInfoMapper.selectStationDetail(
                stationId, longitude, latitude, currentTime, firmId
        );
        
        if (result == null) {
            return null;
        }
        
        // 设置是否企业用户
        result.setFirmUser(isFirmUser);
        
        // 计算预计省多少(当前价 - 原价，如果为负则取绝对值)
        if (result.getCurrentPrice() != null && result.getOriginalPrice() != null) {
            BigDecimal saving = result.getOriginalPrice().subtract(result.getCurrentPrice());
            result.setEstimatedSaving(saving.compareTo(BigDecimal.ZERO) > 0 ? saving : BigDecimal.ZERO);
            result.setShowSpecialPriceTag(saving.compareTo(BigDecimal.ZERO) > 0);
        }
        
        // 查询站点对应的stationId
        ThirdPartyStationInfo stationInfo = thirdPartyStationInfoMapper.selectById(stationId);
        if (stationInfo == null) {
            return result;
        }
        
        // 根据站点stationId查询设备列表（third_party_equipment_info）
        List<ThirdPartyEquipmentInfo> equipmentList = thirdPartyEquipmentInfoMapper.selectList(
                new LambdaQueryWrapper<ThirdPartyEquipmentInfo>()
                        .eq(ThirdPartyEquipmentInfo::getStationId, stationInfo.getStationId())
        );
        
        // 构建设备ID到设备类型的映射
        Map<String, Integer> equipmentTypeMap = equipmentList.stream()
                .collect(Collectors.toMap(
                        ThirdPartyEquipmentInfo::getEquipmentId,
                        e -> e.getEquipmentType() != null ? e.getEquipmentType() : 0,
                        (v1, v2) -> v1
                ));
        
        // 根据设备列表的equipmentId查询充电接口信息（third_party_connector_info）
        List<ThirdPartyConnectorInfo> connectorList = new ArrayList<>();
        if (!equipmentList.isEmpty()) {
            List<String> equipmentIds = equipmentList.stream()
                    .map(ThirdPartyEquipmentInfo::getEquipmentId)
                    .collect(Collectors.toList());
            connectorList = thirdPartyConnectorInfoMapper.selectList(
                    new LambdaQueryWrapper<ThirdPartyConnectorInfo>()
                            .in(ThirdPartyConnectorInfo::getEquipmentId, equipmentIds)
            );
        }
        
        // 统计终端状态
        int idleCount = 0;
        int occupiedCount = 0;
        int offlineCount = 0;
        
        List<AppletStationDetailVO.ConnectorInfoVO> connectorVOList = new ArrayList<>();
        for (ThirdPartyConnectorInfo connector : connectorList) {
            AppletStationDetailVO.ConnectorInfoVO vo = new AppletStationDetailVO.ConnectorInfoVO();
            vo.setConnectorId(connector.getId());
            vo.setConnectorName(connector.getConnectorName());
            vo.setConnectorCode(connector.getConnectorId());
            
            // 设备分类：从设备表获取设备类型（1-直流设备,2-交流设备,3-交直流一体设备,4-无线设备,5-其他）
            Integer equipmentType = equipmentTypeMap.get(connector.getEquipmentId());
            if (equipmentType != null) {
                switch (equipmentType) {
                    case 1:
                        vo.setEquipmentType("直流设备");
                        break;
                    case 2:
                        vo.setEquipmentType("交流设备");
                        break;
                    case 3:
                        vo.setEquipmentType("交直流一体设备");
                        break;
                    case 4:
                        vo.setEquipmentType("无线设备");
                        break;
                    case 5:
                        vo.setEquipmentType("其他");
                        break;
                    default:
                        vo.setEquipmentType("未知");
                }
            }
            
            // 从充电接口表获取实际状态
            // 0-离网,1-空闲,2-占用(未充电),3-占用(充电中),4-占用(预约锁定),255-故障
            Integer connectorStatus = connector.getStatus();
            if (connectorStatus == null) {
                // 默认为离网
                connectorStatus = 0;
            }
            vo.setStatus(connectorStatus);
            
            // 设置状态名称并统计
            switch (connectorStatus) {
                case 0:
                    vo.setStatusName("离网");
                    offlineCount++;
                    break;
                case 1:
                    vo.setStatusName("空闲");
                    idleCount++;
                    break;
                case 2:
                    vo.setStatusName("占用(未充电)");
                    occupiedCount++;
                    break;
                case 3:
                    vo.setStatusName("占用(充电中)");
                    occupiedCount++;
                    break;
                case 4:
                    vo.setStatusName("占用(预约锁定)");
                    occupiedCount++;
                    break;
                case 255:
                    vo.setStatusName("故障");
                    offlineCount++;
                    break;
                default:
                    vo.setStatusName("未知");
                    offlineCount++;
            }
            
            connectorVOList.add(vo);
        }
        
        result.setConnectorList(connectorVOList);
        result.setIdleCount(idleCount);
        result.setOccupiedCount(occupiedCount);
        result.setOfflineCount(offlineCount);
        
        return result;
    }

    @Override
    public AppletConnectorListVO getConnectorList(Long stationId) {
        // 查询站点信息
        ThirdPartyStationInfo stationInfo = thirdPartyStationInfoMapper.selectById(stationId);
        if (stationInfo == null) {
            return null;
        }
        
        AppletConnectorListVO result = new AppletConnectorListVO();
        result.setStationId(stationId);
        result.setStationName(stationInfo.getStationName());
        result.setTips(stationInfo.getStationTips());
        
        // 根据站点stationId查询设备列表
        List<ThirdPartyEquipmentInfo> equipmentList = thirdPartyEquipmentInfoMapper.selectList(
                new LambdaQueryWrapper<ThirdPartyEquipmentInfo>()
                        .eq(ThirdPartyEquipmentInfo::getStationId, stationInfo.getStationId())
        );
        
        // 构建设备ID到设备类型的映射
        Map<String, Integer> equipmentTypeMap = equipmentList.stream()
                .collect(Collectors.toMap(
                        ThirdPartyEquipmentInfo::getEquipmentId,
                        e -> e.getEquipmentType() != null ? e.getEquipmentType() : 0,
                        (v1, v2) -> v1
                ));
        
        // 查询充电接口信息
        List<ThirdPartyConnectorInfo> connectorList = new ArrayList<>();
        if (!equipmentList.isEmpty()) {
            List<String> equipmentIds = equipmentList.stream()
                    .map(ThirdPartyEquipmentInfo::getEquipmentId)
                    .collect(Collectors.toList());
            connectorList = thirdPartyConnectorInfoMapper.selectList(
                    new LambdaQueryWrapper<ThirdPartyConnectorInfo>()
                            .in(ThirdPartyConnectorInfo::getEquipmentId, equipmentIds)
            );
        }
        
        // 统计终端状态
        int idleCount = 0;
        int occupiedCount = 0;
        int offlineCount = 0;
        
        List<AppletConnectorListVO.ConnectorItemVO> connectorVOList = new ArrayList<>();
        for (ThirdPartyConnectorInfo connector : connectorList) {
            AppletConnectorListVO.ConnectorItemVO vo = new AppletConnectorListVO.ConnectorItemVO();
            vo.setConnectorId(connector.getId());
            vo.setConnectorName(connector.getConnectorName());
            vo.setConnectorCode(connector.getConnectorId());
            
            // 设备分类
            Integer equipmentType = equipmentTypeMap.get(connector.getEquipmentId());
            vo.setEquipmentType(getEquipmentTypeName(equipmentType));
            
            // 状态处理
            Integer connectorStatus = connector.getStatus();
            if (connectorStatus == null) {
                connectorStatus = 0;
            }
            vo.setStatus(connectorStatus);
            vo.setStatusName(getStatusName(connectorStatus));
            
            // 统计
            switch (connectorStatus) {
                case 1:
                    idleCount++;
                    break;
                case 2:
                case 3:
                case 4:
                    occupiedCount++;
                    break;
                default:
                    offlineCount++;
            }
            
            connectorVOList.add(vo);
        }
        
        result.setConnectorList(connectorVOList);
        result.setIdleCount(idleCount);
        result.setOccupiedCount(occupiedCount);
        result.setOfflineCount(offlineCount);
        
        return result;
    }

    @Override
    public AppletStationPriceListVO getStationPriceList(Long stationId) {
        // 查询站点信息
        ThirdPartyStationInfo stationInfo = thirdPartyStationInfoMapper.selectById(stationId);
        if (stationInfo == null) {
            log.warn("站点信息不存在，stationId: {}", stationId);
            return null;
        }
        
        log.info("查询站点价格列表，stationId: {}, stationName: {}, station_id字段: {}", 
                stationId, stationInfo.getStationName(), stationInfo.getStationId());
        
        AppletStationPriceListVO result = new AppletStationPriceListVO();
        result.setStationId(stationId);
        result.setStationName(stationInfo.getStationName());
        result.setTips(stationInfo.getStationTips());
        
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        log.info("当前用户ID: {}", userId);
        
        // 查询用户是否为企业用户，获取企业ID
        Long firmId = null;
        if (userId != null) {
            UserFirm userFirm = userFirmMapper.selectOne(
                    new LambdaQueryWrapper<UserFirm>()
                            .eq(UserFirm::getUserId, userId)
                            .last("LIMIT 1")
            );
            if (userFirm != null) {
                firmId = userFirm.getFirmId();
                log.info("用户所属企业ID: {}", firmId);
            }
        }
        
        // 获取当前时间(HHmmss格式)
        String currentTime = LocalTime.now().format(TIME_FORMATTER);
        log.info("当前时间: {}", currentTime);
        
        // 查询站点对应的价格策略
        // 1. 先查询充电接口
        ThirdPartyConnectorInfo connector = thirdPartyConnectorInfoMapper.selectOne(
                new LambdaQueryWrapper<ThirdPartyConnectorInfo>()
                        .eq(ThirdPartyConnectorInfo::getStationId, stationInfo.getStationId())
                        .last("LIMIT 1")
        );
        
        if (connector == null) {
            log.warn("未找到充电接口信息，station_id: {}", stationInfo.getStationId());
            result.setPriceList(new ArrayList<>());
            return result;
        }
        
        log.info("找到充电接口，connectorId: {}", connector.getConnectorId());
        
        // 2. 查询价格策略
        ThirdPartyEquipmentPricePolicy pricePolicy = thirdPartyEquipmentPricePolicyMapper.selectOne(
                new LambdaQueryWrapper<ThirdPartyEquipmentPricePolicy>()
                        .eq(ThirdPartyEquipmentPricePolicy::getConnectorId, connector.getConnectorId())
                        .eq(ThirdPartyEquipmentPricePolicy::getIsDeleted, 0)
                        .last("LIMIT 1")
        );
        
        if (pricePolicy == null) {
            log.warn("未找到价格策略，connectorId: {}", connector.getConnectorId());
            result.setPriceList(new ArrayList<>());
            return result;
        }
        
        log.info("找到价格策略，pricePolicyId: {}", pricePolicy.getId());
        
        // 3. 查询价格明细列表
        List<ThirdPartyPolicyInfo> policyInfoList = thirdPartyPolicyInfoMapper.selectList(
                new LambdaQueryWrapper<ThirdPartyPolicyInfo>()
                        .eq(ThirdPartyPolicyInfo::getPricePolicyId, pricePolicy.getId())
                        .eq(ThirdPartyPolicyInfo::getIsDeleted, 0)
                        .orderByAsc(ThirdPartyPolicyInfo::getStartTime)
        );
        
        log.info("查询到价格明细记录数: {}", policyInfoList.size());
        
        // 如果没有查询到价格策略明细，说明该站点未配置价格策略，直接返回空列表
        if (policyInfoList.isEmpty()) {
            log.warn("third_party_policy_info表中没有价格策略数据，pricePolicyId: {}", pricePolicy.getId());
            result.setPriceList(new ArrayList<>());
            result.setHasEnterprisePrice(false);
            return result;
        }
        
        // 4. 查询平台价格（salesType=0），用于普通用户的价格计算
        Map<Integer, PolicyFee> platformPriceMap = new HashMap<>();
        List<PolicyFee> platformPolicyFeeList = policyFeeMapper.selectList(
                new LambdaQueryWrapper<PolicyFee>()
                        .eq(PolicyFee::getStationInfoId, stationId)
                        .eq(PolicyFee::getSalesType, 0) // 0-平台
                        .eq(PolicyFee::getIsDeleted, 0)
        );
        log.info("查询平台价格记录数: {}, stationInfoId: {}", platformPolicyFeeList.size(), stationId);
        for (PolicyFee policyFee : platformPolicyFeeList) {
            platformPriceMap.put(policyFee.getPeriodFlag(), policyFee);
        }
        
        // 5. 如果是企业用户，查询企业价格
        Map<Integer, BigDecimal> enterprisePriceMap = new HashMap<>();
        boolean hasEnterprisePrice = false;
        if (firmId != null) {
            List<PolicyFee> policyFeeList = policyFeeMapper.selectList(
                    new LambdaQueryWrapper<PolicyFee>()
                            .eq(PolicyFee::getStationInfoId, stationId)
                            .eq(PolicyFee::getSalesType, 1) // 1-企业
                            .eq(PolicyFee::getFirmId, firmId)
                            .eq(PolicyFee::getIsDeleted, 0)
            );
            
            log.info("查询企业价格记录数: {}, stationInfoId: {}, firmId: {}", 
                    policyFeeList.size(), stationId, firmId);
            
            // 如果查询到企业价格记录，设置标志为true
            if (!policyFeeList.isEmpty()) {
                hasEnterprisePrice = true;
            }
            
            // 构建企业价格映射 (periodFlag -> enterprisePrice)
            for (PolicyFee policyFee : policyFeeList) {
                // 企业价格 = 综合销售费（直接取c_policy_fee.comp_sales_fee）
                BigDecimal compSalesFee = policyFee.getCompSalesFee() != null ? policyFee.getCompSalesFee() : BigDecimal.ZERO;
                enterprisePriceMap.put(policyFee.getPeriodFlag(), compSalesFee);
                log.debug("企业价格计算 - periodFlag: {}, 综合销售费(企业价): {}",
                        policyFee.getPeriodFlag(), compSalesFee);
            }
        }
        
        // 设置是否有企业价格
        result.setHasEnterprisePrice(hasEnterprisePrice);
        log.info("是否有企业价格: {}", hasEnterprisePrice);
        
        // 6. 构建价格列表
        List<AppletStationPriceListVO.PriceItemVO> priceList = new ArrayList<>();
        for (int i = 0; i < policyInfoList.size(); i++) {
            ThirdPartyPolicyInfo policyInfo = policyInfoList.get(i);
            AppletStationPriceListVO.PriceItemVO priceItem = new AppletStationPriceListVO.PriceItemVO();
            
            // 时段格式化：HHmmss -> HH:mm
            String startTime = formatTime(policyInfo.getStartTime());
            // 下一个时段的开始时间作为当前时段的结束时间
            String endTime = (i + 1 < policyInfoList.size()) 
                    ? formatTime(policyInfoList.get(i + 1).getStartTime()) 
                    : "24:00";
            priceItem.setTimePeriod(startTime + "-" + endTime);
            
            priceItem.setPeriodFlag(policyInfo.getPeriodFlag());
            priceItem.setPeriodFlagName(getPeriodFlagName(policyInfo.getPeriodFlag()));
            priceItem.setElecPrice(policyInfo.getElecPrice());
            
            // 从平台价格映射中获取运营费和综合销售费
            BigDecimal originalServicePrice = policyInfo.getServicePrice() != null ? policyInfo.getServicePrice() : BigDecimal.ZERO;
            BigDecimal platformOpFee = BigDecimal.ZERO;
            BigDecimal platformCompSalesFee = BigDecimal.ZERO;
            
            PolicyFee platformPolicyFee = platformPriceMap.get(policyInfo.getPeriodFlag());
            if (platformPolicyFee != null) {
                platformOpFee = platformPolicyFee.getOpFee() != null ? platformPolicyFee.getOpFee() : BigDecimal.ZERO;
                platformCompSalesFee = platformPolicyFee.getCompSalesFee() != null ? platformPolicyFee.getCompSalesFee() : BigDecimal.ZERO;
            }
            
            // 服务费 = 原服务费 + 运营费
            BigDecimal servicePrice = originalServicePrice.add(platformOpFee);
            priceItem.setServicePrice(servicePrice);
            
            // 合计充电价 = 综合销售费（直接取c_policy_fee.comp_sales_fee）
            priceItem.setTotalPrice(platformCompSalesFee);
            log.debug("平台价格计算 - periodFlag: {}, 电费: {}, 原服务费: {}, 运营费: {}, 服务费(含运营): {}, 综合销售费(totalPrice): {}",
                    policyInfo.getPeriodFlag(), policyInfo.getElecPrice(), originalServicePrice, platformOpFee, servicePrice, platformCompSalesFee);
            
            // 设置企业价格（如果有）- 通过periodFlag匹配
            BigDecimal enterprisePrice = enterprisePriceMap.get(policyInfo.getPeriodFlag());
            priceItem.setEnterprisePrice(enterprisePrice);
            
            // 判断是否为当前时段
            priceItem.setCurrentPeriod(isCurrentPeriod(policyInfo.getStartTime(), 
                    (i + 1 < policyInfoList.size()) ? policyInfoList.get(i + 1).getStartTime() : null, 
                    currentTime));
            
            priceList.add(priceItem);
        }
        
        result.setPriceList(priceList);
        return result;
    }
    
    /**
     * 获取设备类型名称
     */
    private String getEquipmentTypeName(Integer equipmentType) {
        if (equipmentType == null) {
            return "未知";
        }
        switch (equipmentType) {
            case 1:
                return "直流设备";
            case 2:
                return "交流设备";
            case 3:
                return "交直流一体设备";
            case 4:
                return "无线设备";
            case 5:
                return "其他";
            default:
                return "未知";
        }
    }
    
    /**
     * 获取状态名称
     */
    private String getStatusName(Integer status) {
        if (status == null) {
            return "未知";
        }
        switch (status) {
            case 0:
                return "离网";
            case 1:
                return "空闲";
            case 2:
                return "占用(未充电)";
            case 3:
                return "占用(充电中)";
            case 4:
                return "占用(预约锁定)";
            case 255:
                return "故障";
            default:
                return "未知";
        }
    }
    
    /**
     * 获取时段标志名称
     */
    private String getPeriodFlagName(Integer periodFlag) {
        if (periodFlag == null) {
            return "";
        }
        switch (periodFlag) {
            case 1:
                return "尖";
            case 2:
                return "峰";
            case 3:
                return "平";
            case 4:
                return "谷";
            default:
                return "";
        }
    }
    
    /**
     * 格式化时间 HHmmss -> HH:mm
     */
    private String formatTime(String time) {
        if (time == null || time.length() < 4) {
            return "00:00";
        }
        return time.substring(0, 2) + ":" + time.substring(2, 4);
    }
    
    /**
     * 判断是否为当前时段
     */
    private boolean isCurrentPeriod(String startTime, String nextStartTime, String currentTime) {
        if (startTime == null || currentTime == null) {
            return false;
        }
        // 当前时间 >= 开始时间 且 当前时间 < 下一个时段开始时间
        if (currentTime.compareTo(startTime) >= 0) {
            if (nextStartTime == null || currentTime.compareTo(nextStartTime) < 0) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 从字典表获取默认运营费
     * @return 默认运营费，如果字典未配置则返回0.2
     */
    private BigDecimal getDefaultOpFee() {
        DictItem dictItem = dictItemMapper.selectOne(
                new LambdaQueryWrapper<DictItem>()
                        .eq(DictItem::getDictCode, DEFAULT_OP_FEE_DICT_CODE)
                        .eq(DictItem::getStatus, 1)
                        .last("LIMIT 1")
        );
        if (dictItem != null && dictItem.getValue() != null) {
            try {
                return new BigDecimal(dictItem.getValue());
            } catch (NumberFormatException e) {
                log.warn("默认运营费字典值转换失败: {}", dictItem.getValue());
            }
        }
        return new BigDecimal("0.2");
    }

    @Override
    public AppChargingCostVO getCurrentChargingCost(String orderNo) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            return null;
        }

        AppChargingCostVO result = thirdPartyStationInfoMapper.selectCurrentChargingCost(userId,orderNo);
        if (result == null) {
            return null;
        }

        // 计算服务费和总金额（加上运营费）
        calculateChargingCostWithOpFee(result);

        return result;
    }

    @Override
    public List<AppStationSearchVO> searchStations(String keyword, BigDecimal longitude, BigDecimal latitude) {
        // 关键词为空或空字符串，返回空列表
        if (keyword == null || keyword.trim().isEmpty()) {
            return new ArrayList<>();
        }

        // 调用Mapper查询
        return thirdPartyStationInfoMapper.searchStations(keyword.trim(), longitude, latitude);
    }

    @Override
    public AppletConnectorDetailVO getConnectorDetail(String connectorCode) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 获取当前时间(HHmmss格式)
        String currentTime = LocalTime.now().format(TIME_FORMATTER);

        // 查询用户余额
        BigDecimal userBalance = null;
        if (userId != null) {
            UserAccount userAccount = userAccountMapper.selectOne(
                    new LambdaQueryWrapper<UserAccount>()
                            .eq(UserAccount::getUserId, userId)
                            .eq(UserAccount::getIsDeleted, 0)
            );
            if (userAccount != null) {
                userBalance = userAccount.getBalance();
            }
        }

        // 查询新用户优惠金额（仅当用户为新用户时）
        BigDecimal newUserDiscount = null;
        if (userId != null) {
            // 检查用户是否有充电订单
            Long orderCount = chargeOrderInfoMapper.selectCount(
                    new LambdaQueryWrapper<ChargeOrderInfo>()
                            .eq(ChargeOrderInfo::getUserId, userId)
                            .eq(ChargeOrderInfo::getIsDeleted, 0)
            );

            // 如果是新用户（没有订单），查询新用户首单优惠金额
            if (orderCount == 0) {
                // 查询c_discounts_activity表，type=1（新用户首单立减）且status=1（启用）的数据
                List<DiscountsActivity> discountActivities = discountsActivityMapper.selectList(
                        new LambdaQueryWrapper<DiscountsActivity>()
                                .eq(DiscountsActivity::getType, 1) // 1-新用户首单立减
                                .eq(DiscountsActivity::getStatus, 1) // 1-启用
                                .eq(DiscountsActivity::getIsDeleted, 0)
                );

                // 计算所有启用的新用户优惠金额总和
                if (!discountActivities.isEmpty()) {
                    newUserDiscount = discountActivities.stream()
                            .map(DiscountsActivity::getDiscount)
                            .filter(discount -> discount != null)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                    log.info("新用户首单优惠金额 - userId: {}, discount: {}", userId, newUserDiscount);
                }
            }
        }

        // 调用Mapper方法，一次SQL查询获取所有信息
        AppletConnectorDetailVO result = thirdPartyConnectorInfoMapper.selectConnectorDetailById(
                connectorCode, userId, currentTime, userBalance, newUserDiscount
        );

        if (result == null) {
            log.warn("充电接口不存在，connectorId: {}", connectorCode);
        }

        return result;
    }

    @Override
    public BigDecimal calculateAvailableChargingAmount(String connectorCode) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            log.warn("未登录用户，无法计算可用充电金额");
            return BigDecimal.ZERO;
        }

        // 1. 查询当前用户余额
        UserAccount userAccount = userAccountMapper.selectOne(
                new LambdaQueryWrapper<UserAccount>()
                        .eq(UserAccount::getUserId, userId)
                        .eq(UserAccount::getIsDeleted, 0)
        );
        if (userAccount == null || userAccount.getBalance() == null) {
            log.warn("用户账户不存在或余额为空 - userId: {}", userId);
            return BigDecimal.ZERO;
        }
        BigDecimal userBalance = userAccount.getBalance();

        // 2. 从字典表查询安全价（safety_fee）
        DictItem safetyFeeItem = dictItemMapper.selectOne(
                new LambdaQueryWrapper<DictItem>()
                        .eq(DictItem::getDictCode, "safety_fee")
                        .eq(DictItem::getStatus, 1)
                        .last("LIMIT 1")
        );
        BigDecimal safetyFee = safetyFeeItem != null && safetyFeeItem.getValue() != null
                ? new BigDecimal(safetyFeeItem.getValue())
                : BigDecimal.ZERO;

        // 计算扣除安全价后的余额
        BigDecimal balanceAfterSafety = userBalance.subtract(safetyFee);
        if (balanceAfterSafety.compareTo(BigDecimal.ZERO) <= 0) {
            log.info("用户余额不足 - userId: {}, balance: {}, safetyFee: {}", userId, userBalance, safetyFee);
            return BigDecimal.ZERO;
        }

        // 3. 查询充电接口、设备、站点信息
        ThirdPartyConnectorInfo connectorInfo = thirdPartyConnectorInfoMapper.selectOne(Wrappers.<ThirdPartyConnectorInfo>lambdaQuery()
                .eq(ThirdPartyConnectorInfo::getConnectorId,connectorCode).last("LIMIT 1"));
        if (connectorInfo == null) {
            log.warn("充电接口不存在 - connectorId: {}", connectorCode);
            return BigDecimal.ZERO;
        }

        ThirdPartyEquipmentInfo equipmentInfo = thirdPartyEquipmentInfoMapper.selectOne(
                new LambdaQueryWrapper<ThirdPartyEquipmentInfo>()
                        .eq(ThirdPartyEquipmentInfo::getEquipmentId, connectorInfo.getEquipmentId())
                        .eq(ThirdPartyEquipmentInfo::getIsDeleted, 0)
                        .last("LIMIT 1")
        );
        if (equipmentInfo == null) {
            log.warn("设备信息不存在 - equipmentId: {}", connectorInfo.getEquipmentId());
            return BigDecimal.ZERO;
        }

        ThirdPartyStationInfo stationInfo = thirdPartyStationInfoMapper.selectOne(
                new LambdaQueryWrapper<ThirdPartyStationInfo>()
                        .eq(ThirdPartyStationInfo::getStationId, equipmentInfo.getStationId())
                        .eq(ThirdPartyStationInfo::getIsDeleted, 0)
                        .last("LIMIT 1")
        );
        if (stationInfo == null) {
            log.warn("站点信息不存在 - stationId: {}", equipmentInfo.getStationId());
            return BigDecimal.ZERO;
        }

        // 4. 查询价格策略
        ThirdPartyEquipmentPricePolicy pricePolicy = thirdPartyEquipmentPricePolicyMapper.selectOne(
                new LambdaQueryWrapper<ThirdPartyEquipmentPricePolicy>()
                        .eq(ThirdPartyEquipmentPricePolicy::getConnectorId, connectorInfo.getConnectorId())
                        .eq(ThirdPartyEquipmentPricePolicy::getIsDeleted, 0)
                        .last("LIMIT 1")
        );
        if (pricePolicy == null) {
            log.warn("价格策略不存在 - connectorId: {}", connectorInfo.getConnectorId());
            return BigDecimal.ZERO;
        }

        // 5. 查询所有时段的价格信息（按开始时间排序）
        List<ThirdPartyPolicyInfo> policyInfoList = thirdPartyPolicyInfoMapper.selectList(
                new LambdaQueryWrapper<ThirdPartyPolicyInfo>()
                        .eq(ThirdPartyPolicyInfo::getPricePolicyId, pricePolicy.getId())
                        .eq(ThirdPartyPolicyInfo::getIsDeleted, 0)
                        .orderByAsc(ThirdPartyPolicyInfo::getStartTime)
        );
        if (policyInfoList.isEmpty()) {
            log.warn("价格策略明细不存在 - pricePolicyId: {}", pricePolicy.getId());
            return BigDecimal.ZERO;
        }

        // 6. 查询用户是否为企业用户
        UserFirm userFirm = userFirmMapper.selectOne(
                new LambdaQueryWrapper<UserFirm>()
                        .eq(UserFirm::getUserId, userId)
                        .eq(UserFirm::getIsDeleted, 0)
                        .last("LIMIT 1")
        );

        // 7. 计算可用充电金额
        // 正确公式：可用余额 = (用户余额 - 安全价) × 基础费率占比
        // 其中：基础费率占比 = (电费 + 服务费) / (电费 + 服务费 + 运营费 + 增值费)
        // 这样计算确保度数计算时已包含所有费用，避免重复扣费

        // 获取当前时段的价格信息（用于计算费率占比）
        String currentTimeStr = LocalTime.now().format(TIME_FORMATTER);
        ThirdPartyPolicyInfo currentPolicyInfo = null;
        for (int i = 0; i < policyInfoList.size(); i++) {
            ThirdPartyPolicyInfo policyInfo = policyInfoList.get(i);
            String startTime = policyInfo.getStartTime();
            // 下一个时段的开始时间作为当前时段的结束时间
            String endTime = (i + 1 < policyInfoList.size()) 
                    ? policyInfoList.get(i + 1).getStartTime() 
                    : "240000";
            
            // 判断当前时间是否在该时段内
            if (currentTimeStr.compareTo(startTime) >= 0 && currentTimeStr.compareTo(endTime) < 0) {
                currentPolicyInfo = policyInfo;
                break;
            }
        }
        // 如果没找到当前时段，使用第一个时段
        if (currentPolicyInfo == null && !policyInfoList.isEmpty()) {
            currentPolicyInfo = policyInfoList.get(0);
        }
        if (currentPolicyInfo == null) {
            log.warn("无法确定当前时段价格 - connectorId: {}", connectorCode);
            return BigDecimal.ZERO;
        }

        // 获取电费、服务费
        BigDecimal elecPrice = currentPolicyInfo.getElecPrice() != null ? currentPolicyInfo.getElecPrice() : BigDecimal.ZERO;
        BigDecimal servicePrice = currentPolicyInfo.getServicePrice() != null ? currentPolicyInfo.getServicePrice() : BigDecimal.ZERO;
        BigDecimal basePrice = elecPrice.add(servicePrice); // 基础价格 = 电费 + 服务费

        if (basePrice.compareTo(BigDecimal.ZERO) == 0) {
            log.warn("基础价格为0 - connectorId: {}", connectorCode);
            return BigDecimal.ZERO;
        }

        // 查询该时段的运营费
        PolicyFee policyFee;
        if (userFirm != null) {
            policyFee = policyFeeMapper.selectOne(
                    new LambdaQueryWrapper<PolicyFee>()
                            .eq(PolicyFee::getStationInfoId, stationInfo.getId())
                            .eq(PolicyFee::getPeriodFlag, currentPolicyInfo.getPeriodFlag())
                            .eq(PolicyFee::getSalesType, 1)
                            .eq(PolicyFee::getFirmId, userFirm.getFirmId())
                            .eq(PolicyFee::getIsDeleted, 0)
                            .last("LIMIT 1")
            );
        } else {
            policyFee = policyFeeMapper.selectOne(
                    new LambdaQueryWrapper<PolicyFee>()
                            .eq(PolicyFee::getStationInfoId, stationInfo.getId())
                            .eq(PolicyFee::getPeriodFlag, currentPolicyInfo.getPeriodFlag())
                            .eq(PolicyFee::getSalesType, 0)
                            .eq(PolicyFee::getIsDeleted, 0)
                            .last("LIMIT 1")
            );
        }

        BigDecimal opFee = (policyFee != null && policyFee.getOpFee() != null)
                ? policyFee.getOpFee()
                : getDefaultOpFee();

        // 查询增值费用
        BigDecimal valueAddedFee = BigDecimal.ZERO;
        if (currentPolicyInfo.getPeriodFlag() != null) {
            String periodLabel = "";
            switch (currentPolicyInfo.getPeriodFlag()) {
                case 1: periodLabel = "尖"; break;
                case 2: periodLabel = "峰"; break;
                case 3: periodLabel = "平"; break;
                case 4: periodLabel = "谷"; break;
            }

            if (!periodLabel.isEmpty()) {
                DictItem valueAddedItem = dictItemMapper.selectOne(
                        new LambdaQueryWrapper<DictItem>()
                                .eq(DictItem::getDictCode, "time_period_flag")
                                .eq(DictItem::getLabel, periodLabel)
                                .eq(DictItem::getStatus, 1)
                                .last("LIMIT 1")
                );
                if (valueAddedItem != null && valueAddedItem.getValue() != null) {
                    valueAddedFee = new BigDecimal(valueAddedItem.getValue());
                }
            }
        }

        // 计算总单价（每度电的总费用）
        BigDecimal totalUnitPrice = basePrice.add(opFee).add(valueAddedFee);
        
        // 计算可充电度数 = (余额 - 安全价) / 总单价
        BigDecimal kwh = balanceAfterSafety.divide(totalUnitPrice, 4, RoundingMode.HALF_UP);
        
        // 计算可用于基础费用（电费+服务费）的金额 = 度数 × 基础价格
        // 这就是实际可用于充电的金额（不含运营费和增值费）
        BigDecimal availableAmount = kwh.multiply(basePrice);
        
        // 计算运营费和增值费用（用于日志记录）
        BigDecimal totalOpFeeCost = kwh.multiply(opFee);
        BigDecimal totalValueAddedCost = kwh.multiply(valueAddedFee);

        log.debug("时段计算 - 电费: {}, 服务费: {}, 运营费: {}, 增值费: {}, 总单价: {}, 可充度数: {}, 基础费用: {}",
                elecPrice, servicePrice, opFee, valueAddedFee, totalUnitPrice, kwh, availableAmount);

        // 确保不为负数
        if (availableAmount.compareTo(BigDecimal.ZERO) < 0) {
            availableAmount = BigDecimal.ZERO;
        }

        // 保留 2 位小数
        availableAmount = availableAmount.setScale(2, RoundingMode.HALF_UP);

        log.info("可用充电金额计算完成 - userId: {}, connectorId: {}, userBalance: {}, safetyFee: {}, " +
                        "totalOpFeeCost: {}, totalValueAddedCost: {}, availableAmount: {}",
                userId, connectorCode, userBalance, safetyFee, totalOpFeeCost, totalValueAddedCost, availableAmount);

        return availableAmount;
    }

    /**
     * 计算充电费用（含运营费）
     * 根据 charge_details 是否有数据决定计算方式：
     * 1. 有 charge_details：按照时段明细计算，不同时段使用对应的 op_fee
     * 2. 没有 charge_details：直接使用当前时段的 op_fee 计算
     *
     * @param costVO 充电费用VO
     */
    private void calculateChargingCostWithOpFee(AppChargingCostVO costVO) {
        try {
            // 获取充电站ID（通过 connectorCode 查询）
            ThirdPartyConnectorInfo connector = thirdPartyConnectorInfoMapper.selectOne(
                    new LambdaQueryWrapper<ThirdPartyConnectorInfo>()
                            .eq(ThirdPartyConnectorInfo::getConnectorId, costVO.getConnectorCode())
                            .eq(ThirdPartyConnectorInfo::getIsDeleted, 0)
            );
            if (connector == null) {
                log.warn("未找到充电接口信息 - connectorCode: {}", costVO.getConnectorCode());
                return;
            }

            ThirdPartyStationInfo station = thirdPartyStationInfoMapper.selectOne(
                    new LambdaQueryWrapper<ThirdPartyStationInfo>()
                            .eq(ThirdPartyStationInfo::getStationId, connector.getStationId())
                            .eq(ThirdPartyStationInfo::getIsDeleted, 0)
            );
            if (station == null) {
                log.warn("未找到充电站信息 - stationId: {}", connector.getStationId());
                return;
            }

            BigDecimal opFeeCost = BigDecimal.ZERO;
            String chargeDetails = costVO.getChargeDetails();

            // 判断是否有时段明细
            if (StrUtil.isNotBlank(chargeDetails)) {
                // 有时段明细，按照时段计算运营费
                opFeeCost = calculateOpFeeByCrossPeriod(station.getId(), chargeDetails);
            } else {
                // 没有时段明细，使用当前时段计算
                opFeeCost = calculateOpFeeByCurrentPeriod(station.getId(), costVO.getTotalPower());
            }

            // 更新服务费和总金额
            BigDecimal serviceMoney = costVO.getServiceMoney();
            if (serviceMoney == null) {
                serviceMoney = BigDecimal.ZERO;
            }
            costVO.setServiceMoney(serviceMoney.add(opFeeCost));

            BigDecimal totalMoney = costVO.getTotalMoney();
            if (totalMoney == null) {
                totalMoney = BigDecimal.ZERO;
            }
            costVO.setTotalMoney(totalMoney.add(opFeeCost));

        } catch (Exception e) {
            log.error("计算充电费用失败", e);
        }
    }

    /**
     * 根据时段明细计算运营费（跨时段充电）
     * chargeDetails 格式：[{DetailStartTime, DetailEndTime, ElecPrice, SevicePrice, DetailPower, DetailElecMoney, DetailSeviceMoney}]
     */
    private BigDecimal calculateOpFeeByCrossPeriod(Long stationId, String chargeDetails) {
        try {
            // 解析 JSON
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode detailsArray = objectMapper.readTree(chargeDetails);

            if (!detailsArray.isArray()) {
                log.warn("时段明细格式错误 - chargeDetails: {}", chargeDetails);
                return BigDecimal.ZERO;
            }

            BigDecimal totalOpFeeCost = BigDecimal.ZERO;

            // 遍历每个时段
            for (com.fasterxml.jackson.databind.JsonNode detail : detailsArray) {
                String startTime = detail.has("DetailStartTime") ? detail.get("DetailStartTime").asText() : null;
                BigDecimal detailPower = detail.has("DetailPower") ? new BigDecimal(detail.get("DetailPower").asText()) : BigDecimal.ZERO;

                if (startTime == null || detailPower.compareTo(BigDecimal.ZERO) <= 0) {
                    continue;
                }

                // 根据时间查询对应的时段 period_flag
                String timeHHmmss = startTime.length() >= 6 ? startTime.substring(0, 6) : startTime;
                Integer periodFlag = getPeriodFlagByTime(stationId, timeHHmmss);

                // 查询该时段的运营费
                BigDecimal opFee = getOpFeeByPeriodFlag(stationId, periodFlag);

                // 计算该时段的运营费
                BigDecimal periodOpFeeCost = detailPower.multiply(opFee);
                totalOpFeeCost = totalOpFeeCost.add(periodOpFeeCost);

                log.debug("时段运营费 - startTime: {}, periodFlag: {}, detailPower: {}, opFee: {}, cost: {}",
                        startTime, periodFlag, detailPower, opFee, periodOpFeeCost);
            }

            return totalOpFeeCost.setScale(2, RoundingMode.HALF_UP);
        } catch (Exception e) {
            log.error("解析时段明细失败 - chargeDetails: {}", chargeDetails, e);
            return BigDecimal.ZERO;
        }
    }

    /**
     * 根据当前时段计算运营费（非跨时段充电）
     */
    private BigDecimal calculateOpFeeByCurrentPeriod(Long stationId, BigDecimal totalPower) {
        if (totalPower == null || totalPower.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }

        // 获取当前时间
        String currentTime = LocalTime.now().format(TIME_FORMATTER);

        // 获取当前时段标志
        Integer periodFlag = getPeriodFlagByTime(stationId, currentTime);

        // 查询该时段的运营费
        BigDecimal opFee = getOpFeeByPeriodFlag(stationId, periodFlag);

        // 计算运营费
        BigDecimal opFeeCost = totalPower.multiply(opFee);

        log.debug("当前时段运营费 - periodFlag: {}, totalPower: {}, opFee: {}, cost: {}",
                periodFlag, totalPower, opFee, opFeeCost);

        return opFeeCost.setScale(2, RoundingMode.HALF_UP);
    }

    /**
     * 根据时间获取时段标志
     */
    private Integer getPeriodFlagByTime(Long stationId, String timeHHmmss) {
        // 查询充电接口
        ThirdPartyConnectorInfo connector = thirdPartyConnectorInfoMapper.selectOne(
                new LambdaQueryWrapper<ThirdPartyConnectorInfo>()
                        .eq(ThirdPartyConnectorInfo::getStationId, 
                                thirdPartyStationInfoMapper.selectById(stationId).getStationId())
                        .eq(ThirdPartyConnectorInfo::getIsDeleted, 0)
                        .last("LIMIT 1")
        );
        if (connector == null) {
            log.warn("未找到充电接口 - stationId: {}", stationId);
            return 3; // 默认平时段
        }

        // 查询价格策略
        ThirdPartyEquipmentPricePolicy pricePolicy = thirdPartyEquipmentPricePolicyMapper.selectOne(
                new LambdaQueryWrapper<ThirdPartyEquipmentPricePolicy>()
                        .eq(ThirdPartyEquipmentPricePolicy::getConnectorId, connector.getConnectorId())
                        .eq(ThirdPartyEquipmentPricePolicy::getIsDeleted, 0)
                        .last("LIMIT 1")
        );
        if (pricePolicy == null) {
            log.warn("未找到价格策略 - connectorId: {}", connector.getConnectorId());
            return 3; // 默认平时段
        }

        // 查询当前时间对应的时段
        ThirdPartyPolicyInfo policyInfo = thirdPartyPolicyInfoMapper.selectOne(
                new LambdaQueryWrapper<ThirdPartyPolicyInfo>()
                        .eq(ThirdPartyPolicyInfo::getPricePolicyId, pricePolicy.getId())
                        .eq(ThirdPartyPolicyInfo::getIsDeleted, 0)
                        .le(ThirdPartyPolicyInfo::getStartTime, timeHHmmss)
                        .orderByDesc(ThirdPartyPolicyInfo::getStartTime)
                        .last("LIMIT 1")
        );

        if (policyInfo == null || policyInfo.getPeriodFlag() == null) {
            log.warn("未找到时段信息 - pricePolicyId: {}, time: {}", pricePolicy.getId(), timeHHmmss);
            return 3; // 默认平时段
        }

        return policyInfo.getPeriodFlag();
    }

    /**
     * 根据时段标志获取运营费
     */
    private BigDecimal getOpFeeByPeriodFlag(Long stationId, Integer periodFlag) {
        PolicyFee policyFee = policyFeeMapper.selectOne(
                new LambdaQueryWrapper<PolicyFee>()
                        .eq(PolicyFee::getStationInfoId, stationId)
                        .eq(PolicyFee::getPeriodFlag, periodFlag)
                        .eq(PolicyFee::getSalesType, 0) // 平台价格
                        .eq(PolicyFee::getIsDeleted, 0)
                        .last("LIMIT 1")
        );

        if (policyFee == null || policyFee.getOpFee() == null) {
            log.warn("未找到运营费配置 - stationId: {}, periodFlag: {}", stationId, periodFlag);
            return BigDecimal.ZERO;
        }

        return policyFee.getOpFee();
    }


}
