/** 订单标签 texiao_json 规范化（兼容字符串 / 对象） */
export function parseTexiaoJson(raw) {
  if (!raw) return {};
  if (typeof raw === 'object') return { ...raw };
  if (typeof raw === 'string') {
    try {
      const parsed = JSON.parse(raw);
      return typeof parsed === 'object' && parsed ? { ...parsed } : {};
    } catch (e) {
      return {};
    }
  }
  return {};
}

/** 合并顶层 color / flash 与 texiao_json */
export function mergeTagTexiao(tag) {
  const texiao = parseTexiaoJson(tag.texiao_json);
  const color = tag.color || texiao.color || texiao.bg_color;
  if (color) {
    texiao.color = color;
  }
  if (tag.flash_enabled != null && texiao.flash == null) {
    texiao.flash = !!tag.flash_enabled;
  }
  return texiao;
}

export function normalizeTagList(list) {
  if (!Array.isArray(list)) return [];
  return list.map((tag) => ({
    ...tag,
    id: tag.id,
    mingcheng: tag.mingcheng || tag.name || '',
    texiao_json: mergeTagTexiao(tag),
  }));
}

export function normalizeOrderTags(item) {
  return {
    xuqiu_biaoqian: normalizeTagList(item.xuqiu_biaoqian),
    dashou_biaoqian: normalizeTagList(item.dashou_biaoqian),
    shangjia_biaoqian: normalizeTagList(item.shangjia_biaoqian),
    shangjia_identity_biaoqian: normalizeTagList(item.shangjia_identity_biaoqian),
    zhiding_identity_biaoqian: normalizeTagList(item.zhiding_identity_biaoqian),
  };
}
