import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { reverseGeocoding } from '@/api/common'
import $modal from '@/plugins/modal'

const location = {
  state: {
    // 包括手机系统经纬度+省市区名字等信息
    location: storage.get(constant.location)
  },

  mutations: {
    SET_LOCATION: (state, location) => {
      state.location = location
      storage.set(constant.location, location)
    }
  },

  actions: {
    // 获取本机位置信息
    GetLocation({ commit }) {
      // getLocation 获取经纬度
      // chooseLocation 让用户在地图手选位置
      return new Promise((resolve, reject) => {
        uni.getLocation({
          success: async (res) => {
            // 经纬度调 百度 逆地理编码获取省市区名字
            const { result } = await reverseGeocoding({
              params: {
                location: res.latitude + "," + res.longitude
              }
            })
            commit('SET_LOCATION', result)
            resolve(result)
          },
          fail: (err) => {
            $modal.msgError("请允许获取位置权限");
            reject(err)
          }
        })
      })
    },
  }
}

export default location
