import Vue from 'vue'
import Vuex from 'vuex'
import * as api from '@/api'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    // 存放状态
    configList: [],
    careerList: [],
    qualificationList: [],
    categoryGoodsList: [],
    categoryActivityList: []
  },
  mutations: {

    setConfigList(state, data) {
      state.configList = data
    },
    setCareerList(state, data) {
      state.careerList = data
    },
    setQualificationList(state, data) {
      state.qualificationList = data
    },
    setCategoryGoodsList(state, data) {
      state.categoryGoodsList = data
    },
    setCategoryActivityList(state, data) {
      state.categoryActivityList = data
    }   
  },
  actions: {
    // 查询配置列表
    async getConfig({ commit }) {
      const res = await api.config.queryConfigList()
      // 要求变成键值对的样子
      const config = res.result.records.reduce((acc, item) => {
        if (!item.paramCode) {
          console.log('paramCode为空', item);
          return acc
        }
        acc[item.paramCode] = item
        return acc
      }, {})
      commit('setConfigList', config)

    },

    // 查询职业列表
    async getCareer({ commit }) {
      const res = await api.config.queryCareerList()
      // if (res.code === 0) {
        commit('setCareerList', res.result.records)
      // } else {
      //   uni.showToast({ title: res.msg, icon: 'error' })
      // }
    },

    // 查询学历列表
    async getQualification({ commit }) {
      const res = await api.config.queryQualificationList()
      // if (res.code === 0) {
        commit('setQualificationList', res.result.records)
      // } else {
      //   uni.showToast({ title: res.msg, icon: 'error' })
      // }
    },

    // 查询商品分类列表
    async getCategoryGoodsList({ commit }) {
      const res = await api.config.queryCategoryGoodsList()
        commit('setCategoryGoodsList', res.result.records)

    },

    // 查询活动分类列表
    async getCategoryActivityList({ commit }) {
      const res = await api.config.queryCategoryActivityList()
      commit('setCategoryActivityList', res.result.records)
    },

    // 初始化数据
    async initData({ dispatch, state }) {
      // 检查是否已初始化
      if (state.configList.length > 0 && state.careerList.length > 0 && state.qualificationList.length > 0 && state.categoryGoodsList.length > 0 && state.categoryActivityList.length > 0) {

        console.log('配置数据已初始化，无需重复初始化')
        return
      }

      try {
        await Promise.all([
          dispatch('getConfig'),
          dispatch('getCareer'),
          dispatch('getQualification'),
          dispatch('getCategoryGoodsList'),
          dispatch('getCategoryActivityList')
        ])
        console.log('所有配置数据初始化完成')
      } catch (error) {
        console.error('配置数据初始化失败:', error)
      }
    },

    
  }
})

export default store