package com.jeesharp.business.modules.setting.application.support;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jeesharp.business.modules.setting.entity.CmsHomeGridIntro;
import com.jeesharp.business.modules.setting.entity.CmsHomeQuickGrid;
import com.jeesharp.business.modules.setting.enums.HomeQuickGridIntroListLayoutEnum;
import com.jeesharp.business.modules.setting.vo.HomeGridIntroBannerItemVO;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * 宫格介绍列表布局：JSON 解析、Tab 标签与轮播规范化。
 *
 * @author jeesharp
 * @since 2026-07-14
 */
public final class HomeQuickGridIntroLayoutSupport {

    private static final String TAB_ALL = "全部";

    private HomeQuickGridIntroLayoutSupport() {
    }

    public static int resolveListLayout(CmsHomeQuickGrid grid) {
        if (grid == null || grid.getIntroListLayout() == null) {
            return HomeQuickGridIntroListLayoutEnum.CARD.getValue();
        }
        HomeQuickGridIntroListLayoutEnum e = HomeQuickGridIntroListLayoutEnum.fromValue(grid.getIntroListLayout());
        return e != null ? e.getValue() : HomeQuickGridIntroListLayoutEnum.CARD.getValue();
    }

    public static List<HomeGridIntroBannerItemVO> parseBanners(String raw) {
        List<HomeGridIntroBannerItemVO> out = new ArrayList<>();
        String trimmed = StrUtil.trimToEmpty(raw);
        if (StrUtil.isBlank(trimmed) || !trimmed.startsWith("[")) {
            return out;
        }
        try {
            JSONArray arr = JSONUtil.parseArray(trimmed);
            for (int i = 0; i < arr.size(); i++) {
                Object el = arr.get(i);
                if (el instanceof CharSequence s) {
                    String url = s.toString().trim();
                    if (StrUtil.isNotBlank(url)) {
                        HomeGridIntroBannerItemVO vo = new HomeGridIntroBannerItemVO();
                        vo.setImageUrl(url);
                        out.add(vo);
                    }
                    continue;
                }
                if (!(el instanceof JSONObject obj)) {
                    continue;
                }
                String imageUrl = firstNonBlank(obj, "imageUrl", "image_url", "url", "src");
                if (StrUtil.isBlank(imageUrl)) {
                    continue;
                }
                HomeGridIntroBannerItemVO vo = new HomeGridIntroBannerItemVO();
                vo.setImageUrl(imageUrl);
                vo.setTitle(firstNonBlank(obj, "title", "label"));
                vo.setLinkUrl(firstNonBlank(obj, "linkUrl", "link_url", "link"));
                out.add(vo);
            }
        } catch (Exception ignored) {
            return new ArrayList<>();
        }
        return out;
    }

    public static String normalizeBannerJson(String raw) {
        String trimmed = StrUtil.trimToEmpty(raw);
        if (StrUtil.isBlank(trimmed)) {
            return "[]";
        }
        if (!trimmed.startsWith("[")) {
            throw new IllegalArgumentException("轮播图须为 JSON 数组");
        }
        parseBanners(trimmed);
        return trimmed;
    }

    public static String normalizeTabLabelsJson(String raw) {
        String trimmed = StrUtil.trimToEmpty(raw);
        if (StrUtil.isBlank(trimmed)) {
            return "[]";
        }
        if (!trimmed.startsWith("[")) {
            throw new IllegalArgumentException("Tab 标签须为 JSON 数组");
        }
        List<String> labels = parseStringList(trimmed);
        if (labels.isEmpty()) {
            return "[]";
        }
        return JSONUtil.toJsonStr(labels);
    }

    public static List<String> buildTabLabels(CmsHomeQuickGrid grid, List<CmsHomeGridIntro> publishedRows) {
        List<String> configured = parseStringList(grid == null ? null : grid.getIntroTabLabels());
        Set<String> set = new LinkedHashSet<>();
        set.add(TAB_ALL);
        if (!configured.isEmpty()) {
            for (String label : configured) {
                if (StrUtil.isNotBlank(label) && !TAB_ALL.equals(label.trim())) {
                    set.add(label.trim());
                }
            }
            return new ArrayList<>(set);
        }
        if (publishedRows != null) {
            for (CmsHomeGridIntro row : publishedRows) {
                String cat = StrUtil.trimToNull(row.getCategory());
                if (cat != null) {
                    set.add(cat);
                }
            }
        }
        return new ArrayList<>(set);
    }

    public static List<String> parseTags(String tagsJson) {
        return parseStringList(tagsJson);
    }

    public static String normalizeTagsJson(String raw) {
        String trimmed = StrUtil.trimToEmpty(raw);
        if (StrUtil.isBlank(trimmed)) {
            return "[]";
        }
        if (!trimmed.startsWith("[")) {
            throw new IllegalArgumentException("标签须为 JSON 数组");
        }
        return JSONUtil.toJsonStr(parseStringList(trimmed));
    }

    private static List<String> parseStringList(String raw) {
        List<String> out = new ArrayList<>();
        String trimmed = StrUtil.trimToEmpty(raw);
        if (StrUtil.isBlank(trimmed) || !trimmed.startsWith("[")) {
            return out;
        }
        try {
            JSONArray arr = JSONUtil.parseArray(trimmed);
            for (int i = 0; i < arr.size(); i++) {
                String s = StrUtil.trimToNull(arr.getStr(i));
                if (s != null) {
                    out.add(s);
                }
            }
        } catch (Exception ignored) {
            return new ArrayList<>();
        }
        return out;
    }

    private static String firstNonBlank(JSONObject obj, String... keys) {
        for (String key : keys) {
            String v = StrUtil.trimToNull(obj.getStr(key));
            if (v != null) {
                return v;
            }
        }
        return null;
    }
}
