<template>
  <div>
  <v-layout row justify-center>
    <v-dialog v-model="dialogRequest" persistent max-width="75%">
      <v-card>
        <v-card-title class="headline grey lighten-2" primary-title>
          FORM PENGELUARAN BARANG
        </v-card-title>
        <v-card-text class="pt-2 pb-0">
          <v-form ref="formRequest" v-model="validationForm" lazy-validtion>
            <v-layout row>
              <v-flex xs6 pa-2>
                <v-menu
                  v-model="menuDateUse"
                  :close-on-content-click="false"
                  transition="scale-transition"
                  :nudge-right="40"
                  lazy
                  offset-y
                  full-width
                  max-width="290px"
                  min-width="290px"
                >
                  <template v-slot:activator="{ on }">
                    <v-text-field
                      v-model="dateUseFormatted"
                      label="Tanggal Transaksi"
                      readonly
                      v-on="on"
                      @blur="dDateUse = deFormatedDate(dateUseFormatted)"
                    ></v-text-field>
                  </template>
                  <v-date-picker
                    no-title
                    v-model="xDateUse"
                    @input="menuDateUse = false"
                  ></v-date-picker>
                </v-menu>
              </v-flex>
              <v-flex xs6 pa-2>
                <v-autocomplete
                  v-model="xWarehouse"
                  label="Gudang"
                  menu-icon="mdi-chevron-down"
                  :items="warehouseOptions"
                  item-text="WarehouseName"
                  item-value="WarehouseID"
                  :rules="warehouseRules"
                  required
                ></v-autocomplete>
              </v-flex>
              <v-flex xs6 pa-2>
                <v-autocomplete
                  v-model="selectedDivision"
                  label="Divisi"
                  menu-icon="mdi-chevron-down"
                  :items="divisionOptions"
                  item-text="DivisionName"
                  item-value="DivisionID"
                  :rules="divisionRules"
                  required
                ></v-autocomplete>
              </v-flex>
              <v-flex pa-2 xs6>
                <v-text-field
                  v-model="xNote"
                  label="Catatan"
                ></v-text-field>
              </v-flex>
            </v-layout>
          </v-form>

          <v-layout row>
            <v-flex pa-2 pl-0 xs12>
              <v-btn v-if="dialogItem == false" color="primary" @click="dialogItem = true">Pilih Item</v-btn>
              <v-btn v-if="dialogItem == true" color="primary" @click="dialogItem = false">Tutup Pilih Item</v-btn>
            </v-flex>
          </v-layout>

          <div v-if="dialogItem == true">
          <v-card class="mt-2">
            <v-layout row>
                <v-flex class="mt-2" pa-2 pb-0 xs3>
                  <v-text-field
                    v-model="searchItem"
                    label="Cari..."
                    placeholder="Ketikkan item"
                    style="max-width: 250px"
                    hide-details
                  ></v-text-field>
                </v-flex>
                <v-flex class="mt-2" pa-2 pb-0 xs2>
                  <v-btn
                    dark
                    color="success"
                    style="min-width: 40px; height: 40px; margin: 0"
                    @click="itemSearch()"
                  >
                    <v-icon>search</v-icon>
                  </v-btn>
                </v-flex>
            </v-layout>
            <v-layout row >
              <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
                <v-data-table
                  :headers="headers"
                  :items="items"
                  :loading="loadingItem"
                  hide-actions
                  class="elevation-1"
                >
                  <template slot="items" slot-scope="props">
                    <td
                      class="text-xs-left pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                      <div
                        style="
                          display: flex;
                          flex-direction: column;
                          align-items: center;
                        "
                      >
                        {{ props.item.rioNumber }}
                      </div>
                    </td>
                    <td
                      class="text-xs-left pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                      <div
                        style="
                          display: flex;
                          flex-direction: column;
                          align-items: center;
                        "
                      >
                        {{ props.item.itemCode }}
                        <v-chip small style="border-radius: 5px; flex-grow: 0">
                          {{ props.item.itemDesc }}
                        </v-chip>
                      </div>
                    </td>
                    <td
                      class="text-xs-center pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                    {{ props.item.unitName }}
                    </td>
                    <td
                      class="text-xs-center pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                    {{ props.item.StockQty }}
                    </td>
                    <td
                      class="text-xs-center pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                    {{ props.item.rioDQty }}
                    </td>
                    <td
                      class="text-xs-center pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                      <v-btn  v-if="checkSelected(props.item) == false"style="min-width: 35px; height: 35px; margin: 0" small color="success" @click="addItem(props.item)"><v-icon small>check</v-icon></v-btn>
                    </td>
                  </template>
                </v-data-table>
              </v-flex>
            </v-layout>
            <v-divider></v-divider>
            <v-layout row>
              <v-flex xs6>
                <v-pagination
                  style="margin-top: 10px; margin-bottom: 10px"
                  v-model="itemCurrentPage"
                  :length="itemTotalPage"
                  :total-visible="7"
                ></v-pagination>
              </v-flex>
              <v-flex class="pt-2 text-xs-right" xs6>
                <v-btn color="primary" @click="dialogItem = false">Tutup Pilih Item</v-btn>
              </v-flex>
            </v-layout>

          </v-card>
          </div>
          <v-divider></v-divider>

          <v-card elevation="0" flat class=" mt-2">
            <v-layout row style="max-height: 600px; overflow: auto">
              <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
                <v-data-table
                  :headers="headersItems"
                  :items="selectedItems"
                  hide-actions
                  class="elevation-1"
                >
                  <template slot="items" slot-scope="props">
                    <td
                      class="text-xs-left pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                      <div
                        style="
                          display: flex;
                          flex-direction: column;
                          align-items: center;
                        "
                      >
                        {{ props.item.rioNumber }}
                        <!-- <span v-if="props.item.ioDetailConfirm == 'Y'">
                          <v-tooltip bottom>
                              <template v-slot:activator="{ on, attrs }">
                                  <v-icon v-bind="attrs" v-on="on" class="ml-1" color="blue" small>check_circle</v-icon>
                              </template>
                              <span>Sudah di konfirmasi</span>
                          </v-tooltip>
                        </span> -->
                      </div>
                    </td>
                    <td
                      class="text-xs-left pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                      <div
                        style="
                          display: flex;
                          flex-direction: column;
                          align-items: center;
                        "
                      >
                        {{ props.item.itemCode }}
                        <v-chip small style="border-radius: 5px; flex-grow: 0">
                          {{ props.item.itemDesc }}
                        </v-chip>
                      </div>
                    </td>
                    <td
                      class="text-xs-center pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                      <p v-for="obj in props.item.ItemRequest" class="body-1 mb-0">
                          Batch: {{ obj.StockBatchNo }}, Jumlah: {{ obj.QtyReq }}, {{ obj.WarehouseName }}
                      </p>
                    </td>
                    <td
                      class="text-xs-center pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                      {{ props.item.StockQty }}
                    </td>
                    <td
                      class="text-xs-center pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                      {{ props.item.rioDQty }}
                    </td>
                    <td
                      class="text-xs-center pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                      @blur="validateReceiveQty(props.item)"
                    >
                      {{ getRemaining(props.item) }} / {{ props.item.rioDReceiveQty }} {{ props.item.unitName }}
                      <p v-show="emptycheck.includes(props.item.rioDID)" style="color: red;" class="ma-0 pa-0">Jumlah melebihi request qty</p>
                      <p v-show="emptycheckvalue.includes(props.item.rioDID)" style="color: red;" class="ma-0 pa-0">Jumlah item harus diisi</p>
                    </td>
                    <!-- <td
                      class="text-xs-center pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                      <v-text-field  
                        v-model=""
                        type="number"
                        @input="validateReceiveQty(props.item)"
                        ></v-text-field>
                        <p v-show="emptycheck.includes(props.item.rioDID)" style="color: red;" class="ma-0 pa-0">Jumlah melebihi request qty</p>
                        <p v-show="emptycheckvalue.includes(props.item.rioDID)" style="color: red;" class="ma-0 pa-0">Jumlah harus diisi</p>
                    </td> -->
                    <td
                      class="text-xs-center pa-2"
                      v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                      @click="selectMe(props.item)"
                    >
                      <v-btn
                        style="min-width: 35px; height: 35px; margin: 0;"
                        small
                        color="orange" title="Pilih Batch Item"
                        @click="updateBatchNo(props.item)"
                      >
                        <v-icon small color="white">edit</v-icon>
                      </v-btn>
                      <v-btn style="min-width: 35px; height: 35px; margin: 0" small color="error" dark @click="deleteItem(props.item)"><v-icon small>close</v-icon></v-btn>
                      
                    </td>
                  </template>
                </v-data-table>
              </v-flex>
            </v-layout>
          </v-card>

        </v-card-text>
        <v-card-actions>
          <v-btn
            v-if="act === 'edit'"
            color="blue"
            :disabled="loadingSave"
            dark
            @click="saveConfirm()"
            >Konfirmasi</v-btn
          >
          <v-spacer></v-spacer>
          <v-btn color="error" flat @click="closeDialogRequest()">
            Tutup
          </v-btn>
          <v-btn
            v-if="act === 'new'"
            color="primary"
            :disabled="loadingSave"
            dark
            @click="saveRequest()"
            >Simpan</v-btn
          >
          <v-btn
            v-if="act === 'edit'"
            color="primary"
            :disabled="loadingSave"
            dark
            @click="updateRequest()"
            >Simpan Perubahan</v-btn
          >
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-layout>
  <one-dialog-batch></one-dialog-batch>
  </div>
