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

    <!-- dialog approve -->
    <v-dialog v-model="dialogApprove" persistent width="70vw">
      <v-card>
        <v-card-title class="headline grey lighten-2" primary-title>
          STOCK REQUEST PERSEDIAAN<v-spacer></v-spacer>
          <v-btn flat icon color="error" @click="closeDialogApprove()">
            <v-icon>close</v-icon>
          </v-btn>
        </v-card-title>

        <v-card-text>
          <v-layout row wrap>
            <v-flex xs3 class="mb-2 subheading">No. PR </v-flex>
            <v-flex xs9 class="mb-2 subheading"
              >: {{ selectedPr.prNumber ?? "" }}
            </v-flex>
            <v-flex xs3 class="mb-2 subheading">Tanggal </v-flex>
            <v-flex xs9 class="mb-2 subheading"
              >: {{ selectedPr.prDate ?? "" }}
            </v-flex>
            <v-flex xs3 class="mb-2 subheading">Type </v-flex>
            <v-flex xs9 class="mb-2 subheading"
              >: {{ selectedPr.prItemTypeName ?? "" }}
            </v-flex>
            <v-flex xs3 class="mb-2 subheading">Catatan </v-flex>
            <v-flex xs9 class="mb-2 subheading"
              >: {{ selectedPr.prNote ?? "" }}
            </v-flex>
            <v-flex
              xs3
              class="mb-2 subheading"
              v-if="selectedPr.prStatus !== 'Draft' && selectedPr.prStatus !== 'Rejected' && selectedPr.prStatus !== 'Pending'"
              >Approved By
            </v-flex>
            <v-flex
              xs3
              class="mb-2 subheading"
              v-if="selectedPr.prStatus !== 'Draft' && selectedPr.prStatus === 'Rejected' && selectedPr.prStatus !== 'Pending'"
              >Rejected By
            </v-flex>
            <v-flex
              xs9
              class="mb-2 subheading"
              v-if="selectedPr.prStatus !== 'Draft' && selectedPr.prStatus !== 'Pending'"
              >: {{ selectedPr.prApprovedBy ?? "" }}
            </v-flex>
            <v-flex
              xs3
              class="mb-2 subheading"
              v-if="selectedPr.prStatus !== 'Draft' && selectedPr.prStatus !== 'Rejected' && selectedPr.prStatus !== 'Pending'"
              >Approved Date
            </v-flex>
            <v-flex
              xs3
              class="mb-2 subheading"
              v-if="selectedPr.prStatus !== 'Draft' && selectedPr.prStatus === 'Rejected' && selectedPr.prStatus !== 'Pending'"
              >Rejected Date
            </v-flex>
            <v-flex
              xs9
              class="mb-2 subheading"
              v-if="selectedPr.prStatus !== 'Draft' && selectedPr.prStatus !== 'Pending'"
              >: {{ selectedPr.prApprovedDate ?? "" }}
            </v-flex>

            <v-flex xs12 class="mt-2">
              <v-data-table
                :headers="detailHeaders"
                :items="detailData"
                :loading="loadingDetail || loading"
                hide-actions
                class="elevation-1"
              >
                <template v-slot:items="props">
                  <td class="">{{ props.item.prDetailItemCode }}</td>
                  <td class="">{{ props.item.prDetailItemName }}</td>
                  <td class="py-2">
                    {{ props.item.CurrentStockQty }} {{ props.item.prDetailItemUnitName }}
                  </td>
                  <td class="py-2">
                    {{ props.item.prDetailItemQty }} {{ props.item.prDetailItemUnitName }}
                  </td>
                  <td class="py-2">
                    Rp {{ convertMoney(props.item.prDetailItemPrice) }}
                  </td>
                </template>
              </v-data-table>
            </v-flex>
          </v-layout>
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="error"
            v-if="selectedPr.prStatus === 'Approved' && act_dialog == 'unapprove'"
            flat
            :disabled="loading || loadingDetail"
            @click="approvePr('U')"
          >
            Unapprove
          </v-btn>
          <v-btn
            color="error"
            v-if="selectedPr.prStatus === 'Pending'"
            flat
            :disabled="loading || loadingDetail"
            @click="approvePr('R')"
          >
            Reject
          </v-btn>
          <v-btn
            color="success"
            v-if="(selectedPr.prStatus === 'Pending' && act_dialog == 'approve') || (selectedPr.prStatus === 'Pending' && act_dialog == 'verif')"
            flat
            :disabled="loading || loadingDetail"
            @click="approvePr('A')"
          >
            {{ user_approvelevel == '1'?  'Verify': 'Approve'}}
          </v-btn>
          <v-btn
            color="primary"
            v-if="selectedPr.prStatus !== 'Pending'"
            @click="closeDialogApprove()"
            :disabled="loading"
            flat
          >
            Tutup
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="dialogQty" persistent width="70vw">
      <v-card>
        <v-card-title class="headline grey lighten-2" primary-title>
          FORM EDIT QTY<v-spacer></v-spacer>
          <v-btn flat icon color="error" @click="closeDialogQty()">
            <v-icon>close</v-icon>
          </v-btn>
        </v-card-title>

        <v-card-text>
          <v-layout row wrap>
            <v-flex xs3 class="mb-2 subheading">No. PR </v-flex>
            <v-flex xs9 class="mb-2 subheading"
              >: {{ selectedPr.prNumber ?? "" }}
            </v-flex>
            <v-flex xs3 class="mb-2 subheading">Tanggal </v-flex>
            <v-flex xs9 class="mb-2 subheading"
              >: {{ selectedPr.prDate ?? "" }}
            </v-flex>
            <v-flex xs3 class="mb-2 subheading">Type </v-flex>
            <v-flex xs9 class="mb-2 subheading"
              >: {{ selectedPr.prItemTypeName ?? "" }}
            </v-flex>
            <v-flex xs3 class="mb-2 subheading">Catatan </v-flex>
            <v-flex xs9 class="mb-2 subheading"
              >: {{ selectedPr.prNote ?? "" }}
            </v-flex>

            <v-flex xs12 class="mt-2">
              <v-data-table
                :headers="qtyHeaders"
                :items="detailData"
                :loading="loadingDetail || loading"
                hide-actions
                class="elevation-1"
              >
                <template v-slot:items="props">
                  <td class="">{{ props.item.prDetailItemCode }}</td>
                  <td class="">{{ props.item.prDetailItemName }}</td>
                  <td class="">{{ props.item.CurrentStockQty }} {{ props.item.prDetailItemUnitName }}</td>
                  <td class="">
                    <v-text-field v-model="props.item.prDetailItemQty" 
                      type="number" min=0 step=1
                      @keypress="blockDecimalInput($event)" @change="updateQuantity(props.item)">
                    </v-text-field>
                  </td>
                </template>
              </v-data-table>
            </v-flex>
          </v-layout>
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="error"
            @click="closeDialogQty()"
            flat
          >
            Tutup
          </v-btn>
          <v-btn
            color="primary"
            @click="doUpdateQty()"
          >
            Simpan Perubahan
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- main layout -->
    <v-toolbar color="primary" dark>
      <v-toolbar-title class="white--text"
        >STOCK REQUEST APPROVE</v-toolbar-title
      >
      <v-spacer></v-spacer>
      <v-btn v-if="flag == 'G'" @click="goBack()" color="orange darken-2" title="Kembali ke listing pending approval" dark>
        <v-icon dark left>arrow_back</v-icon>Back
      </v-btn>
    </v-toolbar>

    <v-card class="pa-2">
      <v-layout row wrap>
        <v-flex xs3>
          <v-menu
            v-model="menuSelectedDate"
            :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
                :value="selectedDateFormatted"
                label="Tanggal Awal"
                readonly
                hide-details
                class="mr-2"
                outline
                v-on="on"
              ></v-text-field>
            </template>
            <v-date-picker
              no-title
              v-model="selectedDate"
              @input="menuSelectedDate = false"
            ></v-date-picker>
          </v-menu>
        </v-flex>
        <v-flex xs3>
          <v-menu
            v-model="menuSelectedEndDate"
            :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
                :value="selectedEndDateFormatted"
                label="Tanggal Akhir"
                readonly
                hide-details
                class="mr-2"
                outline
                v-on="on"
              ></v-text-field>
            </template>
            <v-date-picker
              no-title
              v-model="selectedEndDate"
              @input="menuSelectedEndDate = false"
            ></v-date-picker>
          </v-menu>
        </v-flex>
        <v-flex xs3>
          <v-autocomplete
            v-model="selectedStatus"
            menu-icon="mdi-chevron-down"
            :items="statusOptions"
            item-text="title"
            item-value="value"
            class="mr-2"
            label="Status"
            return-object
            outline
            hide-details
          ></v-autocomplete
        ></v-flex>
        <v-flex xs3>
          <v-text-field
            v-model="search"
            label="Cari..."
            placeholder="NO. PR"
            class="mr-2"
            outline
            hide-details
          >
          </v-text-field>
        </v-flex>
      </v-layout>
    </v-card>
    <v-card class="pa-2 mt-2">
      <div>
        <v-data-table
          :headers="headers"
          :items="prList"
          :loading="loading"
          hide-actions
          class="elevation-1"
        >
          <template v-slot:items="props">
            <td class="">{{ props.item.prBranchName }}</td>
            <td class="">{{ props.item.prNumber }}</td>
            <td class="text-xs-center">{{ props.item.prItemTypeName }}</td>
            <td class="">{{ props.item.prDate }}</td>
            <td class="">{{ props.item.prNote }}</td>
            <td class="">{{ props.item.prRequestedBy }}</td>
            <td class="text-xs-center">
              <v-layout column align-center justify-center>
                <v-chip
                  color="blue"
                  v-if="props.item.prStatus === 'Draft'"
                  text-color="white"
                  >{{ props.item.prStatus }}
                </v-chip>
                <v-chip
                  color="warning"
                  v-if="props.item.prStatus === 'Pending'"
                  text-color="white"
                  >{{ props.item.prStatus }}
                </v-chip>
                <v-chip
                  color="red"
                  v-if="props.item.prStatus === 'Rejected'"
                  text-color="white"
                  >{{ props.item.prStatus }}
                </v-chip>
                <v-chip
                  color="green"
                  v-if="props.item.prStatus !== 'Draft' && props.item.prStatus !== 'Rejected'&& props.item.prStatus !== 'Pending'"
                  text-color="white"
                  >{{ props.item.prStatus }}
                </v-chip>
                <p
                  v-if="props.item.prStatus !== 'Draft' && props.item.prStatus !== 'Pending'"
                  class="mb-1"
                >
                  <kbd>{{ props.item.prApprovedBy }}</kbd>
                </p>
                <p
                  v-if="props.item.prStatus !== 'Draft' && props.item.prStatus !== 'Pending'"
                  class="mb-1"
                >
                  <kbd>{{ props.item.prApprovedDate }}</kbd>
                </p>
              </v-layout>
            </td>
            <td class="text-xs-center">
              <v-layout column align-center justify-center>
                <v-icon
                  color="blue"
                  :disabled="loading"
                  v-if="props.item.prStatus !== 'Pending'"
                  @click="openDialogApprove('preview', props.item)"
                >
                  visibility
                </v-icon>

                <v-btn
                  color="orange" class="white--text" small round
                  :disabled="loading || user_approvelevel != '2' || user.M_BranchID != props.item.prRequestedByFromBranch"
                  :outline="props.item.prStatus == 'Approved'"
                  v-if="props.item.prStatus === 'Approved'"
                  @click="openDialogApprove('unapprove', props.item)"
                >
                  Unapprove
                  <v-icon small right dark>done_outline</v-icon>
                </v-btn>

                <v-btn
                  color="primary" class="white--text" small round
                  :disabled="loading || user_approvelevel != '1' || user.M_BranchID != props.item.prRequestedByFromBranch"
                  :outline="props.item.prStatus != 'Approved' && props.item.PurchaseRequestVerifiedBy == '0'"
                  v-if="props.item.prStatus === 'Pending'"
                  @click="openDialogApprove('verif', props.item)"
                >
                  {{ props.item.PurchaseRequestVerifiedBy != '0' ? 'Verified' : 'Verifikasi'}}
                  <v-icon small right dark>check_circle</v-icon>
                </v-btn>

                <v-btn
                  color="purple" class="white--text" small round
                  :disabled="loading || user.M_BranchID != props.item.prRequestedByFromBranch"
                  outline
                  v-if="props.item.prStatus === 'Pending' && props.item.PurchaseRequestVerifiedBy != '0' && user_approvelevel != '1'"
                  @click="openDialogQty(props.item)"
                >
                  Edit qty
                  <v-icon small right dark>edit</v-icon>
                </v-btn>

                <v-btn
                  color="primary" class="white--text" 
                  :disabled="loading || user_approvelevel != '2' || user.M_BranchID != props.item.prRequestedByFromBranch"
                  small round :outline="props.item.prStatus != 'Approved'"
                  v-if="props.item.prStatus === 'Pending'"
                  @click="openDialogApprove('approve', props.item)"
                >
                  Approve
                  <v-icon small right dark>done_all</v-icon>
                </v-btn>

                <!-- <v-icon
                  color="green"
                  :disabled="loading"
                  v-if="props.item.prStatus === 'Pending'"
                  @click="openDialogApprove(props.item)"
                >check_circle</v-icon> -->
              </v-layout>
            </td>
          </template>
        </v-data-table>
      </div>
    </v-card>
    <v-card class="text-xs-left pa-2">
      <v-pagination v-model="selectedPage" :length="totalPage"></v-pagination>
    </v-card>
  </div>
