package top.continew.admin.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import top.continew.admin.business.mapper.BillingRuleMapper;
import top.continew.admin.business.model.entity.BillingRuleDO;
import top.continew.admin.business.model.query.BillingRuleQuery;
import top.continew.admin.business.model.req.BillingRuleReq;
import top.continew.admin.business.model.resp.BillingRuleResp;
import top.continew.admin.business.service.BillingRuleService;
import top.continew.starter.extension.crud.service.impl.BaseServiceImpl;

import java.util.List;

/**
 * 计费规则业务实现
 *
 * @author jiay
 * @since 2025/11/14
 */
@Service
@RequiredArgsConstructor
public class BillingRuleServiceImpl extends BaseServiceImpl<BillingRuleMapper, BillingRuleDO, BillingRuleResp, BillingRuleResp, BillingRuleQuery, BillingRuleReq> implements BillingRuleService {

    /**
     * 根据平台ID获取计费规则（带缓存）
     */
    @Override
    @Cacheable(value = "billingRule", key = "#platformId", unless = "#result == null")
    public BillingRuleDO getByPlatformId(Long platformId) {
        return baseMapper.selectOne(new LambdaQueryWrapper<BillingRuleDO>().eq(BillingRuleDO::getPlatformId, platformId)
            .eq(BillingRuleDO::getEnabled, 1)
            .last("LIMIT 1"));
    }

    /**
     * 根据平台ID获取计费金额
     */
    @Override
    public Long getPriceByPlatformId(Long platformId) {
        BillingRuleDO rule = getByPlatformId(platformId);
        return rule != null && rule.getPrice() != null ? rule.getPrice() : 0L;
    }

    /**
     * 新增或修改后清除缓存
     */
    @Override
    @CacheEvict(value = "billingRule", allEntries = true)
    public Long add(BillingRuleReq req) {
        return super.add(req);
    }

    /**
     * 更新后清除缓存
     */
    @Override
    @CacheEvict(value = "billingRule", allEntries = true)
    public void update(BillingRuleReq req, Long id) {
        super.update(req, id);
    }

    /**
     * 删除后清除缓存（批量删除）
     */
    @Override
    @CacheEvict(value = "billingRule", allEntries = true)
    public void delete(List<Long> ids) {
        super.delete(ids);
    }

    /**
     * 根据扣费编码获取计费规则（带缓存）
     */
    @Override
    @Cacheable(value = "billingRule", key = "'charge_' + #chargeCode", unless = "#result == null")
    public BillingRuleDO getByChargeCode(String chargeCode) {
        return baseMapper.selectOne(new LambdaQueryWrapper<BillingRuleDO>().eq(BillingRuleDO::getChargeCode, chargeCode)
            .eq(BillingRuleDO::getEnabled, 1)
            .last("LIMIT 1"));
    }
}
