<template>
  <v-layout row justify-center>
    <!-- Dialog Ganti Unit -->
    <v-dialog v-model="dialogUnit" persistent max-width="25%">
      <v-card>
        <v-card-title class="title grey lighten-2" primary-title>
          Ganti Satuan {{ selectedItem.itemDesc ? selectedItem.itemDesc : "" }}
        </v-card-title>
        <v-card-text>
          <v-layout row>
            <v-flex xs12>
              <v-select :loading="loadingUnit" v-model="selectedUnit" return-object :items="unitOptions"
                label="Pilih Satuan" item-text="unitName"></v-select>
            </v-flex>
          </v-layout>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="error" flat @click="dialogUnit = false">
            Tutup
          </v-btn>
          <v-btn color="primary" flat @click="saveUnit()">Ganti</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Dialog Induk Form Request -->
    <v-dialog v-model="dialogRequest" persistent max-width="75%">
      <v-card>
        <v-card-title class="headline grey lighten-2" primary-title>
          FORM STOCK REQUEST
        </v-card-title>
        <v-card-text class="pt-0 pb-0">

          <v-layout row>
            <v-flex pa-2 xs6>
              <v-menu v-model="menuDateUse" :close-on-content-click="false" transition="scale-transition"
                :nudge-right="40" lazy :disabled="act == 'preview'" offset-y full-width max-width="290px"
                min-width="290px">
                <template v-slot:activator="{ on }">
                  <v-text-field :value="dateUseFormatted" label="Tanggal Permintaan" 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 pa-2 xs6>
              <v-autocomplete v-model="xRegional" label="Regional*" menu-icon="mdi-chevron-down"
                :items="regionalOptions" item-text="S_RegionalName" :disabled="act == 'preview'"
                item-value="S_RegionalID" return-object readonly :error="errors.regional"
                :error-messages="errors.regional ? 'Regional harus diisi' : ''"></v-autocomplete>
            </v-flex>
            <v-flex pa-2 xs6>
              <v-autocomplete v-model="xBranch" :label="user.M_BranchID != '0' ? 'Cabang*' : 'Cabang'" menu-icon="mdi-chevron-down" :items="branchOptions"
                item-text="M_BranchName" item-value="M_BranchCode" placeholder="Pilih Cabang"
                :disabled="act == 'preview'" return-object :error="errors.branch"
                :error-messages="errors.branch ? 'Cabang harus diisi' : ''"></v-autocomplete>
            </v-flex>
            <v-flex pa-2 xs6>
              <v-text-field v-model="xDescription" label="Keterangan*" :disabled="act == 'preview'"
                :error="errors.description" :error-messages="errors.description ? 'Keterangan harus diisi' : ''"
                required></v-text-field>
            </v-flex>
          </v-layout>
          <v-layout row>
            <v-flex pa-2 pl-0 xs12>
              <v-btn v-if="dialogItem == false && act != 'preview'" color="primary" @click="dialogItem = true">Pilih
                Item</v-btn>
              <v-btn v-if="dialogItem == true && act != 'preview'" color="primary" @click="dialogItem = false">Tutup
                Pilih
                Item</v-btn>
            </v-flex>
          </v-layout>
          <v-layout v-if="errors.details" row>
            <v-flex xs12 pl-2 pr-2 pt-2 pb-2>
              <v-alert :value="true" type="error" dismissible v-html="msgErrDetails">

              </v-alert>
            </v-flex>
          </v-layout>

          <div v-if="dialogItem == true && act != 'preview'">
            <v-divider></v-divider>
            <v-card elevation="10" 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 xs3>
                  <v-autocomplete v-model="selectedDivision" :items="divisionOptions" label="Divisi" return-object
                    menu-icon="mdi-chevron-down" item-text="DivisionName" hide-details
                    item-value="DivisionID"></v-autocomplete>

                </v-flex>
                <v-flex class="mt-2" pa-2 pb-0 xs3>
                  <v-autocomplete v-model="selectedItemGroup" :items="itemGroupOptions" hide-details label="Grup"
                    return-object menu-icon="mdi-chevron-down" item-text="Nat_GroupName"
                    item-value="Nat_GroupID"></v-autocomplete>

                </v-flex>
                <v-flex class="mt-2" pa-2 pb-0 xs3>
                  <v-autocomplete v-model="selectedItemSubGroup" :items="itemSubGroupOptions" return-object hide-details
                    label="Sub Grup" menu-icon="mdi-chevron-down" item-text="Nat_SubGroupName"
                    item-value="Nat_SubGroupID"></v-autocomplete>

                </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.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.remaining_stock }}
                      </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)">
                        <!--<v-btn v-if="checkSelected(props.item) == true" flat style="min-width: 35px; height: 35px; margin: 0" small color="grey" depressed><v-icon small>check</v-icon></v-btn---->
                        <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>
                        
                        <v-btn
                          style="min-width: 35px; height: 35px; margin: 0" 
                          small color="info"
                          @click="get_riwayat(props.item.itemId)"
                        >
                          <v-icon small>history</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>
            <v-divider></v-divider>
          </div>
          <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
                  :loading="loadingDetailRequest" 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.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)">
                      <v-btn depressed v-if="act != 'preview'" small color="primary"
                        @click="openDialogUnit(props.item)">{{ props.item.unitName }}</v-btn>
                      <span v-else>{{ props.item.unitName }}</span>
                    </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-if="act != 'preview'" v-model="props.item.qty" 
                        type="number" min=0 step=1
                        @keypress="blockDecimalInput($event)" @change="updateQuantity(props.item)">
                      </v-text-field>
                      <span v-else>{{ props.item.qty }}</span>
                    </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="act != 'preview'" style="min-width: 35px; height: 35px; margin: 0" small
                        color="error" dark @click="deleteItem(props.item)"><v-icon small>close</v-icon></v-btn>

                      <v-btn
                        style="min-width: 35px; height: 35px; margin: 0" 
                        small color="info"
                        @click="get_riwayat(props.item.itemId)"
                      >
                        <v-icon small>history</v-icon>
                      </v-btn>
                    </td>
                  </template>
                </v-data-table>
              </v-flex>
            </v-layout>
          </v-card>

        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn v-if="act === 'new'" color="info" :disabled="loadingSave" dark @click="saveAndRequestPurchase()">Save & Request Purchase</v-btn>
          <v-btn v-if="act === 'edit'" color="info" :disabled="loadingSave" dark @click="requestPending()">Request Purchase</v-btn>
          <v-btn color="error" flat @click="closeDialogRequest()">
            Tutup
          </v-btn>
          <v-btn v-if="act === 'new'" color="primary" :disabled="loadingSave" dark
            @click="savePurchaseRequest()">Simpan</v-btn>
          <v-btn v-if="act === 'edit'" color="primary" :disabled="loadingSave" dark
            @click="updatePurchaseRequest()">Simpan
            Perubahan</v-btn>
        </v-card-actions>

      </v-card>
    </v-dialog>
    
    <one-dialog-alert
        :status="dialogConfirmRequest"
        :msg="'Yakin mau melakukan Purchase Request? Tidak bisa diedit setelah melakukan Request'"
        @forget-dialog-alert="dialogConfirmRequest = false"
        @close-dialog-alert="confirmAndRequestPurchase()"
        confirmLabel="Yakin"
        cancelLabel="Batal"
      ></one-dialog-alert>
  </v-layout>
