package cn.qihangerp.service.external.pdd;

import cn.qihangerp.model.entity.OGoodsSku;
import cn.qihangerp.model.request.ExternalGoodsUpsertRequest;
import cn.qihangerp.service.external.shop.PddShopCredential;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 自动拉取 {@code pdd.goods.cat.rule.get}，并在单销售规格维度下尝试 {@code pdd.goods.spec.id.get} 生成 sku-overrides。
 *
 * @author guochengyu
 */
@AllArgsConstructor
@Service
public class PddCatRuleSpecAutoResolver {

    private final PddPopClient popClient;

    @Data
    public static class AutoResolveResult {
        private List<ExternalPddProperties.PddSkuOverride> overrides = new ArrayList<>();
        private String detail;
        private boolean resolved;
        private boolean catRuleFetched;
        private String catRuleSnippet;
        /** {@code pdd.goods.cat.rule.get} 原始响应体（成功或失败），供发布层判断是否走无规格单 SKU 逻辑 */
        private String catRuleRaw;
    }

    /**
     * 拉取类目规则，解析销售 parent_spec_id，并对每条 SKU 调用 spec.id.get。
     */
    public AutoResolveResult resolve(PddShopCredential cred, String gatewayUrl, ExternalGoodsUpsertRequest req,
                                     List<OGoodsSku> orderedSkus, long catId) {
        AutoResolveResult r = new AutoResolveResult();
        if (orderedSkus == null || orderedSkus.isEmpty()) {
            r.setDetail("无有效 SKU，无法自动解析 spec");
            return r;
        }
        try {
            String raw = fetchCatRuleJson(cred, gatewayUrl, catId);
            r.setCatRuleRaw(raw);
            r.setCatRuleFetched(true);
            r.setCatRuleSnippet(PddOpenApiSupport.snippet(raw, 2000));
            if (PddOpenApiSupport.isError(raw)) {
                r.setDetail("pdd.goods.cat.rule.get: " + PddOpenApiSupport.formatError(raw));
                return r;
            }
            Long parentSpecId = PddOpenApiSupport.findFirstSaleParentSpecId(raw);
            if (parentSpecId == null || parentSpecId <= 0) {
                r.setDetail("类目规则中未解析到销售 parent_spec_id"
                        + PddOpenApiSupport.suffixHintForMissingSaleParentSpec(raw));
                return r;
            }
            List<ExternalPddProperties.PddSkuOverride> ovs = buildSkuOverridesBySpecName(
                    catId, parentSpecId, orderedSkus, req, cred, gatewayUrl);
            r.setOverrides(ovs);
            r.setResolved(ovs.size() == orderedSkus.size());
            r.setDetail("parent_spec_id=" + parentSpecId + "，自动生成 " + ovs.size() + " 条 spec（请求 SKU " + orderedSkus.size() + " 条）");
            return r;
        } catch (Exception e) {
            r.setDetail("自动解析异常: " + e.getMessage());
            return r;
        }
    }

    /**
     * 调用 pdd.goods.cat.rule.get
     */
    public String fetchCatRuleJson(PddShopCredential cred, String gatewayUrl, long catId) throws Exception {
        if (catId <= 0) {
            throw new IllegalArgumentException("cat_id 必须为正数，当前=" + catId);
        }
        return popClient.invokeTopLevelBiz(
                gatewayUrl,
                cred.getAppKey(),
                cred.getAppSecret(),
                cred.getAccessToken(),
                "pdd.goods.cat.rule.get",
                PddOpenApiSupport.catRuleGetTopLevelParams(catId)
        );
    }

    /**
     * 对每个 SKU 用 skuName 作为规格值调用 spec.id.get，生成与 YAML 相同结构的 overrides。
     */
    public List<ExternalPddProperties.PddSkuOverride> buildSkuOverridesBySpecName(
            long catId,
            long parentSpecId,
            List<OGoodsSku> orderedSkus,
            ExternalGoodsUpsertRequest req,
            PddShopCredential cred,
            String gatewayUrl) throws Exception {

        List<ExternalPddProperties.PddSkuOverride> out = new ArrayList<>();
        for (OGoodsSku row : orderedSkus) {
            String specName = resolveSpecName(row, req);
            if (!StringUtils.hasText(specName)) {
                throw new IllegalStateException("无法解析 SKU 规格名：outSkuId=" + row.getOuterErpSkuId());
            }
            String body = popClient.invokeTopLevelBiz(
                    gatewayUrl,
                    cred.getAppKey(),
                    cred.getAppSecret(),
                    cred.getAccessToken(),
                    "pdd.goods.spec.id.get",
                    PddOpenApiSupport.specIdGetTopLevelParams(catId, parentSpecId, specName.trim())
            );
            if (PddOpenApiSupport.isError(body)) {
                throw new IllegalStateException("pdd.goods.spec.id.get 失败 spec_name=" + specName + " : "
                        + PddOpenApiSupport.formatError(body));
            }
            Long sid = PddOpenApiSupport.parseSpecIdFromSpecIdGetResponse(body);
            if (sid == null || sid <= 0) {
                throw new IllegalStateException("pdd.goods.spec.id.get 未返回 spec_id，spec_name=" + specName + " body="
                        + PddOpenApiSupport.snippet(body, 400));
            }
            ExternalPddProperties.PddSkuOverride ov = new ExternalPddProperties.PddSkuOverride();
            ov.setSpecIdList("[" + sid + "]");
            ov.setProperties(new ArrayList<>());
            out.add(ov);
        }
        return out;
    }

    private static String resolveSpecName(OGoodsSku row, ExternalGoodsUpsertRequest req) {
        if (row != null && StringUtils.hasText(row.getSkuName())) {
            return row.getSkuName();
        }
        if (req != null && req.getSkus() != null) {
            for (ExternalGoodsUpsertRequest.Sku s : req.getSkus()) {
                if (s == null || !StringUtils.hasText(s.getOutSkuId()) || row == null) {
                    continue;
                }
                if (s.getOutSkuId().equals(row.getOuterErpSkuId()) && StringUtils.hasText(s.getSkuName())) {
                    return s.getSkuName();
                }
            }
        }
        return null;
    }
}