</template>

<style scoped>
  .date-type-table {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }

  .flex-items-center {
    display: flex;
    align-items: center;
    gap: 0.25rem;
  }

  .table.v-table tbody td,
  .table.v-table tbody tr {
    height: 40px;
  }

  .table.v-table thead tr {
    height: 40px;
  }
</style>

<script>
  module.exports = {
    components: {},
    data() {
      return {
        menuSelectedDate: false,
        menuSelectedEndDate: false,
        msgAlertDeleteOrReject: "",
        dialogAlertRejectRequest: false,
        dialogAlertDeleteDetail: false,
        amountRules: [(v) => v >= 0 || "Jumlah harus diisi"],
        validationDetail: false,
        headers: [
          {
            text: "CABANG",
            align: "center",
            sortable: false,
            value: "no",
            width: "10%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "NO. PR",
            align: "center",
            sortable: false,
            value: "no",
            width: "10%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "TIPE",
            align: "center",
            sortable: false,
            value: "no",
            width: "10%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "TANGGAL",
            align: "center",
            sortable: false,
            value: "date",
            width: "10%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "KETERANGAN",
            align: "center",
            sortable: false,
            value: "description",
            width: "30%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "REQUESTER",
            align: "center",
            sortable: false,
            value: "status",
            width: "10%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "STATUS",
            align: "center",
            sortable: false,
            value: "status",
            width: "10%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "AKSI",
            align: "center",
            sortable: false,
            value: "action",
            width: "10%",
            class: "blue lighten-3 white--text",
          },
        ],
        detailHeaders: [
          {
            text: "KODE ITEM",
            align: "center",
            sortable: false,
            value: "no",
            width: "15%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "NAMA ITEM",
            align: "left",
            sortable: false,
            value: "requestDate",
            width: "35%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "STOCK GUDANG",
            align: "left",
            sortable: false,
            value: "requestDate",
            width: "15%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "QTY",
            align: "left",
            sortable: false,
            value: "requestDate",
            width: "15%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "HARGA",
            align: "left",
            sortable: false,
            value: "requestDate",
            width: "20%",
            class: "blue lighten-3 white--text",
          },
        ],
        qtyHeaders: [
          {
            text: "KODE ITEM",
            align: "center",
            sortable: false,
            value: "no",
            width: "15%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "NAMA ITEM",
            align: "left",
            sortable: false,
            value: "requestDate",
            width: "45%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "STOCK GUDANG",
            align: "left",
            sortable: false,
            value: "requestDate",
            width: "25%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "QTY",
            align: "left",
            sortable: false,
            value: "requestDate",
            width: "15%",
            class: "blue lighten-3 white--text",
          }
        ],
      };
    },
    mounted() {
      this.$store.dispatch("prkacab/search");
      this.$store.dispatch("prkacab/getapprovelevel");
    },
    computed: {
      flag() {
        return this.$store.state.prkacab.flag;
      },
      status() {
        return this.$store.state.prkacab.status;
      },
      xstartdate() {
        return this.$store.state.prkacab.xstartdate;
      },
      statusOptions() {
        return this.$store.state.prkacab.statusOptions;
      },
      prList() {
        return this.$store.state.prkacab.prList;
      },
      loadingDetail: {
        get() {
          return this.$store.state.prkacab.loadingDetail;
        },
        set(val) {
          this.$store.commit("prkacab/update_loadingDetail", val);
        },
      },
      snackbar: {
        get() {
          return this.$store.state.prkacab.snackbar;
        },
        set(val) {
          this.$store.commit("prkacab/update_snackbar", val);
        },
      },
      loading: {
        get() {
          return this.$store.state.prkacab.loading;
        },
        set(val) {
          this.$store.commit("prkacab/update_loading", val);
        },
      },
      dialogApprove: {
        get() {
          return this.$store.state.prkacab.dialogApprove;
        },
        set(val) {
          this.$store.commit("prkacab/update_dialogApprove", val);
        },
      },
      detailData: {
        get() {
          return this.$store.state.prkacab.detailData;
        },
        set(val) {
          this.$store.commit("prkacab/update_detailData", val);
        },
      },
      selectedPage: {
        get() {
          return this.$store.state.prkacab.selectedPage;
        },
        set(val) {
          this.$store.commit("prkacab/update_selectedPage", val);
          this.$store.dispatch("prkacab/search");
        },
      },
      totalPage: {
        get() {
          return this.$store.state.prkacab.totalPage;
        },
        set(val) {
          this.$store.commit("prkacab/update_totalPage", val);
        },
      },
      selectedPr: {
        get() {
          return this.$store.state.prkacab.selectedPr;
        },
        set(val) {
          this.$store.commit("prkacab/update_selectedPr", val);
        },
      },
      selectedStatus: {
        get() {
          return this.$store.state.prkacab.selectedStatus;
        },
        set(val) {
          this.$store.commit("prkacab/update_selectedStatus", val);
          this.$store.dispatch("prkacab/search");
        },
      },
      search: {
        get() {
          return this.$store.state.prkacab.search;
        },
        set(val) {
          this.$store.commit("prkacab/update_search", val);
          this.$store.dispatch("prkacab/search");
        },
      },
      selectedDate: {
        get() {
          return this.$store.state.prkacab.selectedDate;
        },
        set(val) {
          this.$store.commit("prkacab/update_selectedDate", val);
          this.$store.dispatch("prkacab/search");
        },
      },
      selectedEndDate: {
        get() {
          return this.$store.state.prkacab.selectedEndDate;
        },
        set(val) {
          this.$store.commit("prkacab/update_selectedEndDate", val);
          this.$store.dispatch("prkacab/search");
        },
      },
      act_dialog: {
        get() {
          return this.$store.state.prkacab.act_dialog;
        },
        set(val) {
          this.$store.commit("prkacab/update_act_dialog", val);
        },
      },
      dialogQty: {
        get() {
          return this.$store.state.prkacab.dialogQty;
        },
        set(val) {
          this.$store.commit("prkacab/update_dialogQty", val);
        },
      },
      selectedItems: {
        get() {
          return this.$store.state.prkacab.selectedItems;
        },
        set(val) {
          this.$store.commit("prkacab/update_selectedItems", val);
        }
      },
      selectedDateFormatted() {
        return this.formatDate(this.selectedDate);
      },
      selectedEndDateFormatted() {
        return this.formatDate(this.selectedEndDate);
      },
      endDateFormatted() {
        return this.formatDate(this.fEndDate);
      },
      user() {
        return this.$store.state.prkacab.user;
      },
      user_approvelevel() {
        return this.$store.state.prkacab.user_approvelevel;
      }
    },
    methods: {
      blockDecimalInput(e) {
        const invalidChars = ['.', ',', '-', 'e'];
        if (invalidChars.includes(e.key)) {
          e.preventDefault();
        }
      },
      goBack() {
        window.history.back();
        // location.href = "/one-ui/test/vuex/one-accone-approve-all/"
      },
      convertMoney(money){
          return one_money(money)
      },
      closeDialogApprove() {
        this.dialogApprove = false;
        this.detailData = [];
      },
      closeDialogQty() {
        this.dialogQty = false;
        this.detailData = [];
      },
      approvePr(type) {
        if (this.user_approvelevel == '1' && this.selectedPr.PurchaseRequestVerifiedBy != '0') {
          let snackbar = {
            state: true,
            type: "warning",
            message: "Request sudah diverifikasi",
          };
          this.snackbar = snackbar;
          return;
        }


        if (this.detailData.length === 0) {
          let snackbar = {
            state: true,
            type: "warning",
            message: "Detail masih kosong",
          };
          this.snackbar = snackbar;
          return
        }

        let cek = this.detailData;
        let newTotal = 0;
        cek.forEach((element) => {
          newTotal =
            newTotal + element.prDetailItemQty * element.prDetailItemPrice;
        });

        let prm = {
          type: type,
          pr: this.selectedPr,
          total: newTotal,
          detail: cek,
        };
        console.log(prm);
        console.log("approve");
        this.$store.dispatch("prkacab/approve", prm);
      },
      openDialogApprove(prm, data) {
        this.act_dialog = prm
        this.selectedPr = data;
        this.dialogApprove = true;
        this.$store.dispatch("prkacab/getDetail");
      },
      openDialogQty(data) {
        this.selectedPr = data;
        this.dialogQty = true;
        this.$store.dispatch("prkacab/getDetail");
      },
      isSelected(p) {
        return (
          p.PurchaseRequestDirectNumber ==
          this.$store.state.prkacab.selectedMainTable
            .PurchaseRequestDirectNumber
        );
      },
      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")}`;
      },
      updateQuantity(item) {
        let items = this.detailData;
        let index = items.findIndex(itemloop => itemloop.prDetailItemID == item.prDetailItemID);
        items[index].prDetailItemQty = item.prDetailItemQty;
        this.$store.commit("prkacab/update_selectedItems", items);
      },
      doUpdateQty() {
        let prm = {
          arrItems: this.selectedItems
        }
        this.$store.dispatch("prkacab/updateqty", prm);
      }
    },
    watch: {
      dialogApprove(val, old) {},
    },
  };
</script>
