package com.haha.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.common.exception.BusinessException;
import com.haha.entity.DistributorConfig;
import com.haha.entity.dto.DistributorConfigDTO;
import com.haha.mapper.DistributorConfigMapper;
import com.haha.service.DistributorConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class DistributorConfigServiceImpl extends ServiceImpl<DistributorConfigMapper, DistributorConfig> implements DistributorConfigService {

    private final DistributorConfigMapper configMapper;

    @Override
    public String getConfigValue(String key) {
        DistributorConfig config = configMapper.selectByKey(key);
        return config != null ? config.getConfigValue() : null;
    }

    @Override
    public String getConfigValue(String key, String defaultValue) {
        String value = getConfigValue(key);
        return value != null ? value : defaultValue;
    }

    @Override
    public BigDecimal getFixedCommissionAmount() {
        String value = getConfigValue("fixed_commission_amount", "20.00");
        return new BigDecimal(value);
    }

    @Override
    public BigDecimal getFirstOrderCommissionRate() {
        String value = getConfigValue("first_order_commission_rate", "5.00");
        return new BigDecimal(value);
    }

    @Override
    public String getValidUserRule() {
        return getConfigValue("valid_user_rule", "FIRST_ORDER");
    }

    @Override
    public BigDecimal getMinValidOrderAmount() {
        String value = getConfigValue("min_valid_order_amount", "0.00");
        return new BigDecimal(value);
    }

    @Override
    public Integer getValidTimeWindowDays() {
        String value = getConfigValue("valid_time_window_days", "0");
        return Integer.parseInt(value);
    }

    @Override
    public BigDecimal getMinWithdrawalAmount() {
        String value = getConfigValue("min_withdrawal_amount", "100.00");
        return new BigDecimal(value);
    }

    @Override
    public List<DistributorConfig> getAllConfigs() {
        return this.list();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DistributorConfig updateConfig(DistributorConfigDTO dto) {
        DistributorConfig config = configMapper.selectByKey(dto.getConfigKey());
        if (config == null) {
            throw new BusinessException(404, "配置项不存在: " + dto.getConfigKey());
        }
        config.setConfigValue(dto.getConfigValue());
        this.updateById(config);

        log.info("更新分销配置: key={}, value={}", dto.getConfigKey(), dto.getConfigValue());
        return config;
    }
}
