<template>
  <div style="width: 100%;">
    <v-layout row wrap>
      <v-flex xs6 class="left" fill-height pa-1>
        <v-toolbar color="primary" dark>
          <v-toolbar-title class="white--text"
            >STOCK REQUEST KACAB</v-toolbar-title
          >
          <v-spacer></v-spacer>
        </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
                  :value="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
                  :value="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"
              item-value="value"
              label="Status"
              style="max-width: 250px;"
              outline
              hide-details
            ></v-autocomplete>
            <v-text-field
              v-model="fSearch"
              label="Cari..."
              placeholder="NO. PR"
              style="max-width: 250px;"
              outline
              hide-details
            ></v-text-field>
            <v-btn
              dark
              color="primary"
              style="min-width: 50px; height: 50px; margin: 0;"
              @click="mainTableSearch()"
            >
              <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="mainTable"
                :loading="mainTableLoading"
                hide-actions
                class="elevation-1"
              >
                <template slot="items" slot-scope="props">
                  <td
                    class="text-xs-center pa-2"
                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                  >
                    <div
                      style="
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                      "
                    >
                      {{ props.item.PurchaseRequestDirectNumber }}
                      <v-chip small style="border-radius: 5px; flex-grow: 0;">
                        {{ props.item.M_RequesterFullName }}
                      </v-chip>
                    </div>
                  </td>
                  <td
                    class="text-xs-left pa-2"
                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                  >
                    <div class="date-type-table">
                      <span>
                        <span class="font-weight-medium"> Permintaan: </span>
                        {{
                          deFormatedDate(props.item.PurchaseRequestDirectDate)
                        }}
                      </span>
                      <span class="text-error">
                        <span class="font-weight-medium"> Pelaksanaan: </span>
                        {{
                          deFormatedDate(
                            props.item.PurchaseRequestDirectDateUse
                          )
                        }}
                      </span>
                    </div>
                  </td>
                  <td
                    class="text-xs-left pa-2"
                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                  >
                    {{ props.item.PurchaseRequestDirectDescription }}
                  </td>
                  <td
                    class="text-xs-left pa-2"
                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                  >
                    <v-chip
                      small
                      :text-color="
                        props.item.PurchaseRequestDirectStatus === 'Draft'
                          ? 'black'
                          : 'white'
                      "
                      :color="
                        getChipStatusColor(
                          props.item.PurchaseRequestDirectStatus
                        )
                      "
                    >
                      {{ props.item.PurchaseRequestDirectStatus }}
                    </v-chip>
                  </td>
                  <template
                    v-if="props.item.PurchaseRequestDirectStatus != 'Draft'"
                  >
                    <td
                      class="text-xs-center pa-2"
                      v-bind:class="{
                        'amber lighten-4': isSelected(props.item),
                      }"
                    >
                      <v-icon
                        v-if="
                          props.item.PurchaseRequestDirectStatus == 'Pending'
                        "
                        small
                        @click="approveOrViewRequest(props.item)"
                        >edit</v-icon
                      >
                      <v-icon
                        v-if="
                          ['Approved', 'Paid', 'Completed'].includes(
                            props.item.PurchaseRequestDirectStatus
                          )
                        "
                        small
                        @click="approveOrViewRequest(props.item)"
                        >visibility</v-icon
                      >
                    </td>
                  </template>
                  <template v-else>
                    <td
                      class="text-xs-center pa-2"
                      v-bind:class="{
                        'amber lighten-4': isSelected(props.item),
                      }"
                    ></td>
                  </template>
                </template>
              </v-data-table>
            </v-flex>
          </v-layout>
          <v-divider></v-divider>
          <v-pagination
            style="margin-top: 10px; margin-bottom: 10px;"
            v-model="mainTableCurrentPage"
            :length="mainTableTotalPage"
          ></v-pagination>
        </v-card>
      </v-flex>
      <v-flex xs6 class="right" fill-height pa-1>
        <v-card>
          <v-card-text>
            <v-layout row wrap>
              <v-flex xs12>
                <v-layout row wrap>
                  <v-flex xs12>
                    <div>
                      <span>Nama Pengambil: </span>
                      <span>{{ selectedMainTable.M_RequesterFullName }}</span>
                    </div>
                  </v-flex>
                </v-layout>
              </v-flex>
              <v-flex xs12 pt-2 pb-2>
                <v-layout row wrap>
                  <v-flex xs12>
                    <v-data-table
                      :headers="detailHeaders"
                      :items="detailTable"
                      :loading="detailTableLoading"
                      hide-actions
                      class="elevation-1"
                    >
                      <template slot="items" slot-scope="props">
                        <td class="text-xs-center pa-2">
                          {{ props.item.RowNumber }}
                        </td>
                        <td class="text-xs-left pa-2">
                          {{ props.item.PurchaseRequestDirectDescription }}
                        </td>
                        <td class="text-xs-left pa-2">
                          {{
                            props.item.PurchaseRequestDirectDetailAmountRequest
                          }}
                        </td>
                        <td class="text-xs-left pa-2">
                          {{
                            props.item.PurchaseRequestDirectDetailAmount ??
                            props.item.PurchaseRequestDirectDetailAmountRequest
                          }}
                        </td>
                        <td class="text-xs-left pa-2">
                          <div class="date-type-table">
                            <span>
                              Satuan : Rp
                              {{
                                props.item.PurchaseRequestDirectDetailEstimationPrice.toString().replace(
                                  /\B(?=(\d{3})+(?!\d))/g,
                                  "."
                                )
                              }}
                            </span>
                            <span>
                              Total : Rp
                              {{
                                (
                                  props.item
                                    .PurchaseRequestDirectDetailAmountRequest *
                                  props.item
                                    .PurchaseRequestDirectDetailEstimationPrice
                                )
                                .toString()
                                .replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                              }}
                            </span>
                          </div>
                        </td>
                        <template
                          v-if="
                            !(
                              selectedMainTable.PurchaseRequestDirectStatus !=
                              'Pending'
                            )
                          "
                        >
                          <td class="text-xs-center pa-2">
                            <v-icon small @click="updateDetail(props.item)"
                              >edit</v-icon
                            >
                            <v-icon small @click="deleteDetail(props.item)"
                              >delete</v-icon
                            >
                          </td>
                        </template>
                        <template v-else>
                          <td class="text-xs-center pa-2"></td>
                        </template> </template
                    ></v-data-table>
                  </v-flex>
                </v-layout>
              </v-flex>
              <div style="width: 100%;" class="d-flex justify-space-between">
                <div class="flex-items-center justify-start">
                  <v-text-field
                    v-if="
                      selectedMainTable.PurchaseRequestDirectStatus == 'Pending'
                    "
                    v-model="xNote"
                    label="Catatan"
                    style="max-width: 300px;"
                    hide-details
                    outline
                    :disabled="!(Object.keys(selectedMainTable).length > 0)"
                  ></v-text-field>
                  <div
                    v-else-if="
                      selectedMainTable.PurchaseRequestDirectStatus ==
                      'Approved'
                    "
                    class="flex-items-center justify-start"
                  >
                    <span>Catatan :</span>
                    <span>{{
                      selectedMainTable.PurchaseRequestDirectNote == ""
                        ? "-"
                        : selectedMainTable.PurchaseRequestDirectNote
                    }}</span>
                  </div>
                </div>
                <div class="d-flex justify-end" style="gap: 0.5rem;">
                  <v-btn
                    color="error"
                    flat
                    dark
                    style="max-width: 100px;"
                    :disabled="
                      !(Object.keys(selectedMainTable).length > 0) ||
                      selectedMainTable.PurchaseRequestDirectStatus != 'Pending'
                    "
                    @click="
                      rejectRequest(
                        selectedMainTable.PurchaseRequestDirectID,
                        selectedMainTable.PurchaseRequestDirectStatus
                      )
                    "
                  >
                    Reject
                  </v-btn>
                  <v-btn
                    color="primary"
                    dark
                    style="max-width: 100px;"
                    :disabled="
                      !(Object.keys(selectedMainTable).length > 0) ||
                      selectedMainTable.PurchaseRequestDirectStatus != 'Pending'
                    "
                    @click="
                      approveRequest(
                        selectedMainTable.PurchaseRequestDirectID,
                        selectedMainTable.PurchaseRequestDirectStatus
                      )
                    "
                  >
                    Approve
                  </v-btn>
                </div>
              </div>
            </v-layout>
          </v-card-text>
        </v-card>
      </v-flex>
    </v-layout>

    <one-dialog-alert
      :status="dialogAlertRejectRequest"
      :msg="msgAlertDeleteOrReject"
      @forget-dialog-alert="dialogAlertRejectRequest = false"
      @close-dialog-alert="closeAndRejectRequest()"
    ></one-dialog-alert>

    <one-dialog-alert
      :status="dialogAlertDeleteDetail"
      :msg="msgAlertDeleteOrReject"
      @forget-dialog-alert="dialogAlertDeleteDetail = false"
      @close-dialog-alert="closeAndDeleteDetail()"
    ></one-dialog-alert>

    <v-layout row justify-center>
      <v-dialog v-model="dialogDetail" persistent max-width="500px">
        <v-card>
          <v-card-title class="headline grey lighten-2" primary-title>
            FORM EDIT REQUEST DETAIL
          </v-card-title>
          <v-card-text class="pt-0 pb-0">
            <v-form ref="formDetail" v-model="validationDetail" lazy-validation>
              <v-layout wrap>
                <v-flex xs12>
                  <v-text-field
                    v-model="xAmount"
                    type="number"
                    label="Jumlah"
                    :min="0"
                    :max="
                      selectedDetailTable.PurchaseRequestDirectDetailAmountRequest
                    "
                    :rules="amountRules"
                    required
                  ></v-text-field>
                </v-flex>
              </v-layout>
            </v-form>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="error" flat @click="closeDialogDetail()">
              Tutup
            </v-btn>
            <v-btn color="primary" dark @click="updateFormDetail()">
              Simpan Perubahan
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-layout>
  </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: {
      "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue"),
      "one-dialog-error": httpVueLoader("../../common/oneDialogError.vue"),
    },
    data() {
      return {
        msgAlertDeleteOrReject: "",
        dialogAlertRejectRequest: false,
        dialogAlertDeleteDetail: false,
        amountRules: [(v) => v >= 0 || "Jumlah harus diisi"],
        validationDetail: false,
        headers: [
          {
            text: "NO. PD",
            align: "center",
            sortable: false,
            value: "no",
            width: "15%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "TANGGAL",
            align: "left",
            sortable: false,
            value: "date",
            width: "30%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "KETERANGAN",
            align: "left",
            sortable: false,
            value: "description",
            width: "35%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "STATUS",
            align: "left",
            sortable: false,
            value: "status",
            width: "15%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "AKSI",
            align: "left",
            sortable: false,
            value: "action",
            width: "5%",
            class: "blue lighten-3 white--text",
          },
        ],
        detailHeaders: [
          {
            text: "NO",
            align: "center",
            sortable: false,
            value: "no",
            width: "5%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "KETERANGAN",
            align: "left",
            sortable: false,
            value: "requestDate",
            width: "35%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "JMLH REQUEST",
            align: "left",
            sortable: false,
            value: "requestDate",
            width: "15%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "JUMLAH",
            align: "left",
            sortable: false,
            value: "requestDate",
            width: "15%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "HARGA",
            align: "left",
            sortable: false,
            value: "requestDate",
            width: "25%",
            class: "blue lighten-3 white--text",
          },
          {
            text: "AKSI",
            align: "left",
            sortable: false,
            value: "action",
            width: "5%",
            class: "blue lighten-3 white--text",
          },
        ],
      };
    },
    mounted() {
      this.$store.dispatch("manager/search");
    },
    computed: {
      mainTable() {
        return this.$store.state.manager.mainTable;
      },
      detailTable() {
        return this.$store.state.manager.detailTable;
      },
      mainTableLoading() {
        return this.$store.state.manager.mainTableLoadingStatus === 1;
      },
      detailTableLoading() {
        return this.$store.state.manager.detailTableLoadingStatus === 1;
      },
      mainTableTotalPage: {
        get() {
          return this.$store.state.manager.countMainTable;
        },
        set(val) {
          this.$store.commit("manager/updateCountMainTable", val);
        },
      },
      mainTableCurrentPage: {
        get() {
          return this.$store.state.manager.mainTableCurrentPage;
        },
        set(val) {
          this.$store.commit("manager/updateMainTableCurrentPage", val);
          this.$store.commit("manager/updateMainTableLastId", -1);
          this.$store.dispatch("manager/search");
        },
      },
      selectedMainTable: {
        get() {
          return this.$store.state.manager.selectedMainTable;
        },
        set(val) {
          this.$store.commit("updateSelectedMainTable", val);
        },
      },
      selectedDetailTable: {
        get() {
          return this.$store.state.manager.selectedDetailTable;
        },
        set(val) {
          this.$store.commit("updateSelectedDetailTable", val);
        },
      },
      menuStartDate: {
        get() {
          return this.$store.state.manager.menuStartDate;
        },
        set(val) {
          this.$store.commit("manager/updateMenuStartDate", val);
        },
      },
      menuEndDate: {
        get() {
          return this.$store.state.manager.menuEndDate;
        },
        set(val) {
          this.$store.commit("manager/updateMenuEndDate", val);
        },
      },
      startDateFormatted() {
        return this.formatDate(this.fStartDate);
      },
      endDateFormatted() {
        return this.formatDate(this.fEndDate);
      },
      dStartDate: {
        get() {
          return this.$store.state.manager.dStartDate;
        },
        set(val) {
          this.$store.commit("manager/updateDStartDate", val);
        },
      },
      dEndDate: {
        get() {
          return this.$store.state.manager.dEndDate;
        },
        set(val) {
          this.$store.commit("manager/updateDEndDate", val);
        },
      },
      fStartDate: {
        get() {
          return this.$store.state.manager.fStartDate;
        },
        set(val) {
          this.$store.commit("manager/updateFStartDate", val);
        },
      },
      fEndDate: {
        get() {
          return this.$store.state.manager.fEndDate;
        },
        set(val) {
          this.$store.commit("manager/updateFEndDate", val);
        },
      },
      fStatus: {
        get() {
          return this.$store.state.manager.fStatus;
        },
        set(val) {
          this.$store.commit("manager/updateFStatus", val);
        },
      },
      statusOptions() {
        return this.$store.state.manager.statusOptions;
      },
      fSearch: {
        get() {
          return this.$store.state.manager.fSearch;
        },
        set(val) {
          this.$store.commit("manager/updateFSearch", val);
        },
      },
      xNote: {
        get() {
          return this.$store.state.manager.xNote;
        },
        set(val) {
          this.$store.commit("manager/updateXNote", val);
        },
      },
      xAmount: {
        get() {
          return this.$store.state.manager.xAmount;
        },
        set(val) {
          this.$store.commit("manager/updateXAmount", val);
        },
      },
      xPRID: {
        get() {
          return this.$store.state.manager.xPRID;
        },
        set(val) {
          this.$store.commit("manager/updateXPRID", val);
        },
      },
      xPRDID: {
        get() {
          return this.$store.state.manager.xPRDID;
        },
        set(val) {
          this.$store.commit("manager/updateXPRDID", val);
        },
      },
      xStatus: {
        get() {
          return this.$store.state.manager.xStatus;
        },
        set(val) {
          this.$store.commit("manager/updateXStatus", val);
        },
      },
      xDescriptionDetail: {
        get() {
          return this.$store.state.manager.xDescriptionDetail;
        },
        set(val) {
          this.$store.commit("manager/updateXDescriptionDetail", val);
        },
      },
      dialogDetail: {
        get() {
          return this.$store.state.manager.dialogDetail;
        },
        set(val) {
          this.$store.commit("manager/updateDialogDetail", val);
        },
      },
    },
    methods: {
      convertMoney(money){
          return one_money(money)
      },
      isSelected(p) {
        return (
          p.PurchaseRequestDirectNumber ==
          this.$store.state.manager.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")}`;
      },
      getChipStatusColor(status) {
        switch (status) {
          case "Pending":
            return "warning";
          case "Approved":
            return "success";
          case "Rejected":
            return "error";
          case "Completed":
            return "info";
          case "Paid":
            return "success";
          default:
            return "";
        }
      },
      getChipStatusDetailColor(status) {
        switch (status) {
          case "Pending":
            return "warning";
          case "Ordered":
            return "success";
          case "Received":
            return "info";
          case "Cancelled":
            return "error";
          default:
            return "warning";
        }
      },
      mainTableSearch() {
        this.$store.dispatch("manager/search");
        this.$store.commit("manager/updateSelectedMainTable", {});
        this.$store.commit("manager/updateDetailTable", []);
      },
      approveOrViewRequest(val) {
        this.$store.commit("manager/updateSelectedMainTable", val);
        this.$store.dispatch("manager/searchDetail");
        this.xNote = val.PurchaseRequestDirectNote;
      },
      updateDetail(val) {
        this.$store.commit(
          "manager/updateXAmount",
          val.PurchaseRequestDirectDetailAmount ??
            val.PurchaseRequestDirectDetailAmountRequest
        );
        this.$store.commit("manager/updateSelectedDetailTable", val);
        this.$store.commit("manager/updateDialogDetail", true);
      },
      closeDialogDetail() {
        this.$store.commit("manager/updateXAmount", 0);
        this.$refs.formDetail.resetValidation();
        this.$store.commit("manager/updateDialogDetail", false);
      },
      updateFormDetail() {
        if (this.$refs.formDetail.validate()) {
          this.$store.dispatch("manager/updateDetail", {
            PRID: this.selectedMainTable.PurchaseRequestDirectID,
            PRDID: this.selectedDetailTable.PurchaseRequestDirectDetailID,
            PRDDescription: this.selectedDetailTable
              .PurchaseRequestDirectDescription,
            PRDAmount: parseInt(this.xAmount),
          });
        }
      },
      rejectRequest(id, status) {
        this.xPRID = id;
        this.xStatus = status;

        this.msgAlertDeleteOrReject = `Yakin, mau Reject Purchase Request [${this.selectedMainTable.PurchaseRequestDirectNumber}] ?`;
        this.dialogAlertRejectRequest = true;
      },
      closeAndRejectRequest() {
        if (this.xStatus === "Pending") {
          this.$store.dispatch("manager/rejectRequest", {
            PRNumber: this.selectedMainTable.PurchaseRequestDirectNumber,
            PRID: this.xPRID,
          });
        }

        this.dialogAlertRejectRequest = false;
      },
      deleteDetail(data) {
        this.xPRID = data.PurchaseRequestDirectDetailPurchaseRequestDirectID;
        this.xPRDID = data.PurchaseRequestDirectDetailID;
        this.xDescriptionDetail = data.PurchaseRequestDirectDescription;

        this.msgAlertDeleteOrReject = `Yakin, mau hapus Request [${data.PurchaseRequestDirectDescription}] ?`;
        this.dialogAlertDeleteDetail = true;
      },
      closeAndDeleteDetail() {
        this.$store.dispatch("manager/deleteDetail", {
          PRID: this.xPRID,
          PRDDescription: this.xDescriptionDetail,
          PRDID: this.xPRDID,
        });
        this.dialogAlertDeleteDetail = false;
      },
      approveRequest(id, status) {
        this.xPRID = id;
        this.xStatus = status;

        this.detailTable.forEach((detail) => {
          if (!detail.PurchaseRequestDirectDetailAmount) {
            this.$store.dispatch("manager/updateDetail", {
              PRID: this.selectedMainTable.PurchaseRequestDirectID,
              PRDID: detail.PurchaseRequestDirectDetailID,
              PRDDescription: detail.PurchaseRequestDirectDescription,
              PRDAmount: parseInt(
                detail.PurchaseRequestDirectDetailAmountRequest
              ),
            });
          }
        });

        if (this.xStatus === "Pending") {
          this.$store.dispatch("manager/approveRequest", {
            PRID: this.xPRID,
            PRNumber: this.selectedMainTable.PurchaseRequestDirectNumber,
            PRNote: this.xNote,
          });
        }
      },
    },
    watch: {
      xAmount(val, old) {
        if (val <= 0) {
          this.$store.commit("manager/updateXAmount", 0);
        }
      },
    },
  };
</script>
