import {
  getMuseumTreeV1,
  getSysRegionTree
} from '@/api/org'

const getDefaultState = () => {
  return {
    museumTree: [], //博物馆树
    regionTree: [], //行政区划树
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_MUSEUM_TREE: (state, museumTree) => {
    state.museumTree = museumTree
  },
  SET_REGION_TREE: (state, regionTree) => {
    state.regionTree = regionTree
  }
}

const actions = {
  getMuseumTreeData({
    commit
  }, isReload) {
    // 如果是空或者需要重新加载则重新调取接口获取，否则直接获取状态管理中的
    if (state.museumTree || state.museumTree.length < 0 || isReload) {
      return new Promise((resolve, reject) => {
        getMuseumTreeV1({
          deptId: ''
        }).then(response => {
          const {
            data
          } = response
          commit('SET_MUSEUM_TREE', data)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    } else {
      return new Promise((resolve, reject) => {
        resolve(state.museumTree)
      })
    }

  },
  getSysRegionTreeData({
    commit
  }, parentId) {
    if (state.regionTree && state.regionTree.length > 0) {
      return new Promise((resolve, reject) => {
        resolve(state.regionTree)
      })
    } else {
      return new Promise((resolve, reject) => {
        getSysRegionTree({
          parentId
        }).then(response => {
          const {
            data
          } = response
          commit('SET_REGION_TREE', data)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    }

  },

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
