import {pcaa as REGION_DATA} from "@/utils/areaData/pcaUtils";

/**
 * Area 属性all的类型
 */
interface PlainPca {
  id: string;
  text: string;
  pid: string;
  index: Number;
}

/**
 * 省市区工具类 -解决列表省市区组件的翻译问题
 */
class Area {
  all: PlainPca[];

  /**
   * 构造器
   * @param pcaa
   */
  constructor(pcaa?) {
    if (!pcaa) {
      pcaa = REGION_DATA;
    }
    let arr: PlainPca[] = [];
    const province = pcaa['86'];
    Object.keys(province).map((key) => {
      arr.push({ id: key, text: province[key], pid: '86', index: 1 });
      const city = pcaa[key];
      Object.keys(city).map((key2) => {
        arr.push({ id: key2, text: city[key2], pid: key, index: 2 });
        const qu = pcaa[key2];
        if (qu) {
          Object.keys(qu).map((key3) => {
            arr.push({ id: key3, text: qu[key3], pid: key2, index: 3 });
          });
        }
      });
    });
    this.all = arr;
  }

  get pca() {
    return this.all;
  }

  getCode(text) {
    if (!text || text.length == 0) {
      return '';
    }
    for (let item of this.all) {
      if (item.text === text) {
        return item.id;
      }
    }
  }
  
// 代码逻辑说明: [issue/382]省市区组件JAreaLinkage数据不回显---
  getText(code,index=3) {
    if (!code || code.length == 0) {
      return '';
    }
    let arr = [];
    this.getAreaBycode(code, arr, index);
    return arr.join('/');
  }

  getRealCode(code) {
    let arr = [];
    this.getPcode(code, arr, 3);
    return arr;
  }

  getPcode(id, arr, index) {
    for (let item of this.all) {
      if (item.id === id && item.index == index) {
        arr.unshift(id);
        if (item.pid != '86') {
          this.getPcode(item.pid, arr, --index);
        }
      }
    }
  }

  getAreaBycode(code, arr, index) {
    for (let item of this.all) {
      if (item.id === code && item.index == index) {
        arr.unshift(item.text);
        if (item.pid != '86') {
          this.getAreaBycode(item.pid, arr, --index);
        }
      }
    }
  }
}
const jeecgAreaData = new Area();

// 根据code找文本
const getAreaTextByCode = function (code) {
  let index = 3;
  // 代码逻辑说明: 判断code是否是多code逗号分割的字符串，是的话，获取最后一位的code ---
  if (code && code.includes(',')) {
    index = code.split(",").length;
    code = code.substr(code.lastIndexOf(',') + 1);
  }
  return jeecgAreaData.getText(code,index);
};

/**
 * 20260204
 * liaozhiyang
 * 【QQYUN-14694】online支持配置独立的省、市、县 （根据 code 找文本（支持仅省、仅省市、省市区））
 * @param includeParent 是否返回父级路径。默认 false 只返回最后一级（如「长治市」），true 返回完整路径（如「山西省/长治市」）
 * @param level 层级：1=省，2=市，3=县。传入时作为 index 使用，不传则从 code 推断
 */
const getAreaTextByCodeAnyLevel = function (code: string | number | undefined, includeParent = false, level?: 1 | 2 | 3): string {
  if (!code) return '';
  const codeStr = String(code).trim();
  if (!codeStr.length) return '';

  let lastCode: string;
  let index: number;
  let resolvedItem: PlainPca | null = null;

  if (codeStr.includes(',')) {
    const parts = codeStr.split(',').map((s) => s.trim()).filter(Boolean);
    if (!parts.length) return '';
    index = level ?? parts.length;
    lastCode = level != null ? parts[level - 1] : parts[parts.length - 1];
    if (level != null) {
      resolvedItem = jeecgAreaData.all.find((it) => String(it.id) === lastCode && it.index == index) ?? null;
    }
  } else {
    const item = jeecgAreaData.all.find((it) => String(it.id) === codeStr);
    if (!item) return '';
    const itemIndex = item.index as number;
    index = level ?? itemIndex;
    lastCode = codeStr;
    if (level != null && level !== itemIndex) {
      const chain: string[] = [];
      jeecgAreaData.getPcode(codeStr, chain, itemIndex);
      const targetCode = chain[level - 1];
      if (targetCode) {
        lastCode = targetCode;
        resolvedItem = jeecgAreaData.all.find((it) => String(it.id) === targetCode && it.index == level) ?? null;
      } else {
        resolvedItem = item;
      }
    } else {
      resolvedItem = item;
    }
  }
  if (includeParent) {
    return jeecgAreaData.getText(lastCode, index);
  } else {
    const item = resolvedItem ?? jeecgAreaData.all.find((it) => String(it.id) === lastCode && it.index == index);
    return item ? item.text : '';
  }
};

export { getAreaTextByCode, getAreaTextByCodeAnyLevel };
