<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"
            >APPROVED PURCHASE REQUEST [ {{levelname}} ]</v-toolbar-title
          >
          <v-spacer></v-spacer>
        <v-btn v-if="(status != '' || status != null) && (xstartdate != '' && xstartdate != null)" @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">
          <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) }"
                    @click="selectMe(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) }"
                    @click="selectMe(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) }"
                    @click="selectMe(props.item)"
                  >
                    {{ props.item.PurchaseRequestDirectDescription }}
                  </td>
                  <td
                    class="text-xs-left pa-2"
                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                    @click="selectMe(props.item)"
                  >
                    <div class="date-type-table">
                      <span>
                        <span class="font-weight-medium"> Estimasi : </span>
                       Rp. {{props.item.PurchaseRequestDirectTotalEstimation.toString().replace(
                                  /\B(?=(\d{3})+(?!\d))/g,
                                  "."
                                )}} 
                      </span>
                      <span class="text-error">
                        <span class="font-weight-medium"> Realisasi : </span>
                        Rp. {{props.item.PurchaseRequestDirectTotalRealitation.toString().replace(
                                  /\B(?=(\d{3})+(?!\d))/g,
                                  "."
                                )}}
                        
                      </span>
                    </div>
                  </td>
                  <td
                    class="text-xs-left pa-2"
                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                    @click="selectMe(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-btn
                      style="min-width: 25px; height: 25px; margin: 0;"
                      v-if="props.item.PurchaseRequestDirectStatus == 'Pending'"
                      small
                      @click="approveOrViewRequest(props.item)"
                      color="black"
                      title="Edit"
                    >
                      <v-icon small color="white">edit</v-icon>
                    </v-btn>
                    <v-btn
                      style="min-width: 25px; height: 25px; margin: 0;"
                      v-if="
                        ['Approved', 'Paid', 'Completed'].includes(
                          props.item.PurchaseRequestDirectStatus
                        )
                      "
                      small
                      @click="approveOrViewRequest(props.item)"
                      color="blue"
                      title="Detail"
                    >
                      <v-icon small color="white">visibility</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),
                      }"
                    ></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">
                          <p class="mb-0">{{ props.item.PurchaseRequestDirectDescription }}</p>
                          <p class="mb-0 font-weight-bold" style="color:#000000">Kategori: {{ props.item.PurchaseDirectCategoryName }}</p>
                        </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">
                            <span v-if="props.item.isAttachemnt == true">
                                <v-btn
                                    style="min-width: 25px; height: 25px; margin: 0;"
                                    @click="openDialogPrevPay(props.item)"
                                    color="grey"
                                    title="Lihat nota pembayaran"
                                    small
                                >
                                 <v-icon small color="white">description</v-icon>
                                </v-btn>
                            </span>
                            <v-btn
                              style="min-width: 25px; height: 25px; margin: 0;"
                              @click="updateDetail(props.item)"
                              small title="Edit"
                              color="black"
                            >
                              <v-icon small color="white">edit</v-icon>
                            </v-btn>
                            <v-btn
                              style="min-width: 25px; height: 25px; margin: 0;"
                              @click="deleteDetail(props.item)"
                              color="red"
                              small title="Hapus"
                            >
                              <v-icon small color="white">delete</v-icon>
                            </v-btn>
                          </td>
                        </template>
                        <template v-else>
                          <td class="text-xs-center pa-2">
                            <span v-if="props.item.isAttachemnt == true">
                              <v-btn
                                style="min-width: 25px; height: 25px; margin: 0;"
                                @click="openDialogPrevPay(props.item)"
                                color="grey"
                                small title="Lihat nota pembayaran"
                              >

                              </v-btn>
                                <v-icon small color="white">description</v-icon>
                            </span>
                          </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"
                    v-if="
                      (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"
                    v-if="
                      (Object.keys(selectedMainTable).length > 0) &&
                      selectedMainTable.PurchaseRequestDirectStatus == 'Pending'
                    "
                    @click="
                      approveRequest(
                        selectedMainTable
                      )
                    "
                  >
                    Approve
                  </v-btn>
                  <v-btn
                    color="orange"
                    dark
                    style="max-width: 100px"
                    v-else-if="
                      (Object.keys(selectedMainTable).length > 0) &&
                      selectedMainTable.PurchaseRequestDirectStatus == 'Approved'
                    "
                    @click="
                      openUnapproveRequest(
                        selectedMainTable
                      )
                    "
                  >
                    Unapprove
                  </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> -->

    <template>
      <v-dialog v-model="dialogAlertDeleteDetail" 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>
                        {{ msgAlertDeleteRequest }}
                      </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="dialogAlertDeleteDetail = false">
              Tutup
            </v-btn>
            <v-btn
              color="primary"
              @click="closeAndDeleteDetail()"
            >
              Ya
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </template>

    <template>
      <v-dialog v-model="dialogAlertUnapprove" 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>
                        {{ msgAlertUnapproveRequest }}
                      </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="dialogAlertUnapprove = false">
              Tutup
            </v-btn>
            <v-btn
              color="primary"
              @click="closeAndUnapprove()"
            >
              Ya
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </template>

    <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-flex xs12>
                  <!-- <v-text-field
                  v-model="xPrice"
                  label="Harga"
                  type="number"
                  :min="1"
                  prefix="Rp "
                  :rules="priceRules"
                  required
                  :hint="convertMoney(xPrice)"
                ></v-text-field> -->
                  <v-text-field 
                    prefix="Rp"
                    v-model="formattedxPrice" 
                    label="Harga">
                  </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>

    <one-dialog-attachment></one-dialog-attachment>

    <template>
      <v-snackbar
          v-model="snackbar"
          :timeout="5000"
          :multi-line="false"
          :vertical="false"
          :top="true"
          color="orange"
          >
          {{ msgSnackbar }}
          <v-btn flat @click="updateAlertSuccess(false)"> Tutup </v-btn>
      </v-snackbar>
    </template>

    <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;
}

