Files
dvcp_v2_webapp/ui/lib/js/area.js
2022-12-01 09:13:53 +08:00

89 lines
2.3 KiB
JavaScript

import request from "./request";
export default class Area {
constructor(code, hash = {}) {
this.id = code
this.level = Area.getLevelByAreaId(code)
this.areaMap = Object.values(this.getAreaInfo(code))
if (Object.keys(hash).length > 0) {
this.getName(this.areaMap.map(id => hash[id]))
}
}
/**
* 获取地区的行政等级
* @param code 地区编码
* @returns {number}
*/
static getLevelByAreaId(code) {
if (code) {
if (code.length === 2 || /0{10}$/.test(code)) return 0;
else if (/0{8}$/.test(code)) return 1;
else if (/0{6}$/.test(code)) return 2;
else if (/0{3}$/.test(code)) return 3;
else return 4
} else return -1
}
/**
* 根据地区编码获取指定等级的地区编码
* @param value 地区编码
* @param level 指定等级
* @returns {string|null|*}
*/
static getAreaCodeByLevel(value, level) {
if (value) {
const areaNumber = value.toString();
switch (level) {
case 0:
return areaNumber.substring(0, 2) + '0000000000';
case 1:
return areaNumber.substring(0, 4) + '00000000';
case 2:
return areaNumber.substring(0, 6) + '000000';
case 3:
return areaNumber.substring(0, 9) + '000';
case 4:
return areaNumber
}
} else return null
}
static createByAction(areaId, ins = request, action = "/admin/area/getAllParentAreaId") {
return ins.post(action, null, {params: {areaId}, withoutToken: 1}).then(res => res?.data?.reverse() || [])
}
getAreaInfo(id) {
let info = {}
const currentLevel = Area.getLevelByAreaId(id);
for (let i = 0; i <= currentLevel; i++) {
info[i] = Area.getAreaCodeByLevel(id, i);
}
return info
}
async getAreaName() {
const names = await Area.createByAction(this.id);
this.getName(names)
}
getName(names) {
this.meta = names
this.nameMap = names?.map(e => e.name) || []
this.name = names?.slice(-1)?.[0]?.name
this.fullname = this.nameMap.join('')
}
/**
* 异步从数据库中获取地区信息
* @returns {Promise<void>}
*/
static async init(code) {
const names = await Area.createByAction(code),
area = new Area(code)
area.getName(names)
return area
}
}