package com.ruoyi.jarvis.util;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.jarvis.domain.dto.QuickRecordModelShopOption;
import com.ruoyi.jarvis.domain.JDOrder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 解析快捷录单型号店铺配置：每行/逗号分隔，格式「短前缀（完整店名）」。
 */
public final class QuickRecordModelShopOptionUtil {

    public static final String CONFIG_KEY = "quickRecord.modelShopOptions";

    private static final Pattern LINE_PATTERN = Pattern.compile("^(.+?)[（(](.+)[）)]$");

    private QuickRecordModelShopOptionUtil() {
    }

    public static List<QuickRecordModelShopOption> parseOptions(String raw) {
        if (StringUtils.isEmpty(raw)) {
            return Collections.emptyList();
        }
        String[] parts = raw.split("[\\r\\n,，]+");
        List<QuickRecordModelShopOption> list = new ArrayList<>();
        for (String part : parts) {
            if (StringUtils.isEmpty(part)) {
                continue;
            }
            QuickRecordModelShopOption opt = parseOneLine(part.trim());
            if (opt != null && StringUtils.isNotEmpty(opt.getPrefix())) {
                list.add(opt);
            }
        }
        return list;
    }

    private static QuickRecordModelShopOption parseOneLine(String line) {
        if (StringUtils.isEmpty(line)) {
            return null;
        }
        Matcher m = LINE_PATTERN.matcher(line);
        QuickRecordModelShopOption opt = new QuickRecordModelShopOption();
        if (m.matches()) {
            opt.setPrefix(m.group(1).trim());
            opt.setFullName(m.group(2).trim());
        } else {
            opt.setPrefix(line.trim());
            opt.setFullName("");
        }
        opt.setLabel(buildLabel(opt.getPrefix(), opt.getFullName()));
        return opt;
    }

    private static String buildLabel(String prefix, String fullName) {
        if (StringUtils.isEmpty(fullName)) {
            return prefix;
        }
        return prefix + "（" + fullName + "）";
    }

    /**
     * 从完整型号末尾匹配已知店铺前缀（长前缀优先），用于回显拆分。
     */
    public static String[] splitModelSuffix(String fullModel, List<QuickRecordModelShopOption> options) {
        String full = StringUtils.trim(fullModel);
        if (StringUtils.isEmpty(full) || options == null || options.isEmpty()) {
            return new String[] { full, "" };
        }
        List<QuickRecordModelShopOption> sorted = new ArrayList<>(options);
        sorted.sort((a, b) -> {
            int la = a.getPrefix() != null ? a.getPrefix().length() : 0;
            int lb = b.getPrefix() != null ? b.getPrefix().length() : 0;
            return Integer.compare(lb, la);
        });
        for (QuickRecordModelShopOption opt : sorted) {
            String prefix = opt.getPrefix();
            if (StringUtils.isEmpty(prefix)) {
                continue;
            }
            if (full.endsWith(prefix) && full.length() > prefix.length()) {
                return new String[] { full.substring(0, full.length() - prefix.length()), prefix };
            }
        }
        return new String[] { full, "" };
    }

    public static String fullModelNumber(String base, String shop) {
        String b = StringUtils.trim(base);
        String s = StringUtils.trim(shop);
        if (StringUtils.isEmpty(b)) {
            return s;
        }
        if (StringUtils.isEmpty(s)) {
            return b;
        }
        if (b.endsWith(s)) {
            return b;
        }
        return b + s;
    }

    public static String fullModelNumber(JDOrder order) {
        if (order == null) {
            return "";
        }
        return fullModelNumber(order.getModelNumber(), order.getModelShop());
    }

    /**
     * 落库前归一化：model_number 仅存本体，model_shop 存店铺前缀。
     * 若 model_shop 已有值则仅纠正 model_number 仍带后缀的情况。
     */
    public static void normalizeOrderModelShop(JDOrder order, List<QuickRecordModelShopOption> options) {
        if (order == null) {
            return;
        }
        String base = StringUtils.trim(order.getModelNumber());
        String shop = StringUtils.trim(order.getModelShop());
        if (StringUtils.isNotEmpty(shop)) {
            if (StringUtils.isNotEmpty(base) && base.endsWith(shop) && base.length() > shop.length()) {
                order.setModelNumber(base.substring(0, base.length() - shop.length()));
            }
            order.setModelShop(shop);
            return;
        }
        if (StringUtils.isEmpty(base)) {
            order.setModelShop("");
            return;
        }
        String[] split = splitModelSuffix(base, options);
        order.setModelNumber(split[0]);
        order.setModelShop(split[1]);
    }

    /** 京粉/型号配置 lookup 用本体型号 */
    public static String lookupModelBase(String rawModel, List<QuickRecordModelShopOption> options) {
        String[] split = splitModelSuffix(StringUtils.trim(rawModel), options);
        return split[0];
    }
}
