import Vue from "vue";
import Vuex from "vuex";
import { queryAllWorkType } from "@/services/workload";
import { queryDep } from "@/services/project";

Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    typeList: [],
    allType: {},
    currentProject: {},
    depUserTree: [],
  },
  mutations: {
    setType(state, values) {
      state.typeList = values.typeList;
      state.allType = values.allType;
    },
    setCurrentProject(state, project) {
      state.currentProject = project;
    },
    setDep(state, dep) {
      const getDepUserTree = (data) => {
        let ret = {};
        ret.text = data.Name;
        ret.value = `${data.ID}-0`;
        if (data.children) {
          if (!ret.children) ret.children = [];
          data.children.forEach((item) => {
            ret.children.push(getDepUserTree(item));
          });
        }
        if (data.Users && data.Users.length !== 0) {
          if (!ret.children) ret.children = [];
          data.Users.forEach((item) => {
            let user = {};
            user.text = item.CName;
            user.value = `${data.ID}-${item.ID}`;
            ret.children.push(user);
          });
        }
        return ret;
      };
      state.depUserTree = dep.data.list.map((item) => getDepUserTree(item));
    },
  },
  actions: {
    getType: async function ({ commit, state }, value) {
      if (state.typeList.length > 0) return;
      commit("setType", await queryAllWorkType());
    },
    getDep: async function ({ commit, state }, value) {
      if (state.depUserTree.length > 0) return;
      commit("setDep", await queryDep());
    },
  },
});
export default store;
