import { getAllWx, listAll } from "dinkle/service/api";

// states
const state = {
  // 文宣模块列表
  tabList: undefined,
  // pk列表数据
  pkList: [],
  // 查询关键字
  searchKey: undefined,
  // 产品参数列表
  paramList: undefined
};

// mutations:
// this.$store.commit("dinkle/xxx");
const mutations = {
  SET_TAB_LIST(state, payload) {
    state.tabList = payload;
  },
  ADD_PK_LIST(state, payload) {
    const list = state.pkList;
    const isExist = list.some(pk => pk.id == payload.id);
    if (!isExist) state.pkList.push(payload);
  },
  DEL_PK_LIST(state) {
    state.pkList = state.pkList.filter(item => !item.isSelected);
  },
  SET_SEARCH_KEY(state, payload) {
    state.searchKey = payload;
  },
  SET_PARAM_LIST(state, payload) {
    state.paramList = payload;
  }
};

// actions
// this.$store.dispatch("dinkle/xxx");
const actions = {
  // 记录文宣模块列表
  async SYNC_TAB_LIST({ commit, state }) {
    if (state.tabList) return state.tabList;
    const res = await getAllWx();
    const list = res.data.map(({ id, moduleName }) => {
      return { id, moduleName };
    });
    commit("SET_TAB_LIST", list);
    return list;
  },
  // 记录产品参数列表
  async SYNC_PARAM_LIST({ commit, state }) {
    if (state.paramList) return state.paramList;
    const resp = await listAll();
    // 参数排序 paramPriority: 返回差值而不是 Boolean
    const list = resp.data.sort(
      (itemA, itemB) => itemA.paramPriority - itemB.paramPriority
    );
    console.log("xxx", list);
    const paramList = list.reduce((acc, cur) => {
      // 去除水中隐藏字段
      if (Number(cur.paramStatus)) return acc;
      // 初始化值, 也需要读取数据
      if (!([cur.paramType] in acc)) {
        acc[cur.paramType] = [];
      }
      acc[cur.paramType].push(cur.paramName);
      return acc;
    }, {});
    commit("SET_PARAM_LIST", paramList);
    console.log(paramList);
    return paramList;
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
