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

  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;
    }
  });
  return {data: result, dic};
}

let loaded = false

const area = {
  state: {data: [], dic: {}},
  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
    },
  },
  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;
