package com.jeesharp.business.modules.common.bizscene.support;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Getter;

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

/**
 * 解析管理端分页列表接口响应（{@code AjaxResult.data.records}），供轮播/优惠券等按注册表 URL 选目标。
 *
 * @author jeesharp
 * @since 2026-07-03
 */
public final class BizSceneAdminListRecordSupport {

    private static final String[] NAME_FALLBACK_FIELDS = {
            "spuName", "name", "headline", "productName", "packageName", "specLabel", "title", "programName"
    };

    private BizSceneAdminListRecordSupport() {
    }

    public static String buildListRequestBody(String keywordField, String keyword, int pageSize) {
        JSONObject body = new JSONObject();
        body.set("pageNo", 1);
        body.set("pageSize", pageSize);
        body.set("status", 1);
        if (StrUtil.isNotBlank(keyword) && StrUtil.isNotBlank(keywordField)) {
            body.set(keywordField.trim(), keyword.trim());
        }
        return body.toString();
    }

    public static List<AdminListRow> parseRows(String responseBody, String nameField) {
        if (StrUtil.isBlank(responseBody)) {
            return List.of();
        }
        JSONObject root;
        try {
            root = JSONUtil.parseObj(responseBody);
        } catch (Exception ex) {
            return List.of();
        }
        if (root.getInt("code", 0) != 200) {
            return List.of();
        }
        JSONObject data = root.getJSONObject("data");
        if (data == null) {
            return List.of();
        }
        JSONArray records = data.getJSONArray("records");
        if (records == null || records.isEmpty()) {
            return List.of();
        }
        List<AdminListRow> out = new ArrayList<>();
        for (int i = 0; i < records.size(); i++) {
            JSONObject row = records.getJSONObject(i);
            if (row == null) {
                continue;
            }
            String id = row.getStr("id");
            if (StrUtil.isBlank(id)) {
                continue;
            }
            String label = resolveName(row, nameField);
            out.add(new AdminListRow(id.trim(), label));
        }
        return out;
    }

    /**
     * 解析管理端详情接口 {@code AjaxResult.data}。
     */
    public static JSONObject parseInfoData(String responseBody) {
        if (StrUtil.isBlank(responseBody)) {
            return null;
        }
        try {
            JSONObject root = JSONUtil.parseObj(responseBody);
            if (root.getInt("code", 0) != 200) {
                return null;
            }
            return root.getJSONObject("data");
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 详情行是否处于可跳转的上线/启用态（兼容 status / publishStatus / shelfStatus 等字段）。
     */
    public static boolean isSelectableRow(JSONObject row) {
        if (row == null || row.isEmpty()) {
            return false;
        }
        if (row.containsKey("status")) {
            Integer status = row.getInt("status");
            return status != null && status == 1;
        }
        if (row.containsKey("publishStatus")) {
            Integer publishStatus = row.getInt("publishStatus");
            return publishStatus != null && publishStatus == 1;
        }
        if (row.containsKey("shelfStatus")) {
            Integer shelfStatus = row.getInt("shelfStatus");
            return shelfStatus != null && shelfStatus == 1;
        }
        return true;
    }

    public static String resolveRowLabel(JSONObject row, String nameField) {
        if (row == null) {
            return "";
        }
        return resolveName(row, nameField);
    }

    private static String resolveName(JSONObject row, String nameField) {
        if (StrUtil.isNotBlank(nameField)) {
            String v = row.getStr(nameField.trim());
            if (StrUtil.isNotBlank(v)) {
                return v.trim();
            }
        }
        for (String field : NAME_FALLBACK_FIELDS) {
            String v = row.getStr(field);
            if (StrUtil.isNotBlank(v)) {
                return v.trim();
            }
        }
        return row.getStr("id");
    }

  /**
     * 管理端列表行（id + 展示名）。
     */
    @Getter
    public static final class AdminListRow {

        private final String id;
        private final String label;

        public AdminListRow(String id, String label) {
            this.id = id;
            this.label = label;
        }
    }
}
