import { listProject } from '@/api/oa/project.js'
import { listUser } from '@/api/oa/user.js'
import { getDicts } from '@/api/oa/dict.js'

const state = {
  projectList: [],
  userList: [],
  projectMap: {},
  userMap: {}, // 修正：添加逗号
  dicts: {}
}

const mutations = {
  SET_DICT(state, data) {
    state.dicts[data.type] = data.value
  },
  SET_USER(state, list) {
    state.userList = list;
    let o = {};
    for (let i = 0; i < list.length; i++) {
      o[list[i].userId] = list[i];
    }
    state.userMap = o;
  },
  SET_PROJECT(state, list) {
    state.projectList = list;
    let o = {};
    for (let i = 0; i < list.length; i++) {
      o[list[i].projectId] = list[i];
    }
    state.projectMap = o;
  }
}

const actions = {
  setDict({ commit, state }, dictType) {
    // 查找state中是否已经有dictType，如果已存在则不处理，否则请求数据并添加
    if (!state.dicts[dictType]) {
      // 调用获取字典的接口，传入字典类型
      getDicts(dictType).then(res => {
        // 假设接口返回的数据结构为 { data: [...] }，根据实际接口调整
        commit('SET_DICT', {
          type: dictType,
          value: res.data
        })
      }).catch(error => {
        console.error('获取字典数据失败：', error)
      })
    }
  },
  setUser({ commit, state }, { refresh }) {
		if (!refresh && state.userList.length > 0) {
			return;
		}
    listUser({ pageSize: 999, pageNum: 1 }).then(res => {
      commit('SET_USER', res.rows)
    }).catch(error => {
      console.error('获取用户列表失败：', error)
    })
  },
  setProject({ commit, state }, { refresh }) {
		if (!refresh && state.projectList.length > 0) {
			return;
		}
    // 与setUser逻辑类似，调用项目列表接口并提交mutation
    listProject({ pageSize: 999, pageNum: 1 }).then(res => {
      commit('SET_PROJECT', res.rows)
    }).catch(error => {
      console.error('获取项目列表失败：', error)
    })
  }
}

export default {
  state,
  mutations,
  actions
}