package com.jeesharp.business.modules.finance.merchantsettle.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeesharp.business.modules.finance.merchantsettle.entity.MerchantSettleConfig;
import com.jeesharp.business.modules.finance.merchantsettle.enums.MerchantSettleConfigStatusEnum;
import com.jeesharp.business.modules.finance.merchantsettle.enums.SettleModeEnum;
import com.jeesharp.business.modules.finance.merchantsettle.mapper.MerchantSettleConfigMapper;
import com.jeesharp.business.modules.finance.merchantsettle.service.MerchantSettleConfigService;
import com.jeesharp.business.modules.finance.merchantsettle.vo.MerchantSettleConfigQueryVO;
import com.jeesharp.framework.exception.BizErrorException;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 商户结算配置领域服务实现。
 *
 * @author jeesharp
 * @since 2026-06-11
 */
@Service
@Transactional(readOnly = true)
public class MerchantSettleConfigServiceImpl
        extends CrudService<MerchantSettleConfigMapper, MerchantSettleConfig, MerchantSettleConfigQueryVO>
        implements MerchantSettleConfigService {

    @Override
    @Transactional(readOnly = false)
    public MerchantSettleConfig createConfig(MerchantSettleConfig config) {
        if (StrUtil.isNotBlank(config.getId())) {
            throw new BizErrorException("新增商户结算配置不应预置主键");
        }
        validateAndFillDefault(config);
        if (getByMerchantTenantId(config.getMerchantTenantId()) != null) {
            throw new BizErrorException("该商户租户已存在结算配置");
        }
        getBaseMapper().insert(config);
        return config;
    }

    @Override
    @Transactional(readOnly = false)
    public void updateConfig(MerchantSettleConfig config) {
        if (StrUtil.isBlank(config.getId())) {
            throw new BizErrorException("更新商户结算配置主键不能为空");
        }
        MerchantSettleConfig existing = get(config.getId());
        if (existing == null) {
            throw new BizErrorException("商户结算配置不存在");
        }
        validateAndFillDefault(config);
        MerchantSettleConfig sameTenant = getByMerchantTenantId(config.getMerchantTenantId());
        if (sameTenant != null && !sameTenant.getId().equals(config.getId())) {
            throw new BizErrorException("该商户租户已存在其他结算配置");
        }
        getBaseMapper().updateById(config);
    }

    @Override
    public MerchantSettleConfig getByMerchantTenantId(String merchantTenantId) {
        if (StrUtil.isBlank(merchantTenantId)) {
            return null;
        }
        LambdaQueryWrapper<MerchantSettleConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MerchantSettleConfig::getMerchantTenantId, merchantTenantId);
        wrapper.last("LIMIT 1");
        return getBaseMapper().selectOne(wrapper);
    }

    private void validateAndFillDefault(MerchantSettleConfig config) {
        if (StrUtil.isBlank(config.getMerchantTenantId())) {
            throw new BizErrorException("商户租户ID不能为空");
        }
        if (SettleModeEnum.fromValue(config.getSettleMode()) == null) {
            throw new BizErrorException("结算模式不合法");
        }
        if (config.getCommissionRate() == null) {
            config.setCommissionRate(BigDecimal.ZERO);
        }
        if (config.getCommissionRate().compareTo(BigDecimal.ZERO) < 0
                || config.getCommissionRate().compareTo(BigDecimal.ONE) > 0) {
            throw new BizErrorException("佣金比例须在 0~1 之间");
        }
        if (config.getStatus() == null) {
            config.setStatus(MerchantSettleConfigStatusEnum.ENABLED.getValue());
        }
        if (MerchantSettleConfigStatusEnum.fromValue(config.getStatus()) == null) {
            throw new BizErrorException("状态不合法");
        }
        if (SettleModeEnum.WECHAT_PROFIT_SHARING.getValue().equals(config.getSettleMode())
                && StrUtil.isBlank(config.getSubMchId())) {
            throw new BizErrorException("微信分账模式下子商户号不能为空");
        }
    }
}
