<template>
    <div style="width: 100%">
        <v-snackbar
        v-model="snackbar.state"
        :color="snackbar.type"
        :timeout="3000"
        multi-line
        top
        >
        {{ snackbar.message }}
        <v-btn flat @click="snackbar.state = false">
            Close
        </v-btn>
        </v-snackbar>

        <template>
          <v-dialog v-model="dialogapprove" max-width="30%">
            <v-card>
              <v-card-title class="headline grey lighten-2 pt-2 pb-2" primary-title>
                Peringatan !
              </v-card-title>
              <v-card-text class="pt-2 pb-2">
                <v-layout row>
                  <v-flex xs12 d-flex>
                    <v-layout row>
                      <v-flex pb-1 xs12>
                        <v-layout row>
                          <v-flex pt-2 pr-2 xs12>
                            {{ msgapprove }}
                          </v-flex>
                        </v-layout>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                </v-layout>
              </v-card-text>
              <v-divider></v-divider>
              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="error" flat @click="dialogapprove = false">
                  Tutup
                </v-btn>
                <v-btn
                  color="primary"
                  @click="orderApprove()"
                >
                  Ya
                </v-btn>
              </v-card-actions>
            </v-card>
          </v-dialog>
        </template>

        <template>
          <v-dialog v-model="dialogreject" max-width="30%">
            <v-card>
              <v-card-title class="headline grey lighten-2 pt-2 pb-2" primary-title>
                Peringatan !
              </v-card-title>
              <v-card-text class="pt-2 pb-2">
                <v-layout row>
                  <v-flex xs12 d-flex>
                    <v-layout row>
                      <v-flex pb-1 xs12>
                        <v-layout row>
                          <v-flex pt-2 pr-2 xs12>
                            {{ msgreject }}
                          </v-flex>
                        </v-layout>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                </v-layout>
              </v-card-text>
              <v-divider></v-divider>
              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="error" flat @click="dialogreject = false">
                  Tutup
                </v-btn>
                <v-btn
                  color="primary"
                  @click="orderRejected()"
                >
                  Ya
                </v-btn>
              </v-card-actions>
            </v-card>
          </v-dialog>
        </template>
  
      <!-- ERROR DIALOG -->
      <!-- <v-dialog v-model="dialog_error" max-width="500px">
        <v-card>
          <v-card-title>
            <span>ERROR !</span>
            <v-spacer></v-spacer>
          </v-card-title>
          <v-divider></v-divider>
          <div class="ma-3 red--text">{{ msgError }}</div>
          <v-divider></v-divider>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="primary" flat @click="dialog_error = false"
              >Tutup</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-dialog> -->
      <!-- END ERROR DIALOG -->  
  
      <v-toolbar color="primary" dark>
        <v-toolbar-title class="white--text"
          >LISTING REQUEST PENGELUARAN BARANG</v-toolbar-title
        >
      </v-toolbar>
      <v-card class="pa-2">
        <div class="d-flex justify-start align-center" style="gap: 1rem">
          <v-menu
            v-model="menuStartDate"
            :close-on-content-click="false"
            transition="scale-transition"
            :nudge-right="40"
            lazy
            offset-y
            max-width="290px"
            min-width="290px"
          >
            <template v-slot:activator="{ on }">
              <v-text-field
                v-model="startDateFormatted"
                label="Tanggal Awal"
                readonly
                style="max-width: 250px"
                outline
                hide-details
                v-on="on"
                @blur="dStartDate = deFormatedDate(startDateFormatted)"
              ></v-text-field>
            </template>
            <v-date-picker
              no-title
              v-model="fStartDate"
              @input="menuStartDate = false"
            ></v-date-picker>
          </v-menu>
          <v-menu
            v-model="menuEndDate"
            :close-on-content-click="false"
            transition="scale-transition"
            :nudge-right="40"
            lazy
            offset-y
            max-width="290px"
            min-width="290px"
          >
            <template v-slot:activator="{ on }">
              <v-text-field
                v-model="endDateFormatted"
                label="Tanggal Akhir"
                readonly
                style="max-width: 250px"
                outline
                hide-details
                v-on="on"
                @blur="dEndDate = deFormatedDate(endDateFormatted)"
              ></v-text-field>
            </template>
            <v-date-picker
              no-title
              v-model="fEndDate"
              @input="menuEndDate = false"
            ></v-date-picker>
          </v-menu>
          <v-autocomplete
            v-model="fStatus"
            menu-icon="mdi-chevron-down"
            :items="statusOptions"
            item-text="title"
            return-object
            label="Status"
            style="max-width: 250px"
            outline
            hide-details
          ></v-autocomplete>
          <v-text-field
            v-model="fSearch"
            label="Cari..."
            placeholder="NO. RIO"
            style="max-width: 250px"
            outline
            hide-details
          ></v-text-field>
          <v-btn
            dark
            color="primary"
            style="min-width: 50px; height: 50px; margin: 0"
            @click="listSearch()"
          >
            <v-icon>search</v-icon>
          </v-btn>
        </div>
      </v-card>
      <v-card class="pa-2 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="headers"
              :items="listRequest"
              :loading="loadingStatus"
              hide-actions
              class="elevation-1"
            >
              <template v-slot:headers="props">
                  <tr>
                      <th
                          v-for="header in props.headers" :class="header.class"
                          :key="header.text" :width="header.width">
                          {{ header.text }}
                      </th>
                      <th width="5%" class="blue lighten-3 white--text">
                          <v-checkbox
                              :loading="loadingStatus"
                              :input-value="headerCheckboxValueAll()" 
                              primary hide-details
                              :indeterminate="headerCheckboxValuePartial()" 
                              @click.stop="checkItemAll"
                          ></v-checkbox>
                      </th>
                  </tr>
              </template>
              <template v-slot:items="props">
                  <td
                    class="text-xs-center pa-2"
                  >
                    <div
                      style="
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                      "
                    >
                      <p class="mb-0 font-weight-bold" style="color:#000000">{{ props.item.rioNumber }}</p>
                      {{ deFormatedDate(props.item.rioDate) }}
                    </div>
                  </td>
                  <td
                    class="text-xs-left pa-2"
                  >
                    {{ props.item.M_ItemDesc }}
                  </td>
                  <td
                    class="text-xs-left pa-2"
                  >
                      {{ props.item.StockQty }}
                  </td>
                  <td
                    class="text-xs-left pa-2"
                  >
                      {{ props.item.rioDQty }}
                  </td>
                  <td
                    class="text-xs-left pa-2"
                  >
                    <v-chip
                      small
                      :text-color="
                        props.item.rioDStatus === 'Draft'
                          ? 'black'
                          : 'white'
                      "
                      :color="
                        getChipStatusColor(
                          props.item.rioDStatus
                        )
                      "
                    >
                      {{ props.item.rioDStatus }}
                    </v-chip>
                  </td>
                  <td>
                    <span v-if="props.item.rioStatus === 'Send Request'">
                      <v-checkbox
                          :input-value="checkBoxValue(props.item)"
                          primary hide-details
                          @change="changeCheckBox(props.item)"
                      ></v-checkbox>
                    </span>
                  </td>


                <!-- <template
                v-if="props.item.rioDStatus == 'Send Request'"
                >
                <td
                  class="text-xs-center pa-2"
                  v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                  @click="selectMe(props.item)"
                >
                    <v-btn
                        dark
                        v-if="requestExist(props.item)"
                        @click="addRequest(props.item)"
                        style="min-width: 25px; height: 30px"
                        small
                        color="success"
                        >
                          <v-icon small>check</v-icon>
                    </v-btn>
                    <v-btn
                        dark
                        v-if="!requestExist(props.item)"
                        @click="removeRequest(props.item)"
                        style="min-width: 25px; height: 30px"
                        small
                        color="red"
                        >
                          <v-icon small>close</v-icon>
                    </v-btn>
                </td>
                </template>
                <template v-else>
                    <td
                        class="text-xs-center pa-2"
                        v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                        @click="selectMe(props.item)">
                    </td>
                </template> -->
              </template>
            </v-data-table>
          </v-flex>
        </v-layout>
        <div style="width: 100%" class="d-flex justify-end">
            <template
                v-if="selectedItems.length > 0 &&
                selectedItems.every(item => item.rioStatus === 'Send Request')"
            >
                <v-btn
                color="red"
                outline
                dark
                style="max-width: 200px"
                class="ml-5"
                :disabled="!listRequest.length"
                @click="openRejected(selectedItems)
                "
                >
                Reject
                </v-btn>
            </template>
            <template
                v-if="selectedItems.length == 0 ? false : true"
            >
                <v-btn
                color="primary"
                dark
                style="max-width: 200px"
                class="ml-2"
                :disabled="!listRequest.length"
                @click="openApprove(selectedItems)
                "
                >
                Approve
                </v-btn>
            </template>
        </div>
        <v-divider></v-divider>
        <v-pagination
          style="margin-top: 10px; margin-bottom: 10px"
          v-model="currentPage"
          :length="totalPage"
        ></v-pagination>
      </v-card>

        <template>
            <one-dialog-info :status="opendialoginfo" :msg="msginfo"
                @close-dialog-info="opendialoginfo = false"></one-dialog-info>
        </template>
    </div>
  </template>
  
  <style scoped>
  .date-type-table {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .table.v-table tbody td,
  table.v-table tbody th {
    height: 40px;
  }
  
  .table.v-table thead tr {
    height: 40px;
  }
  
  .scroll-container {
    scroll-padding: 50px 0 0 50px;
  }
  </style>
  
  <script>
  module.exports = {
    components: {
      "add-item-out-dialog": httpVueLoader(
        "./addItemOutDialog.vue"
      ),
      "add-item-detail-dialog": httpVueLoader("./addItemDetailDialog.vue"),
      "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue"),
      "one-dialog-error": httpVueLoader("../../common/oneDialogError.vue"),
      "one-dialog-info": httpVueLoader("../../common/oneDialogInfo.vue"),
    },
    data() {
      return {
        msgAlertDeleteRequest: "",
        dialogAlertDeleteRequest: false,
        dialogAlertDeleteDetail: false,
        xDescription: "",
        headers: [
          {
            text: "NO RIO",
            align: "center",
            sortable: false,
            value: "no",
            width: "15%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "ITEM",
            align: "left",
            sortable: false,
            value: "date",
            width: "35%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "STOCK",
            align: "left",
            sortable: false,
            value: "warehouse",
            width: "10%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "REQUEST QTY",
            align: "left",
            sortable: false,
            value: "departement",
            width: "10%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "STATUS",
            align: "left",
            sortable: false,
            value: "status",
            width: "15%",
            class: "blue lighten-3 white--text",
          },
        ]
      };
    },
    mounted() {
        this.$store.dispatch("listrequest/listrequestitem");
        this.$store.dispatch("listrequest/getDivisionUser");
    },
    computed: {
        listRequest() {
            return this.$store.state.listrequest.request;
        },
        loadingStatus() {
            return this.$store.state.listrequest.loadingStatus === 1;
        },
        totalPage: {
            get() {
                return this.$store.state.listrequest.totalPage;
            },
            set(val) {
                this.$store.commit("listrequest/update_totalPage", val);
            },
        },
        currentPage: {
            get() {
                return this.$store.state.listrequest.currentPage;
            },
            set(val) {
                this.$store.commit("listrequest/update_currentPage", val);
                this.$store.commit("listrequest/update_lastId", -1);
                this.$store.dispatch("listrequest/listrequestitem");
            },
        },
        menuStartDate: {
            get() {
                return this.$store.state.listrequest.menuStartDate;
            },
            set(val) {
                this.$store.commit("listrequest/update_menuStartDate", val);
            },
        },
        menuEndDate: {
            get() {
                return this.$store.state.listrequest.menuEndDate;
            },
            set(val) {
                this.$store.commit("listrequest/update_menuEndDate", val);
            },
        },
        startDateFormatted() {
            return this.formatDate(this.fStartDate);
        },
        endDateFormatted() {
            return this.formatDate(this.fEndDate);
        },
        dStartDate: {
            get() {
                return this.$store.state.listrequest.dStartDate;
            },
            set(val) {
                this.$store.commit("listrequest/update_dStartDate", val);
            },
        },
        dEndDate: {
            get() {
                return this.$store.state.listrequest.dEndDate;
            },
            set(val) {
                this.$store.commit("listrequest/update_dEndDate", val);
            },
        },
        fStartDate: {
            get() {
                return this.$store.state.listrequest.fStartDate;
            },
            set(val) {
                this.$store.commit("listrequest/update_fStartDate", val);
            },
        },
        fEndDate: {
            get() {
                return this.$store.state.listrequest.fEndDate;
            },
            set(val) {
                this.$store.commit("listrequest/update_fEndDate", val);
            },
        },
        fStatus: {
            get() {
                return this.$store.state.listrequest.fStatus;
            },
            set(val) {
                this.$store.commit("listrequest/update_fStatus", val);
            },
        },
        statusOptions() {
            return this.$store.state.listrequest.statusOptions;
        },
        fSearch: {
            get() {
                return this.$store.state.listrequest.fSearch;
            },
            set(val) {
                this.$store.commit("listrequest/update_fSearch", val);
            },
        },
        selectedRequest: {
            get() {
                return this.$store.state.listrequest.selectedRequest;
            },
            set(val) {
                this.$store.commit("listrequest/update_selectedRequest", val);
            },
        },
        selectedItems: {
            get() {
                return this.$store.state.listrequest.selectedItems;
            },
            set(val) {
                this.$store.commit("listrequest/update_selectedItems", val);
            },
        },
        opendialoginfo: {
            get() {
                return this.$store.state.listrequest.opendialoginfo;
            },
            set(val) {
                this.$store.commit("listrequest/update_opendialoginfo", val);
            },
        },
        msginfo: {
            get() {
                return this.$store.state.listrequest.msginfo;
            },
            set(val) {
                this.$store.commit("listrequest/update_msginfo", val);
            },
        },
        snackbar: {
            get() {
                return this.$store.state.listrequest.snackbar;
            },
            set(val) {
                this.$store.commit("listrequest/update_snackbar", val);
            },
        },
        dialogapprove: {
            get() {
                return this.$store.state.listrequest.dialogapprove;
            },
            set(val) {
                this.$store.commit("listrequest/update_dialogapprove", val);
            },
        },
        msgapprove: {
            get() {
                return this.$store.state.listrequest.msgapprove;
            },
            set(val) {
                this.$store.commit("listrequest/update_msgapprove", val);
            },
        },
        dialogreject: {
            get() {
                return this.$store.state.listrequest.dialogreject;
            },
            set(val) {
                this.$store.commit("listrequest/update_dialogreject", val);
            },
        },
        msgreject: {
            get() {
                return this.$store.state.listrequest.msgreject;
            },
            set(val) {
                this.$store.commit("listrequest/update_msgreject", val);
            },
        },
        approveDivisionUserID: {
          get() {
            return this.$store.state.listrequest.approveDivisionUserID;
          },
          set(val) {
            this.$store.commit("listrequest/updateApproveDivisionUserID", val);
          },
        },
        approveDivision: {
          get() {
            return this.$store.state.listrequest.approveDivision;
          },
          set(val) {
            this.$store.commit("listrequest/updateApproveDivision", val);
          },
        }
    },
    methods: {
        isSelected(p) {
            return (
                p.rioDID ==
                this.$store.state.listrequest.selectedRequest
                .rioDID
            );
        },
        selectMe(spr) {
            this.$store.commit("listrequest/update_selectedRequest", 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")}`;
        },
        getChipStatusColor(status) {
            switch (status) {
                case "Send Request":
                return "warning";
                case "Process":
                return "success";
                case "Rejected":
                return "error";
                case "Completed":
                return "info";
                default:
                return "";
            }
        },
        listSearch() {
            this.$store.dispatch("listrequest/listrequestitem");
            this.$store.commit("listrequest/update_selectedRequest", {});
        },
        requestExist(request) {
            var selectedItems = this.selectedItems;
            var idx = _.findIndex(selectedItems, function (o) {
                return parseInt(o.rioDID) === parseInt(request.rioDID);
            });
            if (idx === -1) {
                return true;
            } else {
                return false;
            }
        },
        checkItemAll() {
          // Salin selectedItems ke dalam array baru
          let raw = JSON.stringify(this.selectedItems);
          let arr = [...JSON.parse(raw)];

          // Cek apakah checkbox utama (select all) sedang dicentang
          let ckAll = this.headerCheckboxValueAll();

          // Iterasi semua item yang tersedia
          for (let i = 0; i < this.listRequest.length; i++) {
            const element = this.listRequest[i];

            // Hanya proses item dengan status 'Send Request'
            if (element.rioStatus !== 'Send Request') continue;

            let foundItem = arr.find((e) => e.rioDID === element.rioDID);
            const index = arr.findIndex((e) => e.rioDID === element.rioDID);

            if (ckAll) {
              // Hapus item dari selected jika sesuai kondisi
              arr.splice(index, 1);
            } else {
              // Tambahkan item ke selected jika sesuai kondisi dan belum ada
              if (!foundItem) {
                arr.push(element);
              }
            }
          }

          // Update pilihan
          this.selectedItems = arr;
          console.log('arr', arr)
        },
        headerCheckboxValueAll() {
          // debugger;
          let total = 0;
          let selected = 0;
          for (let i = 0; i < this.listRequest.length; i++) {
            const element = this.listRequest[i];

            if (element.rioStatus !== 'Send Request') continue;

            total++;
            let foundItem = this.selectedItems.find(
              (e) => e.rioDID === element.rioDID
            );
            if (foundItem) {
              selected++;
            }
          }
          return total > 0 && selected === total;
        },
        headerCheckboxValuePartial() {
          let total = 0;
          let selected = 0;
          for (let i = 0; i < this.listRequest.length; i++) {
            const element = this.listRequest[i];

            if (element.rioStatus !== 'Send Request') continue;

            total++;
            let foundItem = this.selectedItems.find(
              (e) => e.rioDID === element.rioDID
            );
            if (foundItem) {
              selected++;
            }
          }
          return selected > 0 && selected < total;
        },
        changeCheckBox(val) {
          // debugger;
          let raw = JSON.stringify(this.selectedItems);

          let arr = [...JSON.parse(raw)];
          if (arr.length == 0) {
            arr.push(val);
          } else {
            let foundItem = arr.find((e) => e.rioDID === val.rioDID);
            const index = arr.findIndex((e) => e.rioDID === val.rioDID);
            if (foundItem) {
              arr.splice(index, 1);
            } else {
              arr.push(val);
            }
          }
          this.selectedItems = arr;
        },
        checkBoxValue(val) {
          let foundItem = this.selectedItems.find((e) => e.rioDID === val.rioDID);
          if (foundItem) {
            return true;
          } else {
            return false;
          }
        },
        addRequest(request) {
            if (!request.StockID) {
                let msge = "Item belum ada di stock";
                this.msginfo = msge;
                this.opendialoginfo = true;
                return;
            }

            if (!request.StockQty || request.StockQty === 0 || request.StockQty == "0") {
                let msgg = "Item tidak bisa dikeluarkan karena stock kosong";
                this.msginfo = msgg;
                this.opendialoginfo = true;
                return;
            }

            const exists = this.selectedItems.some(item => item.rioDID === request.rioDID);
            console.log('exists', exists)
            if (!exists) {
                this.selectedItems.push(request);
                // console.log("add request", this.selectedItems);
            }
        },
        removeRequest(request) {
            let selectedItems = this.selectedItems;
            let idx = _.findIndex(selectedItems, function (o) {
                return parseInt(o.rioDID) === parseInt(request.rioDID);
            });
            selectedItems.splice(idx, 1);
            console.log("hapus request", this.selectedItems)
        },
        openApprove(request) {
          if (request.some(item => item.rioDivisionID !== this.approveDivisionUserID)) {
            this.msginfo = "Tidak bisa approve, Anda login manager tapi tidak sesuai divisi";
            this.opendialoginfo = true;
            return;
          }


          // Cek jika ada item yang belum punya StockID
          const noStockID = request.find(item => !item.StockID);
          // gabung number
          const allRioNumbers = request.map(item => item.rioNumber).join(', ');
          if (noStockID) {
            this.msginfo = "Item belum ada di stock " + "(" + allRioNumbers + ")";
            this.opendialoginfo = true;
            return;
          }

          // Cek jika ada item dengan stock kosong atau 0
          const stockKosong = request.find(item => !item.StockQty || item.StockQty === 0 || item.StockQty === "0");
          if (stockKosong) {
            this.msginfo = "Item tidak bisa dikeluarkan karena stock kosong " + "(" + allRioNumbers + ")"; 
            this.opendialoginfo = true;
            return;
          }

          let msg = "Yakin, mau approve ?";
          this.msgapprove = msg;
          this.dialogapprove = true;
          
        },
        orderApprove() {
            let prm = {
                arrRequest: this.selectedItems
            }
            this.$store.dispatch("listrequest/approveRequest", prm);
        },
        openRejected(request) {
          let msg = "Yakin, mau reject ?";
          this.msgreject = msg;
          this.dialogreject = true;
        },
        orderRejected() {
            let prm = {
                arrRequest: this.selectedItems
            }
            this.$store.dispatch("listrequest/rejectedRequest", prm);
        }
    },
  
    watch: {

    }
  };
  </script>
  