</template>

<script>
module.exports = {
  name: "AddPurchaseRequestDialog",
  components: {
    "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue")
  },
  data() {
    return {
      errors: { regional: false, branch: false, description: false, details: false },
      msgErrDetails: "<p>Data item belum ada. Silahkan masukkan data item terlebih dahulu.</p>",
      itemUnitChange: {},
      dialogItem: false,
      regionalRules: [(v) => !!v || "Regional harus diisi"],
      branchRules: [(v) => !!v || "Cabang harus diisi"],
      descRules: [(v) => !!v || "Keterangan harus diisi"],
      validationForm: true,
      dialogConfirmRequest: false,
      headers: [
        {
          text: "ITEM PERSEDIAAN",
          align: "center",
          sortable: false,
          value: "itemName",
          width: "15%",
          class: "success lighten-3 white--text",
        },
        {
          text: "SISA STOCK",
          align: "center",
          sortable: false,
          value: "qty",
          width: "10%",
          class: "success lighten-3 white--text",
        },
        {
          text: "SATUAN",
          align: "center",
          sortable: false,
          value: "unitName",
          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: "ITEM PERSEDIAAN",
          align: "center",
          sortable: false,
          value: "itemName",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "SATUAN",
          align: "center",
          sortable: false,
          value: "unitName",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "JUMLAH",
          align: "center",
          sortable: false,
          value: "qty",
          width: "10%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "AKSI",
          align: "center",
          sortable: false,
          value: "action",
          width: "10%",
          class: "blue lighten-3 white--text",
        },
      ]
    };
  },
  computed: {
    loadingDetailRequest() {
      return this.$store.state.requester.loadingDetailRequest;
    },
    loadingUnit() {
      return this.$store.state.requester.loadingUnit;
    },
    dialogUnit: {
      get() {
        return this.$store.state.requester.dialogUnit;
      },
      set(val) {
        this.$store.commit("requester/updateDialogUnit", val);
      },
    },
    selectedUnit: {
      get() {
        return this.$store.state.requester.selectedUnit;
      },
      set(val) {
        this.$store.commit("requester/updateSelectedUnit", val);
      },
    },
    unitOptions: {
      get() {
        return this.$store.state.requester.unitOptions;
      },
      set(val) {
        this.$store.commit("requester/updateUnitOptions", val);
      },
    },
    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);
      },
    },
    xBranch: {
      get() {
        return this.$store.state.requester.xBranch;
      },
      set(val) {
        this.$store.commit("requester/updateXBranch", val);
      },
    },
    branchOptions() {
      return this.$store.state.requester.branchOptions;
    },
    regionalOptions() {
      return this.$store.state.requester.regionalOptions;
    },
    xRegional: {
      get() {
        return this.$store.state.requester.xRegional;
      },
      set(val) {
        this.$store.commit("requester/updateXRegional", val);
      },
    },
    xDescription: {
      get() {
        return this.$store.state.requester.xDescription;
      },
      set(val) {
        this.$store.commit("requester/updateXDescription", val);
      },
    },
    xPRID() {
      return this.$store.state.requester.xPRID;
    },
    act() {
      return this.$store.state.requester.act;
    },
    itemCurrentPage: {
      get() {
        return this.$store.state.requester.itemCurrentPage;
      },
      set(val) {
        this.$store.commit("requester/updateItemCurrentPage", val);
        this.$store.dispatch("requester/getItems", {
          search: this.searchItem,
          division: this.selectedDivision.DivisionID ? this.selectedDivision.DivisionID : "",
          itemGroup: this.selectedItemGroup.Nat_GroupID ? this.selectedItemGroup.Nat_GroupID : "",
          itemSubGroup: this.selectedItemSubGroup.Nat_SubGroupID ? this.selectedItemSubGroup.Nat_SubGroupID : ""
        });
      },
    },
    itemTotalPage: {
      get() {
        return this.$store.state.requester.itemTotalPage;
      },
    },
    items: {
      get() {
        return this.$store.state.requester.items;
      },
      set(val) {
        this.$store.commit("requester/updateItems", val);
      }
    },
    selectedItem: {
      get() {
        return this.$store.state.requester.selectedItem;
      },
      set(val) {
        this.$store.commit("requester/updateSelectedItem", 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);
      }
    },
    itemGroupOptions: {
      get() {
        return this.$store.state.requester.itemGroupOptions;
      },
      set(val) {
        this.$store.commit("requester/updateItemGroupOptions", val);
      }
    },
    selectedItemGroup: {
      get() {
        return this.$store.state.requester.selectedItemGroup;
      },
      set(val) {
        this.$store.commit("requester/updateSelectedItemGroup", val);
        console.log(val)
        this.$store.commit("requester/updateItemSubGroupOptions", val.subGroups);
        this.$store.commit("requester/updateSelectedItemSubGroup", val.subGroups[0]);
      }
    },
    itemSubGroupOptions: {
      get() {
        return this.$store.state.requester.itemSubGroupOptions;
      },
      set(val) {
        this.$store.commit("requester/updateItemSubGroupOptions", val);
      }
    },
    selectedItemSubGroup: {
      get() {
        return this.$store.state.requester.selectedItemSubGroup;
      },
      set(val) {
        this.$store.commit("requester/updateSelectedItemSubGroup", val);

      }
    },
    loadingItemSubGroup: {
      get() {
        return this.$store.state.requester.loadingItemSubGroup;
      },
      set(val) {
        this.$store.commit("requester/updateLoadingItemSubGroup", val);
      }
    },
    loadingItemGroup: {
      get() {
        return this.$store.state.requester.loadingItemGroup;
      },
      set(val) {
        this.$store.commit("requester/updateLoadingItemGroup", val);
      }
    },
    divisionOptions: {
      get() {
        return this.$store.state.requester.divisionOptions;
      },
      set(val) {
        this.$store.commit("requester/updateDivisionOptions", val);
      }
    },
    selectedDivision: {
      get() {
        return this.$store.state.requester.selectedDivision;
      },
      set(val) {
        this.$store.commit("requester/updateSelectedDivision", val);
        this.$store.dispatch("requester/getItemGroupSubGroup");
      }
    },
    loadingSave: {
      get() {
        return this.$store.state.requester.loadingSave;
      },
      set(val) {
        this.$store.commit("requester/updateLoadingSave", val);
      }
    },
    selectedItem: {
      get() {
        return this.$store.state.requester.selectedItem;
      },
      set(val) {
        this.$store.commit("requester/updateSelectedItem", val);
      }
    },
    selectedItems: {
      get() {
        return this.$store.state.requester.selectedItems;
      },
      set(val) {
        this.$store.commit("requester/updateSelectedItems", val);
      }
    },
    dialog_riwayat: {
      get() {
        return this.$store.state.requester.dialog_riwayat
      },
      set(val) {
        this.$store.commit("requester/update_dialog_riwayat", val)
      }
    },
    user: {
      get() {
        return this.$store.state.requester.user
      },
      set(val) {
        this.$store.commit("requester/updateUser", val)
      }
    }
  },
  methods: {
    blockDecimalInput(e) {
      const invalidChars = ['.', ',', '-', 'e'];
      if (invalidChars.includes(e.key)) {
        e.preventDefault();
      }
    },

    requestPending() {
      let items = this.$store.state.requester.selectedItems;
      let valid = true
      items.forEach(item => {
        if (item.qty <= 0.9) {
          valid = false
        }
      });
      if (valid == true) {
        this.$store.commit("requester/updateLoadingSave", true);
        this.$store.dispatch("requester/updatePurchaseRequest", {
          act: "pending",
          PRID: this.$store.state.requester.selectedMainTable.prId,
          PRNumber: this.$store.state.requester.selectedMainTable.prNumber,
          PRDateUse: this.xDateUse,
          PRRegional: this.xRegional.S_RegionalID,
          PRBranch: typeof this.xBranch === "object" && this.xBranch !== null && "M_BranchCode" in this.xBranch ? this.xBranch.M_BranchCode : "",
          PRDescription: this.xDescription,
          items: this.$store.state.requester.selectedItems
        });
        this.errors.details = false;

      } else {
        this.errors.details = true;
        if (this.msgErrDetails == "") {
          this.msgErrDetails = "<p>Qty " + item.itemDesc + " tidak boleh 0</p>";
        } else {
          this.msgErrDetails += "<p>Qty " + item.itemDesc + " tidak boleh 0</p>";
        }
      }
    },
    saveAndRequestPurchase() {
      if (this.validateForm()) {
        // Show confirmation dialog instead of proceeding directly
        this.dialogConfirmRequest = true;
      } else {
        this.errors.details = true;
        this.msgErrDetails = this.selectedItems.length == 0 ? 
          "<p>Data item belum ada. Silahkan masukkan data item terlebih dahulu.</p>" : 
          this.msgErrDetails;
      }
    },
    confirmAndRequestPurchase() {
      // Close the dialog
      this.dialogConfirmRequest = false;
      
      // Now proceed with the actual save and request
      this.$store.commit("requester/updateLoadingSave", true);
      this.$store.dispatch("requester/saveAndDoPurchaseRequest", {
        PRDateUse: this.xDateUse,
        PRRegional: this.xRegional.S_RegionalID,
        PRBranch: typeof this.xBranch === "object" && this.xBranch !== null && "M_BranchCode" in this.xBranch ? this.xBranch.M_BranchCode : "",
        PRDescription: this.xDescription,
        items: this.selectedItems
      });
    },

    updatePurchaseRequest() {
      if (this.validateForm()) {
        this.$store.commit("requester/updateLoadingSave", true);
        this.$store.dispatch("requester/updatePurchaseRequest", {
          act: "edit",
          PRID: this.$store.state.requester.selectedMainTable.prId,
          PRNumber: this.$store.state.requester.selectedMainTable.prNumber,
          PRDateUse: this.xDateUse,
          PRRegional: this.xRegional.S_RegionalID,
          PRBranch: typeof this.xBranch === "object" && this.xBranch !== null && "M_BranchCode" in this.xBranch ? this.xBranch.M_BranchCode : "",
          PRDescription: this.xDescription,
          items: this.selectedItems
        });
      }

    },
    checkSelected(item) {
      let selectedItems = this.selectedItems;
      let rtn = false
      if (selectedItems.length == 0) {
        console.log(item.itemId, "selectedItems.length == 0");
        rtn = false;
      }
      selectedItems.forEach(itemloop => {
        if (itemloop.itemId == item.itemId) {
          console.log(item.itemId, "itemloop.itemId == item.itemId");
          rtn = true;
        }
      });
      console.log(item.itemId, "return false");
      return rtn;
    },
    savePurchaseRequest() {
      if (this.validateForm()) {
        this.$store.commit("requester/updateLoadingSave", true);
        this.$store.dispatch("requester/savePurchaseRequest", {
          PRDateUse: this.xDateUse,
          PRRegional: this.xRegional.S_RegionalID,
          PRBranch: typeof this.xBranch === "object" && this.xBranch !== null && "M_BranchCode" in this.xBranch ? this.xBranch.M_BranchCode : "",
          PRDescription: this.xDescription,
          items: this.selectedItems
        });
      }

    },
    itemSearch() {
      this.$store.dispatch("requester/getItems", {
        search: this.searchItem,
        division: this.selectedDivision.DivisionID ? this.selectedDivision.DivisionID : "",
        itemGroup: this.selectedItemGroup.Nat_GroupID ? this.selectedItemGroup.Nat_GroupID : "",
        itemSubGroup: this.selectedItemSubGroup.Nat_SubGroupID ? this.selectedItemSubGroup.Nat_SubGroupID : ""
      });
    },
    addItem(item) {
      let selectedItems = this.selectedItems;
      let index = selectedItems.findIndex(itemloop => itemloop.itemId == item.itemId);
      if (index == -1) {
        selectedItems.push(item);
      }

      this.$store.commit("requester/updateSelectedItems", selectedItems);
      console.log(this.selectedItems);
    },
    deleteItem(item) {
      let selectedItems = this.selectedItems;
      let index = selectedItems.findIndex(itemloop => itemloop.itemId == item.itemId);
      if (index != -1) {
        selectedItems.splice(index, 1);
      }
      this.$store.commit("requester/updateSelectedItems", selectedItems);
    },

    updateQuantity(item) {
      let items = this.selectedItems;
      let index = items.findIndex(itemloop => itemloop.itemId == item.itemId);
      items[index].qty = item.qty;
      console.log(items[index].qty)
      this.$store.commit("requester/updateSelectedItems", items);
    },
    saveUnit() {
      let items = this.selectedItems;
      let index = items.findIndex(itemloop => itemloop.itemId == this.itemUnitChange.itemId);
      let selectedUnit = this.selectedUnit;

      items[index].unitId = selectedUnit.unitId;
      items[index].unitCode = selectedUnit.unitCode;
      items[index].unitName = selectedUnit.unitName;
      this.$store.commit("requester/updateSelectedItems", items);
      this.$store.commit("requester/updateDialogUnit", false);
    },
    openDialogUnit(item) {
      this.itemUnitChange = item
      this.$store.dispatch("requester/getUnitByItemId", {
        itemId: item.itemId,
        selectedUnit: { unitId: item.unitId, unitCode: item.unitCode, unitName: item.unitName }
      });
    },
    isSelected(p) {
      return (
        p.itemId ==
        this.$store.state.requester.selectedItem
          .itemId
      );
    },
    selectMe(spr) {
      this.$store.commit("requester/updateSelectedItem", spr);
    },
    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.errors.details = false
      this.$store.commit(
        "requester/updateXDateUse",
        moment(new Date()).format("YYYY-MM-DD")
      );
      this.$store.commit("requester/updateXBranch", "");
      this.$store.commit("requester/updateXRegional", "");
      this.$store.commit("requester/updateXDescription", "");
      this.$store.commit("requester/updateDialogRequest", false);
      this.$store.commit("requester/updateSelectedItems", []);
    },
    validateForm() {
      this.errors.regional = _.isEmpty(this.xRegional) ? true : false;
      if (this.user.M_BranchID == '0') {
        this.errors.branch = false
      } else if (this.user.M_BranchID != '0') {
        this.errors.branch = _.isEmpty(this.xBranch) ? true : false;
      }
      this.errors.description = this.xDescription == "" ? true : false;
      this.errors.details = this.selectedItems.length == 0 ? true : false;
      this.msgErrDetails = this.selectedItems.length == 0 ? "<p>Data item belum ada. Silahkan masukkan data item terlebih dahulu.</p>" : "";

      let details = this.selectedItems
      details.forEach(item => {
        if (parseInt(item.qty) == 0 || item.qty == "" || parseInt(item.qty) <= 0) {
          this.errors.details = true;
          if (this.msgErrDetails == "") {
            this.msgErrDetails = "<p>Qty " + item.itemDesc + " tidak boleh 0</p>";
          } else {
            this.msgErrDetails += "<p>Qty " + item.itemDesc + " tidak boleh 0</p>";
          }
        }
      });
      //console.log(this.errors.details);
      if (this.errors.regional == false && this.errors.branch == false && this.errors.description == false && this.errors.details == false) {
        return true;
      } else {
        return false;
      }
    },
    get_riwayat(id) {
      this.$store.dispatch("requester/getRiwayatItem", {itemid: id})
      this.dialog_riwayat = true
    }
  },
  watch: {
    dialogItem(newVal) {
      if (newVal == true) {
        this.$store.commit("requester/updateItems", []);
        this.$store.dispatch("requester/getItems", {
          search: this.searchItem,
          division: this.selectedDivision.DivisionID ? this.selectedDivision.DivisionID : "",
          itemGroup: this.selectedItemGroup.Nat_GroupID ? this.selectedItemGroup.Nat_GroupID : "",
          itemSubGroup: this.selectedItemSubGroup.Nat_SubGroupID ? this.selectedItemSubGroup.Nat_SubGroupID : ""
        });
      }
    },
  },
};
</script>