.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"),
    "one-dialog-info": httpVueLoader("../../common/oneDialogInfo.vue"),
    "one-dialog-attachment": httpVueLoader("./formDialogAttachtment.vue"),
  },
  data() {
    return {
      msgAlertDeleteOrReject: "",
      dialogAlertRejectRequest: false,
      dialogAlertDeleteDetail: false,
      dialogAlertUnapprove: false,
      msgAlertDeleteRequest: "",
      msgAlertUnapproveRequest: "",
      amountRules: [(v) => v >= 0 || "Jumlah harus diisi"],
      priceRules: [(v) => (!!v && v > 0) || "Harga harus diisi"],
      validationDetail: false,
      xStatusNota: "",
      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: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "KETERANGAN",
          align: "left",
          sortable: false,
          value: "description",
          width: "30%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "TOTAL",
          align: "left",
          sortable: false,
          value: "description",
          width: "15%",
          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: "center",
          sortable: false,
          value: "action",
          width: "10%",
          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: "30%",
          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: "20%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "AKSI",
          align: "center",
          sortable: false,
          value: "action",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
      ],
    };
  },
  mounted() {
    this.$store.dispatch("manager/getlevel");
    this.$store.dispatch("manager/search");
  },
  computed: {
    status() {
      return this.$store.state.manager.status;
    },
    xstartdate() {
      return this.$store.state.manager.xstartdate;
    },
    formattedxPrice: {
      get() {
          return this.oneMoney(this.xPrice);
      },
      set(value) {
          // Hilangkan titik dan koma, ubah jadi number
          let raw = value.replace(/\./g, '').replace(',', '.');
          this.xPrice = parseFloat(raw) || 0;
      }
    },
    mainTable() {
      return this.$store.state.manager.mainTable;
    },
    detailTable() {
      return this.$store.state.manager.detailTable;
    },
    levelname: {
      get() {
        return this.$store.state.manager.levelname;
      },
      set(val) {
        this.$store.commit("manager/updateLevelName", val);
      },
    },
    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);
      },
    },
    xPrice: {
      get() {
        return this.$store.state.manager.xPrice;
      },
      set(val) {
        this.$store.commit("manager/updatexPrice", 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);
      },
    },
    opendialoginfo: {
        get() {
            return this.$store.state.manager.open_dialog_info
        },
        set(val) {
            this.$store.commit("manager/update_open_dialog_info", val)
        }
    },
    msginfo: {
        get() {
            return this.$store.state.manager.msg_info
        },
        set(val) {
            this.$store.commit("manager/update_msg_info", val)
        }
    },
    snackbar: {
      get() {
        return this.$store.state.manager.alertSuccess;
      },
      set(val) {
        this.$store.commit("manager/updateAlertSuccess", val);
      },
    },
    msgSnackbar: {
      get() {
        return this.$store.state.manager.successMessage;
      },
      set(val) {
        this.$store.commit("manager/updateSuccessMessage", val);
      },
    },
  },
  methods: {
    updateAlertSuccess() {
      this.$store.commit("manager/updateAlertSuccess", false);
    },
    goBack() {
      window.history.back();
      // location.href = "/one-ui/test/vuex/one-accone-approve-all/"
    },
    roundToThreeSignificantDigits(num) {
      if (num === 0) return 0;
      
      // Hitung jumlah digit
      const absNum = Math.abs(num);
      const magnitude = Math.floor(Math.log10(absNum)) + 1;
      
      // Jika kurang dari 3 digit, tidak perlu dibulatkan
      if (magnitude <= 3) return num;
      
      // Hitung faktor pembulatan
      const factor = Math.pow(10, magnitude - 3);
      
      // Bulatkan
      return Math.round(num / factor) * factor;
    },
    oneMoney(value){
      //return one_money(value);
      let splitValue = value.toString().split(".");
      if(splitValue.length > 1) {
          let val = splitValue[0]
          return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".") + "," + this.roundToThreeSignificantDigits(splitValue[1]);
      } else {
          return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
      }
    },
    convertMoney(money){
        return one_money(money)
    },
    formatAngka(nilai) {
      // Jika tidak ada nilai
      if (!nilai) return '';
      
      try {
          // Ubah ke string
          let strNilai = String(nilai);
          
          // Jika berisi titik desimal
          if (strNilai.includes('.')) {
              // Split bagian utama dan desimal
              let bagian = strNilai.split('.');
              let utama = bagian[0];
              let desimal = bagian[1];
              
              // Format bagian utama
              utama = utama.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
              
              // Kembalikan gabungan
              return utama + ',' + desimal;
          } else {
              // Tidak ada desimal, hanya format bagian utama
              return strNilai.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
          }
      } catch (error) {
          console.error("Error formatting:", error);
          return nilai;
      }
    },
    isSelected(p) {
      return (
        p.PurchaseRequestDirectNumber ==
        this.$store.state.manager.selectedMainTable.PurchaseRequestDirectNumber
      );
    },
    selectMe(spr) {
      this.$store.commit("manager/updateSelectedMainTable", spr);
      this.$store.dispatch("manager/searchDetail");
    },
    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
      );
      let price = val.PurchaseRequestDirectDetailRealitationPrice === "0" ? val.PurchaseRequestDirectDetailEstimationPrice : val.PurchaseRequestDirectDetailRealitationPrice
      console.log('price')
      console.log(price)
      this.$store.commit("manager/updatexPrice",parseInt(price));
      this.$store.commit("manager/updateSelectedDetailTable", val);
      this.$store.commit("manager/updateDialogDetail", true);
    },
    closeDialogDetail() {
      this.$store.commit("manager/updateXAmount", 0);
      this.$store.commit("manager/updatexPrice", 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),
          PRDPrice: parseInt(this.xPrice)
        });
      }
    },
    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.msgAlertDeleteRequest = `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;
    },
    openUnapproveRequest(data) {
      this.xPRID = data.PurchaseRequestDirectID;
      this.xStatus = data.PurchaseRequestDirectStatus;

      this.msgAlertUnapproveRequest = `Yakin, mau unapprove Request [${data.PurchaseRequestDirectNumber}] ?`;
      this.dialogAlertUnapprove = true;
    },
    closeAndUnapprove() {
      if (this.xStatus === "Approved") {
        this.$store.dispatch("manager/unApproveRequest", {
          PRNumber: this.selectedMainTable.PurchaseRequestDirectNumber,
          PRID: this.xPRID,
        });
      }
      this.dialogAlertUnapprove = false;
    },
    approveRequest(val) {
      this.xPRID = val.PurchaseRequestDirectID;
      this.xStatus = val.PurchaseRequestDirectStatus;
      this.xStatusNota = val.PurchaseRequestDirectNotaStatus;

      if (this.xStatusNota == 'Pending') {
        this.opendialoginfo = true
        this.msginfo = "Bukti Pembayaran belum di approve, silahkan melakukan approve bukti pembayaran!"
      } else {
        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,
          });
        }
      }

    },
    openDialogPrevPay(val) {
      console.log('val', val)
      const fileBaseUrl = BASE_URL + "/one-media/cashier/";

      const allImageUrls = [];

      for (let index = 0; index < val.dataAttachment.length; index++) {
        const element = val.dataAttachment[index];

        allImageUrls.push(fileBaseUrl + element.PurchaseDirectAttachmentName)
      }

      this.$store.commit("manager/update_imagePreviews", allImageUrls);

      this.$store.commit("manager/update_dialog_form", true);
      this.$store.commit("manager/update_cekFile", false);
      this.$store.commit("manager/update_actAttach", 'preview');
    }
  },
  watch: {
    xAmount(val, old) {
      if (val <= 0) {
        this.$store.commit("manager/updateXAmount", 0);
      }
    },
    xPrice(val, old) {
      if (val <= 0) {
        this.$store.commit("manager/updatexPrice", 0);
      }
    },
  },
};
</script>
