package com.jeesharp.business.modules.pay.paysubmerchantapplyment.application.support;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.pay.paychannelconfig.support.PayChannelTenantSupport;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.entity.PaySubMerchantApplyment;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.enums.PaySubMerchantApplyStatusEnum;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.service.PaySubMerchantApplymentService;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.support.PaySubMerchantApplyStatusSupport;
import com.jeesharp.framework.exception.BizErrorException;

/**
 * 特约商户进件衍生操作（结算修改、商户注销等）的共用前置校验与微信配置租户键解析。
 *
 * @author jeesharp
 * @since 2026-06-15
 */
public final class PaySubMerchantApplymentOperateSupport {

    /** @see PaySubMerchantApplyStatusSupport#APPLY_STATUS_FINISH */
    public static final String APPLY_STATUS_FINISH = PaySubMerchantApplyStatusSupport.APPLY_STATUS_FINISH;

    private PaySubMerchantApplymentOperateSupport() {
    }

    /**
     * 是否为有效二级商户：已分配 sub_mchid、进件 FINISH、未注销。
     */
    public static boolean isEffectiveSubMerchant(PaySubMerchantApplyment applyment) {
        return PaySubMerchantApplyStatusSupport.isEffectiveSubMerchant(applyment);
    }

    /**
     * 非有效二级商户时的业务提示；已有效则返回 {@code null}。
     */
    public static String resolveIneffectiveMessage(PaySubMerchantApplyment applyment) {
        if (applyment == null) {
            return "尚未创建微信支付特约商户进件";
        }
        if (PaySubMerchantApplyStatusEnum.SUB_MCH_CANCELLED.getValue().equals(applyment.getApplyStatus())) {
            return "特约商户已注销";
        }
        if (StrUtil.isBlank(applyment.getSubMchId())) {
            return "进件尚未获得特约商户号 sub_mch_id，请同步微信审核状态";
        }
        String normalizedStatus = normalizeApplyStatus(applyment.getApplyStatus());
        if (!APPLY_STATUS_FINISH.equals(normalizedStatus)) {
            return "进件尚未完成（当前状态：" + normalizedStatus + "），请等待审核通过后再操作";
        }
        return null;
    }

    /**
     * 进件状态归一化（兼容微信 {@code APPLYMENT_STATE_*} 前缀与本地简写）。
     */
    public static String normalizeApplyStatus(String applyStatus) {
        return PaySubMerchantApplyStatusSupport.normalizeApplyStatus(applyStatus);
    }

    /**
     * 进件业务租户 → 微信配置查询用租户键（平台级传 null）。
     */
    public static String resolveWechatConfigTenantKey(String applymentTenantId) {
        if (PayChannelTenantSupport.isPlatformLevel(applymentTenantId)) {
            return null;
        }
        return PayChannelTenantSupport.normalize(applymentTenantId);
    }

    /**
     * 加载进件并校验已分配特约商户号。
     *
     * @param noSubMchMessage 未分配 sub_mchid 时的业务提示
     */
    public static PaySubMerchantApplyment requireApplymentWithSubMch(
            PaySubMerchantApplymentService service, String applymentId, String noSubMchMessage) {
        if (StrUtil.isBlank(applymentId)) {
            throw new BizErrorException("进件记录 ID 不能为空");
        }
        PaySubMerchantApplyment applyment = service.get(applymentId.trim());
        if (applyment == null) {
            throw new BizErrorException("进件申请单不存在");
        }
        if (StrUtil.isBlank(applyment.getSubMchId())) {
            throw new BizErrorException(noSubMchMessage);
        }
        return applyment;
    }

    /**
     * 校验进件主表未处于「商户已注销」终态。
     */
    public static void assertNotMerchantCancelled(PaySubMerchantApplyment applyment, String deniedMessage) {
        if (PaySubMerchantApplyStatusEnum.SUB_MCH_CANCELLED.getValue().equals(applyment.getApplyStatus())) {
            throw new BizErrorException(deniedMessage);
        }
    }

    /**
     * 加载可操作进件：须已分配 sub_mchid 且未注销。
     */
    public static PaySubMerchantApplyment requireOperableApplymentWithSubMch(
            PaySubMerchantApplymentService service,
            String applymentId,
            String noSubMchMessage,
            String cancelledDeniedMessage) {
        PaySubMerchantApplyment applyment = requireApplymentWithSubMch(service, applymentId, noSubMchMessage);
        assertNotMerchantCancelled(applyment, cancelledDeniedMessage);
        return applyment;
    }

    /**
     * 加载可改结算等「须进件完成」的进件：在 {@link #requireOperableApplymentWithSubMch} 基础上要求 {@code apply_status=FINISH}。
     */
    public static PaySubMerchantApplyment requireFinishedApplymentWithSubMch(
            PaySubMerchantApplymentService service,
            String applymentId,
            String noSubMchMessage,
            String notFinishedMessage,
            String cancelledDeniedMessage) {
        PaySubMerchantApplyment applyment = requireOperableApplymentWithSubMch(
                service, applymentId, noSubMchMessage, cancelledDeniedMessage);
        if (!APPLY_STATUS_FINISH.equals(normalizeApplyStatus(applyment.getApplyStatus()))) {
            throw new BizErrorException(notFinishedMessage);
        }
        return applyment;
    }
}
