function format(data) {
  const result = [];
  const dic = {'0': {label: 'root', value: '0', children: result}};
  const labelResult = []
  const labelChild = {'0': {label: 'root', value: '0', children: labelResult}};

  data.forEach(item => {
    if (item.layer > 3) {
      return;
    }
    const node = {
      label: item.areaName,
      value: item.areaId,
      quickQuery: item.quickQuery,
      simpleSpelling: item.simpleSpelling,
      parentId: item.parentId
    };
    if (dic.hasOwnProperty(item.parentId)) {
      if (!dic[item.parentId].children) {
        dic[item.parentId].children = [];
      }
      dic[item.parentId].children.push(node);
    } else {
      dic[item.parentId] = {children: [node]};
    }
    if (dic.hasOwnProperty(item.areaId)) {
      dic[item.areaId].label = item.areaName;
      dic[item.areaId].value = item.areaId;
    } else {
      dic[item.areaId] = node;
    }
    const nodeR = {
      label: item.areaName,
      value: item.areaName,
      quickQuery: item.quickQuery,
      simpleSpelling: item.simpleSpelling,
      parentId: item.parentId,
      valueId: item.areaId,
    };
    if (labelChild.hasOwnProperty(item.parentId)) {
      if (!labelChild[item.parentId].children) {
        labelChild[item.parentId].children = [];
      }
      labelChild[item.parentId].children.push(nodeR);
    } else {
      labelChild[item.parentId] = {children: [nodeR]};
    }
    if (labelChild.hasOwnProperty(item.areaId)) {
      labelChild[item.areaId].label = item.areaName;
      labelChild[item.areaId].value = item.areaName;
    } else {
      labelChild[item.areaId] = nodeR;
    }

  });
  return {data: result, dic, labelData: labelResult};
}

let loaded = false

const area = {
  state: {data: [], dic: {}, labelData: []},
  actions: {
    InitArea({commit}) {
      if (!loaded) {
        loaded = true
        import('@/util/area').then((resp) => {
          commit('SET_AREA', format(resp.default));
        })
      }
    },
  },
  mutations: {
    SET_AREA: (state, data) => {
      state.data = data.data
      state.dic = data.dic
      state.labelData = data.labelData
    },
  },
  getters: {
    getAreaParents: (state) => (id) => {
      const res = [];
      let item = state.dic[id];
      while (item && item.value !== '0') {
        id = item.parentId;
        res.unshift(item);
        item = state.dic[id];
      }
      return res
    }
  }
};

export default area;