</template>

<script>
module.exports = {
  name: "AddPurchaseRequestDialog",
  components: {
      "one-dialog-batch": httpVueLoader("./dialogBatch.vue")
  },
  data() {
    return {
      warehouseRules: [(v) => !!v || "Gudang harus diisi"],
      divisionRules: [(v) => !!v || "Division harus diisi"],
      validationForm: false,
      headers: [
        {
          text: "NO. RIO",
          align: "center",
          sortable: false,
          value: "itemName",
          width: "20%",
          class: "success lighten-3 white--text",
        },
        {
          text: "ITEM",
          align: "center",
          sortable: false,
          value: "itemName",
          width: "35%",
          class: "success lighten-3 white--text",
        },
        {
          text: "SATUAN",
          align: "center",
          sortable: false,
          value: "unitName",
          width: "20%",
          class: "success lighten-3 white--text",
        },
        {
          text: "STOCK",
          align: "center",
          sortable: false,
          value: "itemName",
          width: "10%",
          class: "success lighten-3 white--text",
        },
        {
          text: "REQUEST QTY",
          align: "center",
          sortable: false,
          value: "itemName",
          width: "15%",
          class: "success lighten-3 white--text",
        },
        {
          text: "AKSI",
          align: "center",
          sortable: false,
          value: "action",
          width: "10%",
          class: "success lighten-3 white--text",
        },
      ],
      headersItems: [
        {
            text: "NO. RIO",
            align: "center",
            sortable: false,
            value: "action",
            width: "10%",
            class: "pa-2 pl-2 blue lighten-3 white--text",
        },
        {
            text: "ITEM",
            align: "center",
            sortable: false,
            value: "action",
            width: "20%",
            class: "pa-2 pl-2 blue lighten-3 white--text",
        },
        {
            text: "ITEM GUDANG",
            align: "center",
            sortable: false,
            value: "action",
            width: "20%",
            class: "pa-2 pl-2 blue lighten-3 white--text",
        },
        {
            text: "STOCK",
            align: "center",
            sortable: false,
            value: "action",
            width: "10%",
            class: "pa-2 pl-2 blue lighten-3 white--text",
        },
        {
            text: "REQ QTY",
            align: "center",
            sortable: false,
            value: "action",
            width: "10%",
            class: "pa-2 pl-2 blue lighten-3 white--text",
        },
        {
            text: "JUMLAH (SISA REQUEST/ITEM OUT)",
            align: "center",
            sortable: false,
            value: "action",
            width: "20%",
            class: "pa-2 pl-2 blue lighten-3 white--text",
        },
        {
            text: "AKSI",
            align: "center",
            sortable: false,
            value: "action",
            width: "10%",
            class: "pa-2 pl-2 blue lighten-3 white--text",
        }
      ]
    };
  },
  mounted() {

  },
  computed: {
    user() {
      return this.$store.state.requester.user;
    },
    dialogRequest: {
      get() {
        return this.$store.state.requester.dialogRequest;
      },
      set(val) {
        this.$store.commit("requester/updateDialogRequest", val);
      },
    },
    menuDateUse: {
      get() {
        return this.$store.state.requester.menuDateUse;
      },
      set(val) {
        this.$store.commit("requester/updateMenuDateUse", val);
      },
    },
    dateUseFormatted() {
      return this.formatDate(this.xDateUse);
    },
    dDateUse: {
      get() {
        return this.$store.state.requester.dDateUse;
      },
      set(val) {
        this.$store.commit("requester/updateDDateUse", val);
      },
    },
    xDateUse: {
      get() {
        return this.$store.state.requester.xDateUse;
      },
      set(val) {
        this.$store.commit("requester/updateXDateUse", val);
      },
    },
    xNote: {
      get() {
        return this.$store.state.requester.xNote;
      },
      set(val) {
        this.$store.commit("requester/updateXNote", val);
      },
    },
    xWarehouse: {
      get() {
        return this.$store.state.requester.xWarehouse;
      },
      set(val) {
        this.$store.commit("requester/updateXWarehouse", val);
        this.$store.dispatch("requester/getItemRequest", {
          search: this.searchItem,
          warehouseID: this.xWarehouse.WarehouseID ? this.xWarehouse.WarehouseID : this.xWarehouse,
          divisionID: this.selectedDivision.DivisionID ? this.selectedDivision.DivisionID : this.selectedDivision
        });
      },
    },
    xDepartment: {
      get() {
        return this.$store.state.requester.xDepartment;
      },
      set(val) {
        this.$store.commit("requester/updateXDepartment", val);
      },
    },
    warehouseOptions() {
      return this.$store.state.requester.warehouseOptions;
    },
    departmentOptions() {
      return this.$store.state.requester.departmentOptions;
    },
    regionalOptions() {
      return this.$store.state.requester.regionalOptions;
    },
    branchOptions() {
      return this.$store.state.requester.branchOptions;
    },
    xTotalPrice: {
      get() {
        return this.$store.state.requester.xTotalPrice;
      },
      set(val) {
        this.$store.commit("requester/updateXTotalPrice", val);
      },
    },
    xIOID() {
      return this.$store.state.requester.xIOID;
    },
    act() {
      return this.$store.state.requester.act;
    },
    divisionOptions() {
      return this.$store.state.requester.divisionOptions;
    },
    selectedDivision: {
      get() {
        return this.$store.state.requester.selectedDivision;
      },
      set(val) {
        this.$store.commit("requester/updateSelectedDivision", val);
        this.$store.dispatch("requester/getItemRequest", {
          search: this.searchItem,
          warehouseID: this.xWarehouse.WarehouseID ? this.xWarehouse.WarehouseID : this.xWarehouse,
          divisionID: this.selectedDivision.DivisionID ? this.selectedDivision.DivisionID : this.selectedDivision
        });
      },
    },
    dialogItem: {
      get() {
        return this.$store.state.requester.dialogItem;
      },
      set(val) {
        this.$store.commit("requester/updateDialogItem", val);
      },
    },
    searchItem: {
      get() {
        return this.$store.state.requester.searchItem;
      },
      set(val) {
        this.$store.commit("requester/updateSearchItem", val);
      },
    },
    loadingItem: {
      get() {
        return this.$store.state.requester.loadingItem;
      },
      set(val) {
        this.$store.commit("requester/updateLoadingItem", val);
      },
    },
    items() {
      return this.$store.state.requester.items
    },
    itemTotalPage: {
      get() {
        return this.$store.state.requester.itemTotalPage;
      },
      set(val) {
        this.$store.commit("requester/updateItemTotalPage", val);
      },
    },
    itemCurrentPage: {
      get() {
        return this.$store.state.requester.itemCurrentPage;
      },
      set(val) {
        this.$store.commit("requester/updateItemCurrentPage", val);
        this.$store.dispatch("requester/getItemRequest", {
          search: this.searchItem,
          warehouseID: this.xWarehouse.WarehouseID ? this.xWarehouse.WarehouseID : "",
          divisionID: this.selectedDivision.DivisionID ? this.selectedDivision.DivisionID : ""
        });
      },
    },
    selectedItems: {
      get() {
        return this.$store.state.requester.selectedItems;
      },
      set(val) {
        this.$store.commit("requester/updateSelectedItems", val);
      }
    },
    loadingSave: {
      get() {
        return this.$store.state.requester.loadingSave;
      },
      set(val) {
        this.$store.commit("requester/updateLoadingSave", val);
      }
    },
    emptycheck: {
      get() {
        return this.$store.state.requester.emptycheck;
      },
      set(val) {
        this.$store.commit("requester/updateEmptycheck", val);
      }
    },
    emptycheckvalue: {
      get() {
        return this.$store.state.requester.emptycheckvalue;
      },
      set(val) {
        this.$store.commit("requester/updateEmptycheckvalue", val);
      }
    },
  },
  methods: {
    isSelected(p) {
      return (
        p.rioDID ==
        this.$store.state.requester.selectedItem
          .rioDID
      );
    },
    selectMe(sc) {
      this.$store.commit("requester/updateSelectedItem", sc);
    },
    formatDate(date) {
      if (!date) return null;

      const [year, month, day] = date.split("-");
      return `${day}-${month}-${year}`;
    },
    deFormatedDate(date) {
      if (!date) return null;

      const [day, month, year] = date.split("-");
      return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
    },
    closeDialogRequest() {
      this.$store.commit("requester/updateEmptycheck", []);
      this.$store.commit("requester/updateEmptycheckvalue", []);
      this.$store.commit(
        "requester/updateXDateUse",
        moment(new Date()).format("YYYY-MM-DD")
      );
      this.$store.commit("requester/updateXWarehouse", "");
      this.$store.commit("requester/updateXDepartment", "");
      this.$refs.formRequest.resetValidation();
      this.$store.commit("requester/updateDialogRequest", false);
      this.$store.commit("requester/updateTempBatchNumber", {
        records: [],
        total: 0
      });
    },
    saveRequest() {
      let empty = [];
      let emptycheckvalue = [];
      let tempSelectedItems = this.selectedItems;

      if (tempSelectedItems.length == 0) {
        this.$store.commit("requester/updateErrMessage", `[Error] data item belum dipilih`);
        this.$store.commit("requester/updateAlertError", true);
        return;
      }

      tempSelectedItems.forEach(e => {
        let totalRequestQty = parseInt(e.rioDQty) || 0;
        // let alreadyReceivedQty = parseInt(e.rioDReceiveQtyBeforeEdit) || 0;
        let currentInputQty = parseInt(e.rioDReceiveQty) || 0;

        // let remainingQty = totalRequestQty - alreadyReceivedQty; // sisa yg boleh diinput

        // Kalau input user lebih besar dari sisa yang seharusnya
        if (currentInputQty > totalRequestQty) {
          empty.push(e.rioDID);
          return;
        }

        // Kalau input user kosong atau 0
        if (currentInputQty <= 0) {
          emptycheckvalue.push(e.rioDID);
          return;
        }
      });

      if (empty.length === 0 && emptycheckvalue.length === 0) {
        this.emptycheck = empty;
        this.emptycheckvalue = emptycheckvalue;
        this.$store.commit("requester/updateLoadingSave", true);

        let prm = {
          date: this.xDateUse,
          note: this.xNote,
          warehouseID: this.xWarehouse.WarehouseID ? this.xWarehouse.WarehouseID : this.xWarehouse,
          divisionID: this.selectedDivision.DivisionID ? this.selectedDivision.DivisionID : this.selectedDivision,
          items: this.selectedItems
        };

        // console.log('prm', prm)
        this.$store.dispatch("requester/saveRequest", prm);
      } else {
        this.emptycheck = empty;
        this.emptycheckvalue = emptycheckvalue;
      }
    },
    updateRequest() {
      let empty = [];
      let emptycheckvalue = [];
      let tempSelectedItems = this.selectedItems;

      if (tempSelectedItems.length == 0) {
        this.$store.commit("requester/updateErrMessage", `[Error] data item belum dipilih`);
        this.$store.commit("requester/updateAlertError", true);
        return;
      }

      // Mengecek jika jumlah yang diterima tidak melebihi jumlah yang diminta dan jika jumlah yang diterima adalah 0
      tempSelectedItems.forEach(e => {
        let qty = parseInt(e.rioDQty);  // Jumlah yang diminta
        let qtyReceive = parseInt(e.rioDReceiveQty);  // Jumlah yang diterima

        if (qtyReceive > qty) {
          empty.push(e.rioDID);  // Menandai item jika qtyReceive melebihi qty yang diminta
          return;
        }
        if (qtyReceive === 0) {
          emptycheckvalue.push(e.rioDID);  // Menandai item jika qtyReceive adalah 0
          return;
        }
      });

      // Jika tidak ada item yang memiliki masalah pada qtyReceive
      if (empty.length === 0 && emptycheckvalue.length === 0) {
        this.emptycheck = empty;  // Menyimpan item yang qtyReceive-nya melebihi qty
        this.emptycheckvalue = emptycheckvalue;  // Menyimpan item yang qtyReceive-nya 0

        this.$store.commit("requester/updateLoadingSave", true);
        let prm = {
          date: this.xDateUse,
          note: this.xNote,
          warehouseID: this.xWarehouse.WarehouseID ? this.xWarehouse.WarehouseID : this.xWarehouse,
          divisionID: this.selectedDivision.DivisionID ? this.selectedDivision.DivisionID : this.selectedDivision,
          IOID: this.xIOID,
          items: this.selectedItems
        };

        // console.log(prm);
        this.$store.dispatch("requester/updateRequest", prm);
      } else {
        this.emptycheck = empty;
        this.emptycheckvalue = emptycheckvalue;
      }
    },
    saveConfirm() {
        this.$store.commit("requester/updateLoadingSave", true);
        let prm = {
            ioID: this.xIOID,
        }
        this.$store.dispatch("requester/confirmIO", prm);
    },
    itemSearch() {
      this.$store.dispatch("requester/getItemRequest", {
          search: this.searchItem,
          warehouseID: this.xWarehouse.WarehouseID ? this.xWarehouse.WarehouseID : "",
          divisionID: this.selectedDivision
      });
    },
    checkSelected(item) {
      let selectedItems = this.selectedItems;
      let rtn = false
      if(selectedItems.length == 0) {
        // console.log(item.rioDID,"selectedItems.length == 0");
        rtn = false;
      }
      selectedItems.forEach(itemloop => {
        if(itemloop.rioDID == item.rioDID) {
          // console.log(item.rioDID,"itemloop.rioDID == item.rioDID");
          rtn = true;
        }
      });
      // console.log(item.rioDID,"return false");
      return rtn;
    },
    addItem(item) {
      let selectedItems = this.selectedItems;
      let index = selectedItems.findIndex(itemloop => itemloop.rioDID == item.rioDID);
      if(index == -1) {
        item.rioDReceiveQtyBeforeEdit = parseInt(item.rioDReceiveQty) || 0;
        selectedItems.push(item);
      }
      
      this.$store.commit("requester/updateSelectedItems", selectedItems);
    },
    deleteItem(item) {
      let selectedItems = this.selectedItems;
      let index = selectedItems.findIndex(itemloop => itemloop.rioDID == item.rioDID);
      if (index != -1) {
        selectedItems.splice(index, 1);
      }

      // Reset receiveQty ke nilai awal sebelum edit
      // item.rioDReceiveQty = item.rioDReceiveQtyBeforeEdit || 0;

      // Bersihkan warning
      this.emptycheck = this.emptycheck.filter(id => id !== item.rioDID);
      this.emptycheckvalue = this.emptycheckvalue.filter(id => id !== item.rioDID);

      // Commit perubahan
      this.$store.commit("requester/updateSelectedItems", selectedItems);
    },
    validateReceiveQtyolds(item) {
      let totalRequestQty = parseInt(item.rioDQty) || 0;
      let alreadyReceivedQty = parseInt(item.rioDReceiveQtyBeforeEdit) || 0;
      let inputReceiveQty = parseInt(item.rioDReceiveQty) || 0;

      // Hitung jumlah kumulatif
      // let cumulativeReceiveQty = alreadyReceivedQty + inputReceiveQty;

      if (inputReceiveQty > totalRequestQty) {
        // let allowedQty = totalRequestQty - alreadyReceivedQty; // Sisa yang boleh diterima
        // item.rioDReceiveQty = allowedQty; // Set input sesuai maksimal sisa
        if (!this.emptycheck.includes(item.rioDID)) {
          this.emptycheck.push(item.rioDID);
        }
      } else {
        this.emptycheck = this.emptycheck.filter(id => id !== item.rioDID);
      }

      // Kalau kosong atau 0, kasih warning juga
      if (inputReceiveQty <= 0) {
        if (!this.emptycheckvalue.includes(item.rioDID)) {
          this.emptycheckvalue.push(item.rioDID);
        }
      } else {
        this.emptycheckvalue = this.emptycheckvalue.filter(id => id !== item.rioDID);
      }
    },
    getRemaining(item) {
      const totalRequestQty = parseInt(item.rioDQty) || 0;
      const alreadyReceivedQty = parseInt(item.rioDReceiveQtyBeforeEdit) || 0;
      const currentInputQty = parseInt(item.rioDReceiveQty) || 0;

      return totalRequestQty - currentInputQty;
    },
    updateBatchNo(val) {
      let params = {
          itemid: val.rioDItemID,
          unitid: val.rioDItemUnitID,
          batchno: ""
      }
      this.$store.commit("requester/update_dialog_batchitem", true);
      this.$store.commit("requester/update_buffer_detailitem", val);
      this.$store.dispatch("requester/getBatchItemDetail", params);

      if (val.ItemRequest.length > 0) {
          this.$store.commit("requester/update_form_batchitem", val.ItemRequest)
      }
    }
  },
  watch: {

  }
};
</script>
