import { getServerList } from '@/api/baseSource/server'

const state = {
  urls: '', // 所有图层信息
  baseUrl: '', // 服务基础地址
  partsUrl: '', // 部件分层地址
  partsAllUrl: '', // 部件不分层地址
  shopUrl: '', // 商户图层
  mapUrl: '', // 二维底图地址
  mapDtUrl: '', // 无网格地图
  gridUrl: '', // 网格图层
  editUrl: '' // 编辑地图URL
}
const mutations = {
  SET_URLS: (state, urls) => {
    state.urls = JSON.stringify(urls)
  },
  SET_BASE_URL: (state, url) => {
    state.baseUrl = url
  },
  SET_PARTS_URL: (state, url) => {
    state.partsUrl = url
  },
  SET_PARTS_EDIT_URL: (state, url) => {
    state.partsEditUrl = url
  },
  SET_PARTS_ALL_URL: (state, url) => {
    state.partsAllUrl = url
  },
  SET_SHOP_URL: (state, url) => {
    state.shopUrl = url
  },
  SET_MAP_URL: (state, url) => {
    state.mapUrl = url
  },
  SET_MAPDT_URL: (state, url) => {
    state.mapDtUrl = url
  },
  SET_GRID_URL: (state, url) => {
    state.gridUrl = url
  },
  SET_EDIT_URL: (state, url) => {
    state.editUrl = url
  }
}

const actions = {
  // 获取地图图层，并存在cookie中，避免重复取数据耗费时间
  GetUrls({ commit }) {
    return new Promise((resolve, reject) => {
      const listQuery = { offset: 1, limit: 100 }
      getServerList(listQuery).then(response => {
        if (response.code === 200) {
          const data = response.data.rows
          commit('SET_URLS', data)
          const urls = data
          // 遍历所以有地址获取
          for (const item of urls) {
            if (item.name === 'GIS地图') {
              commit('SET_BASE_URL', item.url)
            } else if (item.name === '部件分层URL') {
              commit('SET_PARTS_URL', item.url)
              const editUrl = item.url.replace(/MapServer/, 'FeatureServer')
              commit('SET_PARTS_EDIT_URL', editUrl)
            } else if (item.name === '部件地图URL') {
              commit('SET_PARTS_ALL_URL', item.url)
            } else if (item.name === '商户图层URL') {
              commit('SET_SHOP_URL', item.url)
            } else if (item.name === '二维地图URL') {
              commit('SET_MAP_URL', item.url)
            } else if (item.name === '无网格地图URL') {
              commit('SET_MAPDT_URL', item.url)
            } else if (item.name === '网格图层URL') {
              commit('SET_GRID_URL', item.url)
            } else if (item.name === '编辑地图URL') {
              commit('SET_EDIT_URL', item.url)
            }
          }
          resolve()
        } else {
          reject(response)
        }
      }).catch(error => {
        reject(error)
      })
    })
  }
}

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