<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"
            >PURCHASE REQUEST</v-toolbar-title
          >
          <v-spacer></v-spacer>
          <v-btn icon @click="openDialogRequest()">
            <v-icon>add_box</v-icon>
          </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)"
                  >
                  <div
                      style="
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                      "
                    >
                      {{ props.item.PurchaseRequestDirectDescription }}
                  </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>
                  <td
                    class="text-xs-left pa-2"
                    v-bind:class="{ 'amber lighten-4': isSelected(props.item) }"
                    @click="selectMe(props.item)"
                  >
                    Rp
                    {{
                      // props.item.PurchaseRequestDirectTotalEstimation.toString().replace(
                      //   /\B(?=(\d{3})+(?!\d))/g,
                      //   "."
                      // )
                      oneMoney(props.item.PurchaseRequestDirectTotalEstimation)
                    }}
                  </td>
                  <template
                    v-if="props.item.PurchaseRequestDirectStatus == 'Draft'"
                  >
                    <td
                      class="text-xs-center pa-2"
                      style="white-space: nowrap;"
                      v-bind:class="{
                        'amber lighten-4': isSelected(props.item),
                      }"
                    >
                      <v-btn
                        style="min-width: 25px; height: 25px; margin: 0;"
                        @click="updateRequest(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="deleteRequest(props.item)"
                        small title="Hapus"
                        color="red"
                      >
                        <v-icon small color="white">delete</v-icon>
                      </v-btn>
                    </td>
                  </template>
                  <template v-else>
                    <td
                      class="text-xs-center pa-2"
                      style="white-space: nowrap;"
                      v-bind:class="{
                        'amber lighten-4': isSelected(props.item),
                      }"
                    >
                      <v-btn
                        style="min-width: 25px; height: 25px; margin: 0;"
                        @click="printout(props.item)"
                        small title="Cetak PDF"
                        color="primary"
                      >
                        <v-icon small color="white">print</v-icon>
                      </v-btn>
                    </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 xs11>
                    <v-layout row wrap>
                      <v-flex xs12>
                        <div>
                          <span>No. PR : </span>
                          <span>{{
                            selectedMainTable.PurchaseRequestDirectNumber
                          }}</span>
                        </div>
                      </v-flex>
                      <v-flex xs12>
                        <div>
                          <span>Tanggal : </span>
                          <span>{{
                            deFormatedDate(
                              selectedMainTable.PurchaseRequestDirectDate
                            )
                          }}</span>
                        </div>
                      </v-flex>
                      <v-flex xs12>
                        <div>
                          <span>Keterangan : </span>
                          <span>{{
                            selectedMainTable.PurchaseRequestDirectDescription
                          }}</span>
                        </div>
                      </v-flex>
                    </v-layout>
                  </v-flex>
                  <v-flex xs1>
                    <v-btn
                      color="primary"
                      flat
                      icon
                      :disabled="
                        selectedMainTable.PurchaseRequestDirectStatus !==
                        'Draft'
                      "
                      @click="openDialogDetail()"
                    >
                      <v-icon medium>add_box</v-icon>
                    </v-btn>
                  </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">
                          <p class="mb-0">
                            {{
                              props.item.PurchaseRequestDirectDetailAmountRequest
                            }}/{{
                              props.item.PurchaseRequestDirectDetailAmount ?? 0
                            }}
                          </p>
                          <p class="mb-0 font-weight-bold" style="color:#000000">Satuan : {{ props.item.ItemUnitName }}</p>
                        </td>
                        <td class="text-xs-left pa-2">
                          Rp {{ oneMoney(props.item.PurchaseRequestDirectDetailEstimationPrice) }}
                          <!-- {{
                            props.item.PurchaseRequestDirectDetailEstimationPrice
                              .toString()
                              .replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                          }} -->
                        </td>
                        <td class="text-xs-left pa-2">
                          Rp {{ oneMoney(props.item.PurchaseRequestDirectDetailTotalEstimationPrice) }}
                          <!-- {{ (props.item.PurchaseRequestDirectDetailTotalEstimationPrice)
                              .toString()
                              .replace(/\B(?=(\d{3})+(?!\d))/g, ".")
                          }} -->
                        </td>
                        <td class="text-xs-left pa-2">
                          <v-chip
                            small
                            text-color="white"
                            :color="
                              getChipStatusDetailColor(
                                props.item.PurchaseRequestDirectDetailStatus
                              )
                            "
                            >{{
                              props.item.PurchaseRequestDirectDetailStatus
                            }}</v-chip
                          >
                        </td>
                        <template
                          v-if="
                            selectedMainTable.PurchaseRequestDirectStatus ===
                            'Draft'
                          "
                        >
                          <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-icon small color="white">description</v-icon>
                                </v-btn>
                            </span>
                            <!-- <span v-else-if="props.item.isAttachemnt == false">
                                <v-icon small color="green" @click="openDialogPay(props.item)">attachment</v-icon>
                            </span> -->
                            <v-btn
                                style="min-width: 25px; height: 25px; margin: 0;"
                                @click="openDialogPay(props.item)"
                                color="green"
                                small title="Upload nota pembayaran"
                            >
                              <v-icon small color="white">attachment</v-icon>
                            </v-btn>
                            <v-btn
                                style="min-width: 25px; height: 25px; margin: 0;"
                                @click="updateDetail(props.item)"
                                color="black"
                                small title="Edit"
                            >
                              <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-icon small color="white">description</v-icon>
                              </v-btn>
                            </span>
                            <!-- <span v-else-if="props.item.isAttachemnt == false">
                                <v-icon small color="green" @click="openDialogPay(props.item)">attachment</v-icon>
                            </span> -->
                            <v-btn
                                style="min-width: 25px; height: 25px; margin: 0;"
                                @click="openDialogPay(props.item)"
                                color="green"
                                small title="Upload nota pembayaran"
                            >
                              <v-icon small color="white">attachment</v-icon>
                            </v-btn>
                          </td>
                        </template>
                      </template>
                    </v-data-table>
                  </v-flex>
                </v-layout>
              </v-flex>
              <div style="width: 100%" class="d-flex justify-end">
                <template
                  v-if="
                    ['Draft', 'Pending'].includes(
                      selectedMainTable.PurchaseRequestDirectStatus
                    )
                  "
                >
                  <v-btn
                    color="primary"
                    dark
                    style="max-width: 200px"
                    class="ml-5"
                    :disabled="!detailTable.length"
                    @click="
                      orderRequest(
                        selectedMainTable.PurchaseRequestDirectID,
                        selectedMainTable.PurchaseRequestDirectStatus
                      )
                    "
                  >
                    {{
                      selectedMainTable.PurchaseRequestDirectStatus !== "Draft"
                        ? "Pending"
                        : "Request Purchase"
                    }}
                  </v-btn>
                </template>
              </div>
            </v-layout>
          </v-card-text>
        </v-card>
      </v-flex>
    </v-layout>

    <template>
      <v-dialog v-model="dialogAlertDeleteRequest" 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="dialogAlertDeleteRequest = false">
              Tutup
            </v-btn>
            <v-btn
              color="primary"
              @click="closeAndDeleteRequest()"
            >
              Ya
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </template>

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

    <add-purchase-request-dialog></add-purchase-request-dialog>
    <!-- <add-request-detail-dialog></add-request-detail-dialog> -->
    <form-add-request-detail-dialog></form-add-request-detail-dialog>
    <one-dialog-attachment></one-dialog-attachment>
    <one-dialog-print
      :title="printtitle"
      :width="printwidth"
      :height="600"
      :status="openprint"
      :urlprint="urlprint"
      @close-dialog-print="openprint = false"
    ></one-dialog-print>

    <!-- <one-dialog-alert
      :status="dialogAlertDeleteRequest"
      :msg="msgAlertDeleteRequest"
      @forget-dialog-alert="dialogAlertDeleteRequest = false"
      @close-dialog-alert="closeAndDeleteRequest()"
    ></one-dialog-alert>

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

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

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

