import Vue from 'vue'
import Vuex from 'vuex'
import { ajax as request } from "@/request.js";
Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    config: {
      meta: {
        drawtool: {},
        position: [],
        basemap: [],
      },
      tables: [],
    },
    LocalLocation: {
      currentPosition: '',
      currentLocation: ''
    },
    // 登录后初始化的任务数据
    taskData: {
      selectAllWithTableName: [], // /api/task/selectAllWithTableName 的数据
      selectAll: [], // /api/task/selectAll/ 的数据
      selectTaskHasCreated: [] // /api/task/selectTaskHasCreated 的数据
    },
    // 初始化状态
    taskDataInitialized: false,
    taskDataInitializing: false,
    initError: null // 初始化错误信息
  },
  mutations: {
    updateDrawtool(state, drawtool) {
      //刷新之后 重新赋值 页面数据会丢失
      let config = sessionStorage["Data"]
      if (config) {
        state.config = JSON.parse(config)
      }

      state.config.meta.drawtool = drawtool
      sessionStorage["Data"] = JSON.stringify(state.config)
    },
    updatePosition1(state, position) {
      let config = sessionStorage["Data"]
      if (config) {
        state.config = JSON.parse(config)
      }

      state.config.meta.position = position
      sessionStorage["Data"] = JSON.stringify(state.config)
    },
    updateBasemap(state, basemap) {
      let config = sessionStorage["Data"]
      if (config) {
        state.config = JSON.parse(config)
      }

      state.config.meta.basemap = basemap
      sessionStorage["Data"] = JSON.stringify(state.config)
    },
    updateTables(state, tables) {
      let config = sessionStorage["Data"]
      if (config) {
        state.config = JSON.parse(config)
      }

      state.config.tables = tables
      sessionStorage["Data"] = JSON.stringify(state.config)
    },
    updateData(state, config) {
      state.config = config
    },
    updateLocation(state, location) {
      state.LocalLocation.currentLocation = location
    },
    updatePosition(state, position) {
      state.LocalLocation.currentPosition = position
    },
    // 设置任务数据
    setTaskDataSelectAllWithTableName(state, data) {
      state.taskData.selectAllWithTableName = data
    },
    setTaskDataSelectAll(state, data) {
      state.taskData.selectAll = data
    },
    setTaskDataSelectTaskHasCreated(state, data) {
      state.taskData.selectTaskHasCreated = data
    },
    setTaskDataInitialized(state, value) {
      state.taskDataInitialized = value
    },
    setTaskDataInitializing(state, value) {
      state.taskDataInitializing = value
    },
    setInitError(state, error) {
      state.initError = error
    },
    clearInitError(state) {
      state.initError = null
    }

  },
  actions: {
    updateDrawtool({ commit, state }, obj) {
      commit('updateDrawtool', obj.drawtool)
    },
    updatePosition1({ commit, state }, obj) {
      commit('updatePosition1', obj.position)
    },
    updateBasemap({ commit, state }, obj) {
      commit('updateBasemap', obj.basemap)
    },
    updateTables({ commit, state }, obj) {
      commit("updateTables", obj.tables)
    },
    updateData({ commit, state }, obj) {
      commit("updateData", obj.config)
    },
    updateLocation({ commit, state }, obj) {
      commit("updateLocation", obj.location)
    },
    updatePosition({ commit, state }, obj) {
      commit("updatePosition", obj.position)
    },
    // 初始化任务数据
    async initTaskData({ commit, state }) {
      commit('setTaskDataInitializing', true)
      commit('setTaskDataInitialized', false)
      
      try {
        // 调用3个接口
        const [response1, response2, response3] = await Promise.all([
          request({
            url: "/task/selectAllWithTableName",
            method: "get",
          }),
          request({
            url: "/task/selectAll/",
            method: "get",
          }),
          request({
            url: "/task/selectTaskHasCreated",
            method: "get",
          })
        ])

        // 检查是否有401错误
        if (response1.data.status == "401" || response2.data.status == "401" || response3.data.status == "401") {
          throw new Error("认证失败，请重新登录")
        }

        // 处理第一个接口的数据
        let data1 = response1.data.data || []
        commit('setTaskDataSelectAllWithTableName', data1)

        // 处理第二个接口的数据
        let data2 = []
        if (response2.data.success == true && response2.data.data) {
          try {
            const parsed = JSON.parse(response2.data.data)
            data2 = parsed.data || []
          } catch (e) {
            data2 = response2.data.data || []
          }
        }
        commit('setTaskDataSelectAll', data2)

        // 处理第三个接口的数据
        let data3 = []
        if (response3.data.success == true && response3.data.data) {
          try {
            const parsed = JSON.parse(response3.data.data)
            data3 = parsed.data || []
          } catch (e) {
            data3 = response3.data.data || []
          }
        }
        commit('setTaskDataSelectTaskHasCreated', data3)

        commit('setTaskDataInitialized', true)
        commit('setTaskDataInitializing', false)
        return { success: true }
      } catch (error) {
        commit('setTaskDataInitialized', false)
        commit('setTaskDataInitializing', false)
        return { success: false, error: error.message || '初始化失败，请重试' }
      }
    }

  },
})
