// 1 => LOADING
// 2 => DONE
// 3 => ERROR

import * as api from "../api/api.js";

export default {
  namespaced: true,
  state: {
    errMessage: "",
    alertError: false,
    snackbar: {
        state: false,
        type: 'success',
        message: '',
    },
    loadingAutocomplete: false,
    divisionOptions: [],
    selectedDivision: {},
    user: one_user(),
    currentPage: 1,
    loadingStatus: 1, // 1 => LOADING, 2 => DONE, 3 => ERROR
    itemUsageList: [],
    selectedItemUsage: {},
    totalPage: 0,
    dialogUsage: false,
    unitList: [],
    selectedItemUnit: {},
    usedQty: 0,
    errors: [],
    last_id: -1,
    xsearch: "",
    dialogform: false,
    itemRequestList: [],
    emptycheck: [],
    dialogUnit: false,
    selectedUnit: {},
    unitOptions: [],
    loadingUnit: false,
  },
  mutations: {
    updateErrMessage(state, val) {
      state.errMessage = val;
    },
    updateAlertError(state, val) {
      state.alertError = val;
    },
    updateSnackbar(state, val) {
      state.snackbar = val;
    },
    updateLoadingAutocomplete(state, val) {
      state.loadingAutocomplete = val;
    },
    updateDivisionOptions(state, val) {
      state.divisionOptions = val;
    },
    updateSelectedDivision(state, val) {
      state.selectedDivision = val;
    },
    updateUser(state, val) {
      state.user = val;
    },
    updateCurrentPage(state, val) {
      state.currentPage = val;
    },
    updateLoadingStatus(state, val) {
      state.loadingStatus = val;
    },
    updateItemUsageList(state, val) {
      state.itemUsageList = val;
    },
    updateSelectedItemUsage(state, val) {
      state.selectedItemUsage = val;
    },
    updateTotalPage(state, val) {
      state.totalPage = val;
    },
    updateDialogUsage(state, val) {
      state.dialogUsage = val;
    },
    updateUnitList(state, val) {
      state.unitList = val;
    },
    updateSelectedItemUnit(state, val) {
      state.selectedItemUnit = val;
    },
    updateUsedQty(state, val) {
      state.usedQty = val;
    },
    updateErrors(state, val) {
      state.errors = val;
    },
    update_last_id(state, val) {
      state.last_id = val
    },
    updateXsearch(state, val) {
      state.xsearch = val
    },
    updateDialogform(state, val) {
      state.dialogform = val
    },
    updateItemRequestList(state, val) {
      state.itemRequestList = val
    },
    updateEmptycheck(state, val) {
      state.emptycheck = val
    },
    updateLoadingUnit(state, val) {
      state.loadingUnit = val;
    },
    updateDialogUnit(state, val) {
      state.dialogUnit = val;
    },
    updateSelectedUnit(state, val) {
      state.selectedUnit = val;
    },
    updateUnitOptions(state, val) {
      state.unitOptions = val;
    }
  },
  actions: {
    async getDivisionByUser(context) {
      context.commit("updateLoadingAutocomplete", true)
      try {
        let payload = {}
        payload.token = one_token()
        payload.userId = context.state.user.M_UserID
        let response = await api.getDivisionByUser(payload);
        if (response.status != "OK") {
          context.commit("updateLoadingAutocomplete", false)
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingAutocomplete", false)
          let data = {
          records: response.data.records,
          selected: response.data.selected
          };
          context.commit("updateDivisionOptions", data.records);
          context.commit("updateSelectedDivision", data.selected[0]);
        }
      } catch (e) {
          context.commit("updateLoadingAutocomplete", false)
          context.commit("updateErrMessage", e.message);
          context.commit("updateAlertError", true);
      }
    },
    async search(context, payload) {
      context.commit("updateLoadingStatus", 1);
      try {
        // var payload = {
        //   token: one_token(),
        //   currentPage: context.state.currentPage,
        //   divisionID: context.state.selectedDivision == undefined ? 0 : context.state.selectedDivision.DivisionID,
        //   search: context.state.xsearch,
        // };
        payload.token = one_token();

        let response = await api.search(payload);
        if (response.status != "OK") {
          context.commit("updateLoadingStatus", 3);
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingStatus", 2);
          context.commit("updateErrMessage", "");
          let data = {
            records: response.data.records,
            total_page: response.data.total_page,
          };

          context.commit("updateItemUsageList", data.records);
          context.commit("updateTotalPage", data.total_page);

          if (context.state.last_id == -1) {
              if (response.data && response.data.records.length > 0) {
                  context.commit("updateSelectedItemUsage", response.data.records[0])
              }
          } else {
              let idx = _.findIndex(response.data.records, function (o) {
                  return o.ItemUsageID == context.state.selectedItemUsage.ItemUsageID
              });
              if (idx >= 0) {
                  context.commit("updateSelectedItemUsage", response.data.records[idx]);
              }
          }
        }
      } catch (e) {
        context.commit("updateLoadingStatus", 3);
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },
    async getUnit(context, payload) {
      context.commit("updateLoadingAutocomplete", 1);
      try {
          payload.token = one_token()

        let response = await api.getUnit(payload);
        if (response.status != "OK") {
          context.commit("updateLoadingAutocomplete", 3);
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingAutocomplete", 2);
          context.commit("updateErrMessage", "");
          let data = {
            records: response.data.records
          };

          context.commit("updateUnitList", data.records);
        }
      } catch (e) {
        context.commit("updateLoadingAutocomplete", 3);
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },
    async saveItemUsage(context, payload) {
      context.commit("updateLoadingStatus", 1);
      try {
        payload.token = one_token();

        let response = await api.saveItemUsage(payload);
        if (response.status != "OK") {
          context.commit("updateLoadingStatus", 3);
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingStatus", 2);
          context.commit("updateErrMessage", "");
          let data = {
            records: response.data.records,
          };


          context.commit("updateDialogform", false);
          context.commit("updateItemRequestList", []);
          context.commit("update_last_id", payload.ItemUsageID)

          context.commit("updateSnackbar", {
            state: true,
            type: 'success',
            message: 'Item usage saved successfully.'
          });
          context.dispatch("search", {
            currentPage: payload.currentPageUsage,
            divisionID: payload.divisionID,
            search: payload.searchUsage
          });
          context.dispatch("used/getItemUsed", {
            itemUsageID: payload.ItemUsageID,
            currentPage: payload.currentPage,
            search: payload.search,
            statusConfirm: payload.statusConfirm,
          }, { root: true });
        }
      } catch (e) {
        context.commit("updateLoadingStatus", 3);
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },
    async getUnitByItemId(context, payload) {
      context.commit("updateLoadingUnit", true)
      context.commit("updateDialogUnit", true);
      try {
        payload.token = one_token();
        let response = await api.getUnitByItemId(payload);
        if (response.status != "OK") {
          context.commit("updateLoadingUnit", false)
          context.commit("updateDialogUnit", false);
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingUnit", false)
          context.commit("updateErrMessage", "");
          context.commit("updateUnitOptions", response.data.records);
          context.commit("updateSelectedUnit", payload.selectedUnit);
          
        }
      } catch (e) {
        context.commit("updateLoadingUnit", false)
        context.commit("updateDialogUnit", false);
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    }
  }
};