.table.v-table thead tr {
  height: 40px;
}

.scroll-container {
  scroll-padding: 50px 0 0 50px;
}
</style>

<script>
module.exports = {
  components: {
    "add-purchase-request-dialog": httpVueLoader("./addPurchaseRequestDialog.vue"),
    "add-request-detail-dialog": httpVueLoader("./addRequestDetailDialog.vue"),
    "form-add-request-detail-dialog": httpVueLoader("./formAddRequestDetail.vue"),
    "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue"),
    "one-dialog-error": httpVueLoader("../../common/oneDialogError.vue"),
    "one-dialog-attachment": httpVueLoader("./formDialogAttachtment.vue"),
    "one-dialog-print": httpVueLoader("../../common/oneDialogPrintX.vue"),
  },
  data() {
    return {
      urlprint: "",
      printtitle: "",
      printwidth: "60%",
      openprint: false,
      msgAlertDeleteRequest: "",
      dialogAlertDeleteRequest: false,
      dialogAlertDeleteDetail: false,
      headers: [
        {
          text: "NO PD",
          align: "center",
          sortable: false,
          value: "no",
          width: "10%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "TANGGAL",
          align: "left",
          sortable: false,
          value: "requestDate",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "KETERANGAN",
          align: "left",
          sortable: false,
          value: "keterangan",
          width: "20%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "STATUS",
          align: "left",
          sortable: false,
          value: "status",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "TOTAL HARGA",
          align: "left",
          sortable: false,
          value: "total",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "AKSI",
          align: "center",
          sortable: false,
          value: "action",
          width: "15%",
          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: "20%",
          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: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "TOTAL HARGA",
          align: "left",
          sortable: false,
          value: "useDate",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "STATUS",
          align: "left",
          sortable: false,
          value: "status",
          width: "10%",
          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("requester/search");
  },
  computed: {
    mainTable() {
      return this.$store.state.requester.mainTable;
    },
    detailTable() {
      return this.$store.state.requester.detailTable;
    },
    mainTableLoading() {
      return this.$store.state.requester.mainTableLoadingStatus === 1;
    },
    detailTableLoading() {
      return this.$store.state.requester.detailTableLoadingStatus === 1;
    },
    mainTableTotalPage: {
      get() {
        return this.$store.state.requester.countMainTable;
      },
      set(val) {
        this.$store.commit("requester/updateCountMainTable", val);
      },
    },
    mainTableCurrentPage: {
      get() {
        return this.$store.state.requester.mainTableCurrentPage;
      },
      set(val) {
        this.$store.commit("requester/updateMainTableCurrentPage", val);
        this.$store.commit("requester/updateMainTableLastId", -1);
        this.$store.dispatch("requester/search");
      },
    },
    selectedMainTable: {
      get() {
        return this.$store.state.requester.selectedMainTable;
      },
      set(val) {
        this.$store.commit("updateSelectedMainTable", val);
      },
    },
    menuStartDate: {
      get() {
        return this.$store.state.requester.menuStartDate;
      },
      set(val) {
        this.$store.commit("requester/updateMenuStartDate", val);
      },
    },
    menuEndDate: {
      get() {
        return this.$store.state.requester.menuEndDate;
      },
      set(val) {
        this.$store.commit("requester/updateMenuEndDate", val);
      },
    },
    startDateFormatted() {
      return this.formatDate(this.fStartDate);
    },
    endDateFormatted() {
      return this.formatDate(this.fEndDate);
    },
    dStartDate: {
      get() {
        return this.$store.state.requester.dStartDate;
      },
      set(val) {
        this.$store.commit("requester/updateDStartDate", val);
      },
    },
    dEndDate: {
      get() {
        return this.$store.state.requester.dEndDate;
      },
      set(val) {
        this.$store.commit("requester/updateDEndDate", val);
      },
    },
    fStartDate: {
      get() {
        return this.$store.state.requester.fStartDate;
      },
      set(val) {
        this.$store.commit("requester/updateFStartDate", val);
      },
    },
    fEndDate: {
      get() {
        return this.$store.state.requester.fEndDate;
      },
      set(val) {
        this.$store.commit("requester/updateFEndDate", val);
      },
    },
    fStatus: {
      get() {
        return this.$store.state.requester.fStatus;
      },
      set(val) {
        this.$store.commit("requester/updateFStatus", val);
      },
    },
    statusOptions() {
      return this.$store.state.requester.statusOptions;
    },
    fSearch: {
      get() {
        return this.$store.state.requester.fSearch;
      },
      set(val) {
        this.$store.commit("requester/updateFSearch", val);
      },
    },
    xNumber: {
      get() {
        return this.$store.state.requester.xNumber;
      },
      set(val) {
        this.$store.commit("requester/updateXNumber", val);
      },
    },
    xPRID: {
      get() {
        return this.$store.state.requester.xPRID;
      },
      set(val) {
        this.$store.commit("requester/updateXPRID", val);
      },
    },
    xPRDID: {
      get() {
        return this.$store.state.requester.xPRDID;
      },
      set(val) {
        this.$store.commit("requester/updateXPRDID", val);
      },
    },
    snackbar: {
      get() {
        return this.$store.state.requester.alertSuccess;
      },
      set(val) {
        this.$store.commit("requester/updateAlertSuccess", val);
      },
    },
    msgSnackbar: {
      get() {
        return this.$store.state.requester.successMessage;
      },
      set(val) {
        this.$store.commit("requester/updateSuccessMessage", val);
      },
    },

  },
  methods: {
    // convertMoney(money){
    //     return one_money(money)
    // },
    roundToThreeSignificantDigits(digit) {
        // if (num === 0) return 0;
        
        // const absNum = Math.abs(num);
        // const magnitude = Math.floor(Math.log10(absNum)) + 1;
        // if (magnitude <= 3) return num;
        // const factor = Math.pow(10, magnitude - 3);
        // return Math.round(num / factor) * factor;

        const num = parseInt(digit, 10)
        if (isNaN(num) || num <= 0) {
            return '00';
        }

        const scale = 10 ** digit.length;
        const decimal = num / scale
        return Math.round(decimal * 100).toString();
    },
    oneMoney(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, ".");
        }
    },
    isSelected(p) {
      return (
        p.PurchaseRequestDirectNumber ==
        this.$store.state.requester.selectedMainTable
          .PurchaseRequestDirectNumber
      );
    },
    selectMe(spr) {
      this.$store.commit("requester/updateSelectedMainTable", spr);
      this.$store.dispatch("requester/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("requester/search");
      this.$store.commit("requester/updateSelectedMainTable", {});
      this.$store.commit("requester/updateDetailTable", []);
    },
    openDialogRequest() {
      let user = one_user()
      console.log('user')
      console.log(user)
      this.$store.commit("requester/updateRegionalOptions", user);
      this.$store.commit("requester/updateXRegional", user);
      this.$store.commit("requester/updateBranchOptions", user);
      this.$store.commit("requester/updateXBranch", user);
      this.$store.commit(
        "requester/updateXDateUse",
        moment(new Date()).format("YYYY-MM-DD")
      );
      this.$store.commit("requester/updateXDescription", "");
      this.$store.commit("requester/updateAct", "new");
      this.$store.commit("requester/updateDialogRequest", true);
    },
    updateRequest(val) {
      //this.$store.dispatch("requester/branch");
      this.$store.commit(
        "requester/updateXDateUse",
        val.PurchaseRequestDirectDateUse
      );

      console.log(val.M_BranchCode)
      this.$store.commit("requester/updateBranchOptions", {M_BranchCode : val.M_BranchCode, M_BranchName : val.M_BranchName});
      this.$store.commit("requester/updateXBranch",{M_BranchCode : val.M_BranchCode, M_BranchName : val.M_BranchName});
      this.$store.commit("requester/updateRegionalOptions", {S_RegionalID : val.S_RegionalID, S_RegionalName : val.S_RegionalName});
      this.$store.commit("requester/updateXRegional",{S_RegionalID : val.S_RegionalID, S_RegionalName : val.S_RegionalName});
      this.$store.commit(
        "requester/updateXDescription",
        val.PurchaseRequestDirectDescription
      );
      this.$store.commit("requester/updateXPRID", val.PurchaseRequestDirectID);
      this.$store.commit("requester/updateAct", "edit");
      this.$store.commit("requester/updateDialogRequest", true);
    },
    deleteRequest(data) {
      this.xPRID = data.PurchaseRequestDirectID;
      this.xNumber = data.PurchaseRequestDirectNumber;

      this.msgAlertDeleteRequest = `Yakin, mau hapus Purchase Request [${data.PurchaseRequestDirectNumber}] ?`;
      this.dialogAlertDeleteRequest = true;
    },
    closeAndDeleteRequest() {
      this.$store.dispatch("requester/deleteRequest", {
        PRID: this.xPRID,
        PRNumber: this.xNumber,
      });
      this.dialogAlertDeleteRequest = false;
    },
    openDialogDetail() {
      this.$store.commit("requester/updateXDescriptionDetail", "");
      this.$store.commit("requester/updateXAmountRequest", 0);
      this.$store.commit("requester/updateXEstimationPrice",0);
      this.$store.commit("requester/updateAct", "new");
      this.$store.commit("requester/updateDialogDetail", true);
      this.$store.commit("requester/updateSelectedItemUnit", {});
      this.$store.commit("requester/update_selected_category", {});
      this.$store.dispatch("requester/getUnit", this.$store.commit("requester/updateSearchItemUnit", ""))
      this.$store.dispatch("requester/getCategoryPD");
    },
    updateDetail(val) {
      this.$store.commit("requester/updateXDescriptionDetail", 
        val.PurchaseRequestDirectDescription
      );
      this.$store.commit("requester/updateXAmountRequest", 
        parseFloat(val.PurchaseRequestDirectDetailAmountRequest)
      );
      this.$store.commit("requester/updateXEstimationPrice", 
        parseFloat(val.PurchaseRequestDirectDetailEstimationPrice)
      );
      this.$store.commit("requester/updateTotalPrice", 
        parseFloat(val.PurchaseRequestDirectDetailTotalEstimationPrice)
      )
    
      this.$store.commit("requester/updateItemUnits", [{
        ItemUnitID: val.PurchaseRequestDirectDetailItemUnitID,
        ItemUnitName: val.ItemUnitName
      }]);
      this.$store.commit("requester/updateSelectedItemUnit", {
        ItemUnitID: val.PurchaseRequestDirectDetailItemUnitID,
        ItemUnitName: val.ItemUnitName
      });
      this.$store.dispatch("requester/getCategoryPD")
      this.$store.commit("requester/update_selected_category", {
        PurchaseDirectCategoryID: val.PurchaseRequestDirectDetailPurchaseRequestDirectCategoryID,
        PurchaseDirectCategoryCode: val.PurchaseDirectCategoryCode,
        PurchaseDirectCategoryName: val.PurchaseDirectCategoryName
      })
      
      this.$store.commit("requester/updateSelectedDetailTable", val);
      this.$store.commit("requester/updateAct", "edit");
      this.$store.commit("requester/updateDialogDetail", true);
    },
    deleteDetail(data) {
      this.xPRDID = data.PurchaseRequestDirectDetailID;

      this.msgAlertDeleteRequest = `Yakin, mau hapus Request [${data.PurchaseRequestDirectDescription}] ?`;
      this.dialogAlertDeleteDetail = true;
    },
    closeAndDeleteDetail() {
      this.$store.dispatch("requester/deleteDetail", {
        PRDID: this.xPRDID,
        PRDDescriptionDetail: this.xDescriptionDetail,
        PRID: this.selectedMainTable.PurchaseRequestDirectID,
      });
      this.dialogAlertDeleteDetail = false;
    },
    orderRequest(id, status) {
      if (status === "Draft") {
        this.$store.dispatch("requester/orderRequest", {
          PRID: id,
        });
      }
    },
    openDialogPay(val){
      this.$store.commit("requester/updateSelectedDetailTable", val);
      this.$store.commit("requester/update_dialog_form", true);
      this.$store.commit("requester/update_imageFiles", []);
      this.$store.commit("requester/update_imagePreviews", []);
      this.$store.commit("requester/update_cekFile", false);
      this.$store.commit("requester/update_actAttach", 'upload');
    },
    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("requester/update_imagePreviews", allImageUrls);

      this.$store.commit("requester/update_dialog_form", true);
      this.$store.commit("requester/update_cekFile", false);
      this.$store.commit("requester/update_actAttach", 'preview');
    },
    printout(val) {
      this.printwidth = "60%";
      this.printtitle = "";
      let user = one_user();
      let username = user && user.M_StaffName ? user.M_StaffName : "";
      let tm = Date.now();
      this.urlprint = BASE_URL + "/one-api/report/rpt_pr_direct/pdf?id=" + val.PurchaseRequestDirectID + "&username=" + username + "&tm=" + tm;
      this.openprint = true;
    }
  },
};
</script>
