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

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

export default {
  namespaced: true,
  state: {
    user: one_user(),
    mainTable: [],
    detailTable: [],
    countMainTable: 0,
    countDetailTable: 0,
    mainTableLoadingStatus: 0,
    detailTableLoadingStatus: 0,
    mainTableErrorMessage: "",
    detailTableErrorMessage: "",
    mainTableCurrentPage: 1,
    mainTableLastId: -1,

    selectedMainTable: {},
    selectedDetailTable: {},

    statusOptions: [
      { value: 0, title: "All" },
      { value: 1, title: "Draft" },
      { value: 2, title: "Process" },
      { value: 3, title: "Rejected" }
    ],
    regionalOptions: [],
    branchOptions: [],

    menuStartDate: false,
    menuEndDate: false,
    menuDateUse: false,

    dStartDate: new Date().toISOString().substring(0, 10),
    dEndDate: new Date().toISOString().substring(0, 10),
    fStartDate: moment(new Date()).format("YYYY-MM-DD"),
    fEndDate: moment(new Date()).format("YYYY-MM-DD"),
    fStatus: {value: 0, title: "All"},
    fSearch: "",

    dDateUse: new Date().toISOString().substr(0, 10),
    xDateUse: moment(new Date()).format("YYYY-MM-DD"),
    warehouseOptions: [],
    xWarehouse: "",
    xNote: "",
    departmentOptions: [],
    xDepartment: "",
    xDescription: "",
    xTotalPrice: "",
    xIOID: 0,
    xNumber: "",
    xIODID: 0,
    xDescriptionDetail: "",
    xAmountRequest: 0,
    xEstimationPrice: 0,

    dialogRequest: false,
    dialogDetail: false,
    act: "new",
    errMessage: "",
    successMessage: "",
    alertError: false,
    alertSuccess: false,
    errors: [],
    loadingAutocomplete: false,
    dialogFormItem: false,
    itemList: [],
    selectedItem: {},
    search_item: "",
    xQty: "",
    xPrice: "",
    xIsCito: false,
    itemsTemp: [],
    erroritems: [],
    dialogErrors: false,
    item_units: [],
    selected_item_unit: {},
    search_item_unit: "",
    total_price: 0,
    errorsform: [],
    divisionOptions: [],
    selectedDivision: {},
    dialogItem: false,
    searchItem: "",
    loadingItem: false,
    itemCurrentPage: 1,
    items: [],
    selectedItems: [],
    itemTotalPage: 0,
    loadingSave: false,
    emptycheck: [],
    emptycheckvalue: [],

    dialogApprove: false,
    detailItemouts: [],
    dialogPreview: false,
    dialog_batchitem: false,
    list_batchitemform: {},
    form_batchitem: [],
    buffer_detailitem: {},
    approveLevelID: 0,
    dialogProcess: false,
    tempBatchNumber: {
      records: [],
      total: 0
    },
    dialogConfirm: false
  },
  mutations: {
    updateErrorsform(state, val) {
      state.errorsform = val
    },
    updateUser(state, val) {
      state.user = val
    },
    updateMainTable(state, val) {
      state.mainTable = val;
    },
    updateDetailTable(state, val) {
      state.detailTable = val;
    },
    updateCountMainTable(state, val) {
      state.countMainTable = val;
    },
    updateCountDetailTable(state, val) {
      state.countDetailTable = val;
    },
    updateMainTableLoadingStatus(state, val) {
      state.mainTableLoadingStatus = val;
    },
    updateDetailTableLoadingStatus(state, val) {
      state.detailTableLoadingStatus = val;
    },
    updateMainTableErrorMessage(state, val) {
      state.mainTableErrorMessage = val;
    },
    updateDetailTableErrorMessage(state, val) {
      state.detailTableErrorMessage = val;
    },
    updateMainTableCurrentPage(state, val) {
      state.mainTableCurrentPage = val;
    },
    updateMainTableLastId(state, val) {
      state.mainTableLastId = val;
    },

    updateSelectedMainTable(state, val) {
      state.selectedMainTable = val;
    },
    updateSelectedDetailTable(state, val) {
      state.selectedDetailTable = val;
    },

    updateRegionalOptions(state, val) {
      state.regionalOptions = val;
    },

    updateBranchOptions(state, val) {
      state.branchOptions = val;
    },

    updateMenuStartDate(state, val) {
      state.menuStartDate = val;
    },
    updateMenuEndDate(state, val) {
      state.menuEndDate = val;
    },
    updateMenuDateUse(state, val) {
      state.menuDateUse = val;
    },

    updateDStartDate(state, val) {
      state.dStartDate = val;
    },
    updateDEndDate(state, val) {
      state.dEndDate = val;
    },
    updateFStartDate(state, val) {
      state.fStartDate = val;
    },
    updateFEndDate(state, val) {
      state.fEndDate = val;
    },
    updateFStatus(state, val) {
      state.fStatus = val;
    },
    updateFSearch(state, val) {
      state.fSearch = val;
    },

    updateDDateUse(state, val) {
      state.dDateUse = val;
    },
    updateXDateUse(state, val) {
      state.xDateUse = val;
    },
    updateWarehouseOptions(state, val) {
      state.warehouseOptions = val
    },
    updateXWarehouse(state, val) {
      state.xWarehouse = val;
    },
    updateXNote(state, val) {
      state.xNote = val
    },
    updateDepartmentOptions(state, val) {
      state.departmentOptions = val
    },
    updateXDepartment(state, val) {
      state.xDepartment = val
    },
    updateXDescription(state, val) {
      state.xDescription = val;
    },
    updateXTotalPrice(state, val) {
      state.xTotalPrice = val;
    },
    updateXIOID(state, val) {
      state.xIOID = val;
    },
    updateXNumber(state, val) {
      state.xNumber = val;
    },
    updateXIODID(state, val) {
      state.xIODID = val;
    },
    updateXDescriptionDetail(state, val) {
      state.xDescriptionDetail = val;
    },
    updateXAmountRequest(state, val) {
      state.xAmountRequest = val;
    },
    updateXEstimationPrice(state, val) {
      state.xEstimationPrice = val;
    },

    updateDialogRequest(state, val) {
      state.dialogRequest = val;
    },
    updateDialogDetail(state, val) {
      state.dialogDetail = val;
    },
    updateAct(state, val) {
      state.act = val;
    },
    updateErrMessage(state, val) {
      state.errMessage = val;
    },
    updateSuccessMessage(state, val) {
      state.successMessage = val;
    },
    updateAlertError(state, val) {
      state.alertError = val;
    },
    updateAlertSuccess(state, val) {
      state.alertSuccess = val;
    },
    updateErrors(state, val) {
      state.errors = val;
    },
    updateLoadingAutocomplete(state, val) {
      state.loadingAutocomplete = val
    },
    updateDialogFormItem(state, val) {
      state.dialogFormItem = val
    },
    updateItemList(state, val) {
      state.itemList = val
    },
    updateSelectedItem(state, val) {
      state.selectedItem = val
    },
    update_search_item(state, val) {
      state.search_item = val
    },
    updateXQty(state, val) {
      state.xQty = val
    },
    updateXPrice(state, val) {
      state.xPrice = val
    },
    updateXIsCito(state, val) {
      state.xIsCito = val
    },
    updateItemsTemp(state, val) {
      state.itemsTemp = val
    },
    updateErroritems(state, val) {
      state.erroritems = val
    },
    updateDialogErrors(state, val) {
      state.dialogErrors = val
    },
    updateItemUnits(state, val) {
      state.item_units = val
    },
    updateSelectedItemUnit(state, val) {
      state.selected_item_unit = val
    },
    updateSearchItemUnit(state, val) {
      state.search_item_unit = val
    },
    updateTotalPrice(state, val) {
      state.total_price = val
    },
    updateDivisionOptions(state, val) {
      state.divisionOptions = val
    },
    updateSelectedDivision(state, val) {
      state.selectedDivision = val
    },
    updateDialogItem(state, val) {
      state.dialogItem = val
    },
    updateSearchItem(state, val) {
      state.searchItem = val
    },
    updateLoadingItem(state, val) {
      state.loadingItem = val
    },
    updateItemCurrentPage(state, val) {
      state.itemCurrentPage = val
    },
    updateItems(state, val) {
      state.items = val
    },
    updateSelectedItems(state, val) {
      state.selectedItems = val
    },
    updateItemTotalPage(state, val) {
      state.itemTotalPage = val
    },
    updateLoadingSave(state, val) {
      state.loadingSave = val
    },
    updateEmptycheck(state, val) {
      state.emptycheck = val
    },
    updateEmptycheckvalue(state, val) {
      state.emptycheckvalue = val
    },
    updateDialogApprove(state, val) {
      state.dialogApprove = val
    },
    updateDetailItemouts(state, val) {
      state.detailItemouts = val
    },
    updateDialogPreview(state, val) {
      state.dialogPreview = val
    },
    update_dialog_batchitem(state, val) {
      state.dialog_batchitem = val
    },
    update_list_batchitemform(state, data) {
        state.list_batchitemform = data
    },
    update_form_batchitem(state, data) {
        state.form_batchitem = data
    },
    update_buffer_detailitem(state, data) {
        state.buffer_detailitem = data
    },
    updateApproveLevelID(state, val) {
      state.approveLevelID = val;
    },
    updateDialogProcess(state, val) {
      state.dialogProcess = val
    },
    updateTempBatchNumber(state, val) {
      state.tempBatchNumber = val
    },
    updateDialogConfirm(state, val) {
      state.dialogConfirm = val
    }
  },
  actions: {
    async search(context) {
      context.commit("updateMainTableLoadingStatus", 1);

      try {
        var prm = {
          token: one_token(),
          current_page: context.state.mainTableCurrentPage,
          startDate: context.state.fStartDate,
          endDate: context.state.fEndDate,
          status: context.state.fStatus.title,
          search: context.state.fSearch,
          mainTableLastId: -1,
        };

        let response = await api.search(prm);
        if (response.status != "OK") {
          context.commit("updateMainTableLoadingStatus", 3);
          context.commit("updateMainTableErrorMessage", response.message);
        } else {
          context.commit("updateMainTableLoadingStatus", 2);
          context.commit("updateMainTableErrorMessage", "");
          let data = {
            records: response.data.records,
            total: response.data.totalPage,
          };

          context.commit("updateMainTable", data.records);
          context.commit("updateCountMainTable", data.total);

          if (context.state.mainTableLastId == -1) {
              if (response.data && response.data.records.length > 0) {
                  context.commit("updateSelectedMainTable", response.data.records[0])
              }
          } else {
              let idx = _.findIndex(resp.data.records, function (o) {
                  return o.T_ItemOutID == context.state.updateSelectedMainTable.T_ItemOutID
              });
              if (idx >= 0) {
                  context.commit("updateSelectedMainTable", resp.data.records[idx]);
              }
          }
        }
      } catch (e) {
        context.commit("updateMainTableLoadingStatus", 3);
        context.commit("updateMainTableErrorMessage", e.message);
      }
    },
    async searchDetail(context) {
      context.commit("updateDetailTableLoadingStatus", 1);

      try {
        var prm = {
          token: one_token(),
          IOID: context.state.selectedMainTable.T_ItemOutID,
        };

        let response = await api.searchDetail(prm);
        if (response.status != "OK") {
          context.commit("updateDetailTableLoadingStatus", 3);
          context.commit("updateDetailTableErrorMessage", response.message);
        } else {
          context.commit("updateDetailTableLoadingStatus", 2);
          context.commit("updateDetailTableErrorMessage", "");
          let data = {
            records: response.data.records,
            total: response.data.total,
          };

          context.commit("updateDetailTable", data.records);
          context.commit("updateCountDetailTable", data.total);
        }
      } catch (e) {
        context.commit("updateDetailTableLoadingStatus", 3);
        context.commit("updateDetailTableErrorMessage", e.message);
      }
    },
    
    async saveRequest(context, prm) {
      context.commit("updateLoadingSave", true);
      try {
        prm.token = one_token();

        let response = await api.saveRequest(prm);
        if (response.status !== "OK") {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", "");
          let data = {
            total: response.data.total,
          };

          if (data.total !== -1) {
            context.commit("updateErrors", []);
            context.commit("updateSelectedItems", []);
            context.commit("updateSelectedItem", {});
            context.commit("updateItems", []);
            context.commit("updateItemTotalPage", 0);
            context.commit("updateItemCurrentPage", 1);
            context.commit("updateAlertSuccess", true);
            context.commit("updateDialogRequest", false);
            var msg = "Berhasil simpan pengeluaran barang";
            context.commit("updateSuccessMessage", msg);
            context.dispatch("search");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateLoadingSave", false);
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },
    async updateRequest(context, prm) {
      try {
        prm.token = one_token();

        let response = await api.updateRequest(prm);
        if (response.status !== "OK") {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", "");
          let data = {
            total: response.data.total,
          };

          if (data.total !== -1) {
            context.commit("updateErrors", []);
            context.commit("updateAlertSuccess", true);
            context.commit("updateDialogRequest", false);
            var msg = "Berhasil update pengeluaran barang";
            context.commit("updateSuccessMessage", msg);
            context.dispatch("search");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateLoadingSave", false);
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },
    async deleteRequest(context, prm) {
      try {
        prm.token = one_token();

        let response = await api.deleteRequest(prm);
        if (response.status !== "OK") {
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateErrMessage", "");
          let data = {
            total: response.data.total,
          };

          if (data.total !== -1) {
            context.commit("updateErrors", []);
            context.commit("updateAlertSuccess", true);
            context.commit("updateDialogRequest", false);
            var msg = `Pengeluaran barang dengan kode ${prm.Number} berhasil dihapus`;
            context.commit("updateSuccessMessage", msg);
            context.dispatch("search");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },
    async saveDetail(context, prm) {
      try {
        prm.token = one_token();

        let response = await api.saveDetail(prm);
        if (response.status !== "OK") {
          context.commit("updateErrMessage", response.message);
        } else {
          context.commit("updateErrMessage", "");
          let data = {
            records: response.data.records,
            total: response.data.total,
          };

          if (data.total !== -1) {
            context.commit("updateErrors", []);
            context.commit("updateAlertSuccess", true);
            context.commit("updateDialogDetail", false);
            var msg = "Request baru " + prm.itemDescription + " sudah tersimpan";
            context.commit("updateSuccessMessage", msg);
            // context.dispatch("search");
            context.dispatch("searchDetail");
          } else {
            context.commit("updateErrors", response.data.errors[0].msg);
            context.commit("updateDialogErrors", true);
          }
        }
      } catch (e) {
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },
    async updateDetail(context, prm) {
      try {
        prm.token = one_token();

        let response = await api.updateDetail(prm);
        if (response.status !== "OK") {
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateErrMessage", "");
          let data = {
            records: response.data.records,
            total: response.data.total,
          };

          if (data.total !== -1) {
            context.commit("updateErrors", []);
            context.commit("updateAlertSuccess", true);
            context.commit("updateDialogDetail", false);
            var msg = "Perubahan Request item " + prm.itemDescription + " berhasil disimpan";
            context.commit("updateSuccessMessage", msg);
            // context.dispatch("search");
            context.dispatch("searchDetail");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },
    async deleteDetail(context, prm) {
      try {
        prm.token = one_token();

        let response = await api.deleteDetail(prm);
        if (response.status !== "OK") {
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateErrMessage", "");
          let data = {
            total: response.data.total,
          };

          if (data.total !== -1) {
            context.commit("updateErrors", []);
            context.commit("updateAlertSuccess", true);
            context.commit("updateDialogDetail", false);
            var msg = `Request [${prm.itemDescription}] sudah dihapus`;
            context.commit("updateSuccessMessage", msg);
            // context.dispatch("search");
            context.dispatch("searchDetail");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },

    async getWarehouse(context) {
      context.commit("updateLoadingAutocomplete", true)
      try {
        let prm = {}
        prm.regionalID = context.state.user.S_RegionalID
        prm.branchCode = context.state.user.M_BranchCode
        prm.token = one_token()
        let response = await api.getWarehouse(prm);
        if (response.status !== "OK") {
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
          context.commit("updateLoadingAutocomplete", false)
        } else {
          context.commit("updateLoadingAutocomplete", false)
          context.commit("updateErrMessage", "");
          let data = {
            records: response.data.records,
          };

            context.commit("updateWarehouseOptions", data.records);
            context.commit("updateXWarehouse", data.records[0]);
        }
      } catch (e) {
        context.commit("updateLoadingAutocomplete", true)
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },

    async getDepartment(context) {
      context.commit("updateLoadingAutocomplete", true)
      try {
        let prm = {}
        prm.token = one_token()
        let response = await api.getDepartment(prm);
        if (response.status !== "OK") {
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
          context.commit("updateLoadingAutocomplete", false)
        } else {
          context.commit("updateLoadingAutocomplete", false)
          context.commit("updateErrMessage", "");
          let data = {
            records: response.data.records,
          };

            context.commit("updateDepartmentOptions", data.records);
        }
      } catch (e) {
        context.commit("updateLoadingAutocomplete", true)
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },

    async searchItem(context, prm) {
        context.commit("updateLoadingAutocomplete", true)
        try {
            prm.token = one_token()
            let resp = await api.searchItem(prm)
            if (resp.status != "OK") {
                context.commit("updateLoadingAutocomplete", false)
                context.commit("updateErrMessage", resp.message);
                context.commit("updateAlertError", true);
            } else {
                context.commit("updateLoadingAutocomplete", false)
                context.commit("updateErrMessage", "");
                let data = {
                    records: resp.data.records
                }

                context.commit("updateItemList", data.records)
            }
        } catch (e) {
            context.commit("updateLoadingAutocomplete", true)
            context.commit("updateErrMessage", e.message);
            context.commit("updateAlertError", true);
        }
    },

    async getUnit(context, prm) {
        context.commit("updateLoadingAutocomplete", true)
        try {
          prm.token = one_token()
            let resp = await api.getUnit(prm)
            if (resp.status != "OK") {
                context.commit("updateLoadingAutocomplete", false)
                context.commit("updateErrMessage", resp.message);
                context.commit("updateAlertError", true);
            } else {
                context.commit("updateLoadingAutocomplete", false)
                context.commit("updateErrMessage", "");
                let data = {
                    records: resp.data.records
                }

                context.commit("updateItemUnits", data.records)
            }
        } catch (e) {
            context.commit("updateLoadingAutocomplete", true)
            context.commit("updateErrMessage", e.message);
            context.commit("updateAlertError", true);
        }
    },

    async orderConfirm(context, prm) {
      try {
        prm.token = one_token();

        let response = await api.orderConfirm(prm);
        if (response.status !== "OK") {
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateErrMessage", "");
          let data = {
            total: response.data.total,
          };

          if (data.total !== -1) {
            context.commit("updateErrors", []);
            context.commit("updateAlertSuccess", true);
            context.commit("updateDialogDetail", false);
            context.dispatch("search");
            context.dispatch("searchDetail");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },

    async getDivisionByUser(context, prm) {
      context.commit("updateLoadingAutocomplete", true)
      try {
        prm.token = one_token()
        prm.userId = context.state.user.M_UserID
        let response = await api.getDivisionByUser(prm);
        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("updateErrMessage", "");
          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 getItemRequest(context, prm) {
      context.commit("updateLoadingItem", true)
      try {
        prm.token = one_token()
        prm.currentPage = context.state.itemCurrentPage;
        let response = await api.getItemRequest(prm);
        if (response.status != "OK") {
          context.commit("updateLoadingItem", false)
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingItem", false)
          context.commit("updateErrMessage", "");
          context.commit("updateItems", response.data.records);
          context.commit("updateItemTotalPage", response.data.total);
        }
      } catch (e) {
          context.commit("updateLoadingItem", false)
          context.commit("updateErrMessage", e.message);
          context.commit("updateAlertError", true);
      }
    },

    async getDetailItemOut(context, prm) {
      context.commit("updateLoadingItem", true)
      try {
        prm.token = one_token()
        let response = await api.getDetailItemOut(prm);
        if (response.status != "OK") {
          context.commit("updateLoadingItem", false)
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingItem", false)
          context.commit("updateErrMessage", "");
          context.commit("updateSelectedItems", response.data.records);
        }
      } catch (e) {
          context.commit("updateLoadingItem", false)
          context.commit("updateErrMessage", e.message);
          context.commit("updateAlertError", true);
      }
    },

    async getItemOuts(context, prm) {
      context.commit("updateLoadingItem", true)
      try {
        prm.token = one_token()
        let response = await api.getItemOuts(prm);
        if (response.status != "OK") {
          context.commit("updateLoadingItem", false)
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingItem", false)
          context.commit("updateErrMessage", "");
          context.commit("updateDetailItemouts", response.data.records);
        }
      } catch (e) {
          context.commit("updateLoadingItem", false)
          context.commit("updateErrMessage", e.message);
          context.commit("updateAlertError", true);
      }
    },

    async confirmIO(context, prm) {
      context.commit("updateLoadingSave", true);
      try {
        prm.token = one_token();

        let response = await api.confirmIO(prm);
        if (response.status !== "OK") {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", "");
          let data = {
            total: response.data.total,
          };

          if (data.total !== -1) {
            context.commit("updateErrors", []);
            context.commit("updateAlertSuccess", true);
            context.commit("updateDialogConfirm", false);
            var msg = "Berhasil konfirmasi pengeluaran barang";
            context.commit("updateSuccessMessage", msg);
            context.dispatch("search");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateLoadingSave", false);
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },

    async approveIO(context, prm) {
      context.commit("updateLoadingSave", true);
      try {
        prm.token = one_token();

        let response = await api.approveIO(prm);
        if (response.status !== "OK") {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", "");
          let data = {
            total: response.data.total,
          };

          if (data.total !== -1) {
            context.commit("updateErrors", []);
            context.commit("updateAlertSuccess", true);
            context.commit("updateDialogApprove", false);
            var msg = "Berhasil APPROVE pengeluaran barang";
            context.commit("updateSuccessMessage", msg);
            context.dispatch("search");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateLoadingSave", false);
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },

    async processIO(context, prm) {
      context.commit("updateLoadingSave", true);
      try {
        prm.token = one_token();

        let response = await api.processIO(prm);
        if (response.status !== "OK") {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", "");
          let data = {
            total: response.data.total,
          };

          if (data.total !== -1) {
            context.commit("updateErrors", []);
            context.commit("updateAlertSuccess", true);
            context.commit("updateDialogProcess", false);
            var msg = "Berhasil Proses pengeluaran barang";
            context.commit("updateSuccessMessage", msg);
            context.dispatch("search");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateLoadingSave", false);
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },

    async rejectRequest(context, prm) {
      context.commit("updateLoadingSave", true);
      try {
        prm.token = one_token();

        let response = await api.rejectRequest(prm);
        if (response.status !== "OK") {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", response.message);
          context.commit("updateAlertError", true);
        } else {
          context.commit("updateLoadingSave", false);
          context.commit("updateErrMessage", "");
          let data = {
            total: response.data.total,
          };

          if (data.total !== -1) {
            context.commit("updateErrors", []);
            context.commit("updateAlertSuccess", true);
            context.commit("updateDialogApprove", false);
            var msg = "Berhasil REJECT pengeluaran barang";
            context.commit("updateSuccessMessage", msg);
            context.dispatch("search");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateLoadingSave", false);
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },

    async getBatchItemDetail(context, params) {
        try {
            params.token = one_token()
            params.regionalid = context.state.user.S_RegionalID
            params.branchid = context.state.user.M_BranchID

            let resp = await api.getItemBatchListing(params)
            if (resp.status != 'OK') {
                context.commit("updateErrMessage", response.message);
                context.commit("updateAlertError", true);
            } else {
                context.commit("updateErrMessage", "");
                context.commit("update_list_batchitemform", resp.data)

                let newBatchNumber = resp.data.records;
                let updateBatchNumber = context.state.tempBatchNumber.records
                    // console.log('before updateBatchNumber module', updateBatchNumber)
                    // console.log('before recordIndex module', newBatchNumber)
                updateBatchNumber.forEach(bn => {
                    let recordIndex = newBatchNumber.findIndex(record => 
                        record.StockBatchNo === bn.StockBatchNo &&
                        record.StockItemID === bn.StockItemID &&
                        record.StockItemUnitID === bn.StockItemUnitID

                    );

                    // console.log('newBatchNumber module', newBatchNumber)
                    // console.log('recordIndex module', recordIndex)

                    if (recordIndex !== -1) {
                      let updatestock = updateBatchNumber[recordIndex].StockQty
                      newBatchNumber[recordIndex].StockQty = String(updatestock)

                        // Atau hapus record jika StockQty menjadi 0
                        // if (stok <= 0) {
                        //     newBatchNumber.splice(recordIndex, 1);
                        // }

                    }
                });

                let newBatch = {
                    records: newBatchNumber,
                    total: newBatchNumber.length
                };
                context.commit("update_list_batchitemform", newBatch)
            }
        } catch (error) {
            context.commit("updateErrMessage", e.message);
            context.commit("updateAlertError", true);
        }
    },

    async getlevel(context) {
      context.commit("updateMainTableLoadingStatus", 1);

      try {
        var payload = {
          token: one_token()
        };

        let resp = await api.getlevel(payload);
        if (resp.status != "OK") {
          context.commit("updateMainTableLoadingStatus", 3);
          context.commit("updateMainTableErrorMessage", resp.message);
        } else {
          context.commit("updateMainTableLoadingStatus", 2);
          context.commit("updateMainTableErrorMessage", "");
          let data = {
            records: resp.data.records,
            total: resp.data.total,
          };

          // context.commit("updateLevelName", data.records[0].M_ApproveLevelName);
          context.commit("updateApproveLevelID", data.records[0].M_ApproveLevelID);
        }
      } catch (e) {
        context.commit("updateMainTableLoadingStatus", 3);
        context.commit("updateMainTableErrorMessage", e.message);
      }
    }
  },
};

