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

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

export default {
  namespaced: true,
  state: {
    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: "Pending" },
      { value: 3, title: "Approved" },
      { value: 4, title: "Rejected" },
      { value: 5, title: "Paid" },
      { value: 6, title: "Completed" },
    ],
    branchOptions: [],
    regionalOptions: [],

    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: 0,
    fSearch: "",

    dDateUse: new Date().toISOString().substring(0, 10),
    xDateUse: moment(new Date()).format("YYYY-MM-DD"),
    xRegional: "",
    xBranch: "",
    xDescription: "",
    xPRID: 0,
    xNumber: "",
    xPRDID: 0,
    xDescriptionDetail: "",
    xAmountRequest: 0,
    xEstimationPrice: 0,

    dialogRequest: false,
    dialogDetail: false,
    act: "new",
    errMessage: "",
    successMessage: "",
    alertError: false,
    alertSuccess: false,
    errors: [],
    total_price: 0,
    item_units: [],
    selected_item_unit: {},
    search_item_unit: "",
    loadingAutocomplete: false,
    dialog_form: false,
    show_progrees_upload: false,
    imageFiles: [],
    imagePreviews: [],
    cekFile: false,
    actAttach: "",

    category_direct: [],
    selected_category: {}
  },
  mutations: {
    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;
    },

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

    updateRegionalOptions(state, val) {
      state.regionalOptions = 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;
    },
    updateXRegional(state, val) {
      state.xRegional = val;
    },
    updateXBranch(state, val) {
      state.xBranch = val;
    },
    updateXDescription(state, val) {
      state.xDescription = val;
    },
    updateXPRID(state, val) {
      state.xPRID = val;
    },
    updateXNumber(state, val) {
      state.xNumber = val;
    },
    updateXPRDID(state, val) {
      state.xPRDID = 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;
    },
    updateTotalPrice(state, val) {
      state.total_price = val;
    },
    updateItemUnits(state, val) {
      state.item_units = val;
    },
    updateSelectedItemUnit(state, val) {
      state.selected_item_unit = val;
    },
    updateSearchItemUnit(state, val) {
      state.search_item_unit = val;
    },
    updateLoadingAutocomplete(state, val) {
      state.loadingAutocomplete = val;
    },
    update_dialog_form(state, val) {
      state.dialog_form = val;
    },
    update_show_progrees_upload(state, val) {
        state.show_progrees_upload = val
    },
    update_imageFiles(state, val) {
        state.imageFiles = val
    },
    update_imagePreviews(state, val) {
        state.imagePreviews = val
    },
    update_cekFile(state, val) {
        state.cekFile = val
    },
    update_actAttach(state, val) {
        state.actAttach = val
    },
    update_category_direct(state, val) {
      state.category_direct = val
    },
    update_selected_category(state, val) {
      state.selected_category = val
    }
  },
  actions: {
    async getCategoryPD(context) {
      context.commit("updateDetailTableLoadingStatus", 1);
      try {
        var params = {
          token: one_token(),
          name: ''
        }

        let resp = await api.getCategoryPD(params)
        if (resp.status != 'OK') {
          context.commit("updateDetailTableLoadingStatus", 3);
          context.commit("updateDetailTableErrorMessage", resp.message);
        } else {
          context.commit("updateDetailTableLoadingStatus", 2);
          context.commit("update_category_direct", resp.data)
        }

      } catch (error) {
        context.commit("updateDetailTableLoadingStatus", 3);
        context.commit("updateDetailTableErrorMessage", error.message);
      }
    },
    async search(context) {
      context.commit("updateMainTableLoadingStatus", 1);

      try {
        var url_string = window.location.href
        var url = new URL(url_string);
        var xdate = url.searchParams.get("date");
        var xsearch = url.searchParams.get("search");

        if (xsearch) {
          context.commit("updateFSearch", xsearch);
        }
        if (xdate) {
          context.commit("updateFStartDate", xdate);
          context.commit("updateFEndDate", xdate);
        }

        var payload = {
          token: one_token(),
          currentPage: context.state.mainTableCurrentPage,
          startDate: context.state.fStartDate,
          endDate: context.state.fEndDate,
          status: context.state.fStatus,
          search: context.state.fSearch,
          lastId: -1,
        };

        let response = await api.search(payload);
        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.total,
          };

          context.commit("updateMainTable", data.records);
          context.commit("updateCountMainTable", data.total);
          context.dispatch("system/getlistnotif", null, { root: true })
        }
      } catch (e) {
        context.commit("updateMainTableLoadingStatus", 3);
        context.commit("updateMainTableErrorMessage", e.message);
      }
    },
    async searchDetail(context) {
      context.commit("updateDetailTableLoadingStatus", 1);

      try {
        var payload = {
          token: one_token(),
          PRID: context.state.selectedMainTable.PurchaseRequestDirectID,
        };

        let response = await api.searchDetail(payload);
        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 regional(context) {
      let response = await api.getRegional({ token: one_token() });
      if (response.status === "OK") {
        let data = {
          records: response.data.records,
        };

        context.commit("updateRegionalOptions", data.records);
      }
    },
    async branch(context) {
      let response = await api.getBranch({ token: one_token() });
      if (response.status === "OK") {
        let data = {
          records: response.data.records,
        };

        context.commit("updateBranchOptions", data.records);
      }
    },
    async saveRequest(context, payload) {
      try {
        payload.token = one_token();

        let response = await api.saveRequest(payload);
        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("updateDialogRequest", false);
            var msg = `Purchase Request baru dengan kode ${data.records[0].PurchaseRequestDirectNumber} sudah tersimpan`;
            context.commit("updateSuccessMessage", msg);
            context.dispatch("search");
            context.commit("updateSelectedMainTable", data.records[0]);
            context.dispatch("searchDetail");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },
    async updateRequest(context, payload) {
      try {
        payload.token = one_token();

        let response = await api.updateRequest(payload);
        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("updateDialogRequest", false);
            var msg = `Perubahan Purchase Request dengan kode ${data.records[0].PurchaseRequestDirectNumber} sudah tersimpan`;
            context.commit("updateSuccessMessage", msg);
            context.dispatch("search");
            context.commit("updateSelectedMainTable", data.records[0]);
            context.dispatch("searchDetail");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },
    async deleteRequest(context, payload) {
      try {
        payload.token = one_token();

        let response = await api.deleteRequest(payload);
        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("updateDialogRequest", false);
            var msg = `Purchase Request dengan kode ${payload.PRNumber} sudah 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, payload) {
      try {
        payload.token = one_token();

        let response = await api.saveDetail(payload);
        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 ${payload.PRDDescription} sudah tersimpan`;
            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 updateDetail(context, payload) {
      try {
        payload.token = one_token();

        let response = await api.updateDetail(payload);
        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 sudah tersimpan";
            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, payload) {
      try {
        payload.token = one_token();

        let response = await api.deleteDetail(payload);
        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 = `Request [${payload.PRDDescriptionDetail}] 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 orderRequest(context, payload) {
      try {
        payload.token = one_token();

        let response = await api.orderRequest(payload);
        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);
            context.dispatch("search");
            context.commit("updateSelectedMainTable", data.records[0]);
            context.dispatch("searchDetail");
          } else {
            context.commit("updateErrors", response.data.errors);
          }
        }
      } catch (e) {
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },

    async getUnit(context, prm) {
        context.commit("updateLoadingAutocomplete", true)
        try {
            let resp = await api.getUnit(one_token(), prm)
            if (resp.status != "OK") {
                context.commit("updateLoadingAutocomplete", false)
                context.commit("updateErrMessage", response.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 saveFiles(context, payload) {
      try {
        // payload.token = one_token();

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

            context.commit("update_dialog_form", false);
            context.commit("update_imageFiles", []);
            context.commit("update_imagePreviews", []);
            context.commit("updateErrors", []);
            context.commit("updateAlertSuccess", true);
            var msg = "Upload file berhasil";
            context.commit("updateSuccessMessage", msg);
            context.dispatch("search");
            context.dispatch("searchDetail");
        }
      } catch (e) {
        context.commit("updateErrMessage", e.message);
        context.commit("updateAlertError", true);
      }
    },
  },
};
