<template>
  <div>
    <!-- Dialog View -->
    <v-dialog v-model="dialogView" persistent width="85vw">
      <v-card>
        <v-card-title class="headline grey lighten-2" primary-title>
          DETAIL PURCHASE ORDER {{ selectedPO.PurchaseOrderNumber ?? "" }}
        </v-card-title>

        <v-card-text>
          <v-layout row wrap class="px-2 py-2">
            <!-- HEADER PO VIEW -->
            <v-layout row wrap class="pa-0 ma-0">
              <!-- Tanggal -->
              <v-flex xs3>
                <div class="label-value subheading mb-2">
                  <span class="label">Nomor PO</span>
                </div>
              </v-flex>
              <v-flex xs9>
                <div class="label-value subheading mb-2">
                  <span class="value">: {{ selectedPO.PurchaseOrderNumber }}</span>
                </div>
              </v-flex>
              <!-- Tanggal -->
              <v-flex xs3>
                <div class="label-value subheading mb-2">
                  <span class="label">Tanggal</span>
                </div>
              </v-flex>
              <v-flex xs9>
                <div class="label-value subheading mb-2">
                  <span class="value">: {{ selectedPO.DisplayDate }}</span>
                </div>
              </v-flex>

              <!-- Nomor Referensi -->
              <v-flex xs3>
                <div class="label-value subheading mb-2">
                  <span class="label">Nomor Referensi</span>
                </div>
              </v-flex>
              <v-flex xs9>
                <div class="label-value subheading mb-2">
                  <span class="value">: {{ selectedPO.PurchaseOrderRefNumber }}</span>
                </div>
              </v-flex>

              <!-- Pajak Pendapatan (PPN) -->
              <v-flex xs3>
                <div class="label-value subheading mb-2">
                  <span class="label">Pajak Pendapatan (PPN):</span>
                </div>
              </v-flex>
              <v-flex xs9>
                <div class="label-value subheading mb-2">
                  <span v-if="selectedPO.PurchaseOrderTaxPpnType == 'P'" class="value">: {{ selectedPO.PurchaseOrderTaxPercentPpn }}%</span>
                  <span v-else-if="selectedPO.PurchaseOrderTaxPpnType == 'R'" class="value">: Rp {{ selectedPO.PurchaseOrderTaxAmountPpn }}</span>
                  <span v-else class="value">: -</span>
                </div>
              </v-flex>

              <!-- Pajak Penghasilan (PPH) -->
              <v-flex xs3>
                <div class="label-value subheading mb-2">
                  <span class="label">Pajak Penghasilan (PPH)</span>
                </div>
              </v-flex>
              <v-flex xs9>
                <div class="label-value subheading mb-2">
                  <span class="value">: {{ selectedPO.PurchaseOrderTaxPercentPph }}%</span>
                </div>
              </v-flex>

              <!-- Vendor -->
              <v-flex xs3>
                <div class="label-value subheading mb-2">
                  <span class="label">Vendor</span>
                </div>
              </v-flex>
              <v-flex xs9>
                <div class="label-value subheading mb-2">
                  <span class="label">: {{ selectedPO.SupplierCode }}
                    {{ selectedPO.SupplierName }}
                  </span>
                </div>
              </v-flex>

              <!-- Diskon Vendor -->
              <v-flex xs3>
                <div class="label-value subheading mb-2">
                  <span class="label">Diskon Vendor(Tipe Diskon)</span>
                </div>
              </v-flex>
              <v-flex xs9>
                <div class="label-value subheading mb-2">
                  <span v-if="selectedPO.DiscountType == 'Percentage'" class="label">: {{ selectedPO.PurchaseOrderDiscountPercent }}% (Percentage)</span>
                  <span v-if="selectedPO.DiscountType == 'Absolute'" class="label">: Rp {{ selectedPO.PurchaseOrderDiscountAmount }} (Absolut)</span>
                  <span v-if="selectedPO.DiscountType == ''" class="label">: - (-)</span>
                </div>
              </v-flex>

              <!-- Jangka Waktu Pembayaran -->
              <v-flex xs3>
                <div class="label-value subheading mb-2">
                  <span class="label">Jangka Waktu Pembayaran</span>
                </div>
              </v-flex>
              <v-flex xs9>
                <div class="label-value subheading mb-2">
                  <span class="value">: {{ selectedPO.PurchaseOrderPaymentTerm }} hari</span>
                </div>
              </v-flex>

              <!-- Tipe Gudang -->
              <v-flex xs3>
                <div class="label-value subheading mb-2">
                  <span class="label">Tipe Gudang</span>
                </div>
              </v-flex>
              <!-- Tipe Gudang -->
              <v-flex xs9>
                <div class="label-value subheading mb-2">
                  <span class="value">: {{ selectedPO.PurchaseOrderWarehouseType }}</span>
                </div>
              </v-flex>

              <!-- Gudang -->
              <v-flex xs3 v-if="selectedPO.PurchaseOrderWarehouseType === 'Single'">
                <div class="label-value subheading mb-2">
                  <span class="label">Gudang</span>
                </div>
              </v-flex>
              <v-flex xs9 v-if="selectedPO.PurchaseOrderWarehouseType === 'Single'">
                <div class="label-value subheading mb-2">
                  <span class="value">: {{ selectedPO.WarehouseName }}</span>
                </div>
              </v-flex>

              <!-- Keterangan -->
              <v-flex xs3>
                <div class="label-value subheading mb-2">
                  <span class="label">Biaya Ekspedisi</span>
                </div>
              </v-flex>
              <v-flex xs9>
                <div class="label-value subheading mb-2">
                  <span class="value">: {{ selectedPO && selectedPO.PurchaseOrderShippingCost != null
                    ? oneMoney(selectedPO.PurchaseOrderShippingCost) : '0' }}
                    <span v-if="selectedPO.PurchaseOrderShippingCostStatus === 'Y'">Sudah dibayar
                    </span>
                    <span v-if="selectedPO.PurchaseOrderShippingCostStatus === 'N'">Belum dibayar
                    </span>
                  </span>
                </div>
              </v-flex>

              <!-- Keterangan -->
              <v-flex xs3>
                <div class="label-value subheading mb-2">
                  <span class="label">Keterangan</span>
                </div>
              </v-flex>
              <v-flex xs9>
                <div class="label-value subheading mb-2">
                  <span class="value">: {{ selectedPO.PurchaseOrderNote }}</span>
                </div>
              </v-flex>
            </v-layout>

            <!-- TABEL ITEM VIEW -->
            <v-flex xs12>
              <v-data-table v-if="summary.length > 0" :headers="summaryHeaders" :items="summary" :loading="loading"
                hide-actions class="elevation-1 mt-4" expand item-key="M_ItemID">
                
                <!-- Tabel Item -->
                <template slot="items" slot-scope="props">
                  <tr @click="props.expanded = !props.expanded">
                    <td class="text-xs-center">
                      <v-icon>{{
                        props.expanded
                          ? "keyboard_arrow_down"
                          : "keyboard_arrow_right"
                      }}</v-icon>
                    </td>
                    <td class="">
                      <kbd>{{ props.item.M_ItemCode }}</kbd>
                      {{ props.item.M_ItemDesc }}
                    </td>

                    <td class="text-xs-center">
                      {{ props.item.TotalPoQty }} {{ props.item.PoItemUnitName }}
                    </td>
                    <td class="text-xs-center">
                      {{ oneMoney(props.item.RealPrice) }}
                    </td>
                    <td class="text-xs-right">
                      <div v-if="props.item.discountType === 'R'">
                        {{ oneMoney(props.item.discount) }}
                      </div>
                      <div v-if="props.item.discountType === 'P'">
                        <kbd>{{ props.item.discount }}%</kbd>
                        {{ oneMoney(props.item.summaryDiscountAmount) }}
                      </div>
                    </td>
                    <td class="text-xs-right">
                      {{ oneMoney(props.item.Price) }}
                    </td>
                    <td class="text-xs-right">
                      {{ oneMoney(props.item.Total) }}
                    </td>
                  </tr>
                </template>

                <!-- Detail per Baris Item -->
                <template slot="expand" slot-scope="props">
                  <v-card flat>
                    <v-card-text class="pl-3">
                      <div class="ml-3 mb-3">
                        <v-data-table :headers="detailHeaders" :items="props.item.Details" hide-actions
                          class="elevation-0">
                          <template slot="items" slot-scope="detailProps">
                            <td class="">
                              <kbd>{{ detailProps.item.M_ItemCode }}</kbd>

                              {{ detailProps.item.M_ItemDesc }}
                            </td>
                            <td class="">
                              {{
                                detailProps.item.PurchaseRequestNumber
                              }}
                            </td>
                            <td class="">
                              {{
                                detailProps.item.M_BranchName ??
                                detailProps.item.S_RegionalName
                              }}
                            </td>
                            <td class="py-1">
                              {{ detailProps.item.warehouse.WarehouseName }}
                            </td>
                            <td class="text-xs-center">
                              {{ detailProps.item.PoQty }}
                              {{ detailProps.item.PoItemUnitName }}
                            </td>
                          </template>
                        </v-data-table>
                      </div>
                    </v-card-text>
                  </v-card>
                </template>

                <!-- Tabel di bawah Item -->
                <template v-slot:footer>
                  <tr>
                    <td :colspan="4">
                      <strong class="ml-2">TOTAL HARGA TANPA DISKON</strong>
                    </td>
                    <td :colspan="3" class="text-xs-right">
                      <strong>{{
                        selectedPO && selectedPO.TotalRealPrice != null
                          ? oneMoney(selectedPO.TotalRealPrice) : '0'
                      }}</strong>
                    </td>
                  </tr>
                  <tr>
                    <td :colspan="4">
                      <strong class="ml-2">TOTAL DISKON PER ITEM</strong>
                    </td>
                    <td :colspan="3" class="text-xs-right">
                      <strong>{{
                        selectedPO && selectedPO.TotalDiskonPerItem != null
                          ? oneMoney(selectedPO.TotalDiskonPerItem) : '0'
                      }}</strong>
                    </td>
                  </tr>
                  <tr>
                    <td :colspan="4">
                      <strong class="ml-2">DISKON VENDOR</strong>
                    </td>
                    <td :colspan="3" class="text-xs-right">
                      <strong>{{
                        selectedPO && selectedPO.DiscountAmount != null
                          ? oneMoney(selectedPO.DiscountAmount) : '0'
                      }}</strong>
                    </td>
                  </tr>
                  <tr>
                    <td :colspan="4">
                      <strong class="ml-5">PAJAK PENDAPATAN(PPN)</strong>
                    </td>
                    <td :colspan="3" class="text-xs-right">
                      <strong>{{
                        selectedPO && selectedPO.PurchaseOrderTaxAmountPpn != null
                          ? oneMoney(selectedPO.PurchaseOrderTaxAmountPpn) : '0'
                      }}</strong>
                    </td>
                  </tr>
                  <tr>
                    <td :colspan="4">
                      <strong class="ml-5">PAJAK PENGHASILAN(PPH)</strong>
                    </td>
                    <td :colspan="3" class="text-xs-right">
                      <strong>{{
                        selectedPO && selectedPO.PurchaseOrderTaxAmountPph != null
                          ? oneMoney(selectedPO.PurchaseOrderTaxAmountPph) : '0'
                      }}</strong>
                    </td>
                  </tr>
                  <tr>
                    <td :colspan="4">
                      <strong class="ml-2">PAJAK</strong>
                    </td>
                    <td :colspan="3" class="text-xs-right">
                      <strong>{{ selectedPO && selectedPO.TaxAmount != null
                        ? oneMoney(selectedPO.TaxAmount) : '0' }}</strong>
                    </td>
                  </tr>
                  <tr>
                    <td :colspan="4">
                      <strong>TOTAL</strong>
                    </td>
                    <td :colspan="3" class="text-xs-right">
                      <strong>{{
                        selectedPO && selectedPO.PurchaseOrderGrandTotal != null
                          ? oneMoney(selectedPO.PurchaseOrderGrandTotal) : '0'
                      }}</strong>
                    </td>
                  </tr>
                </template>
              </v-data-table>
            </v-flex>
          </v-layout>
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="green" flat @click="dialogView = false">
            TUTUP
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
module.exports = {
  data() {
    return {
      selectedDateForm: null,
      refNumber: "",
      taxPpn: 0,
      taxPph: 0,
      selectedSupplier: {},
      paymentTerm: 0,
      warehouseType: "",
      selectedWarehouse: {},
      note: "",
      selectedItem: [],
      detailHeaders: [
        // {
        //   text: "KODE ITEM",
        //   align: "center",
        //   sortable: false,
        //   value: "M_ItemCode",
        //   width: "15%",
        //   class: "blue lighten-4 black--text",
        // },
        {
          text: "NAMA PRODUK",
          align: "center",
          sortable: false,
          value: "M_ItemDesc",
          width: "20%",
          class: "blue lighten-4 black--text",
        },
        {
          text: "PR NUMBER",
          align: "center",
          sortable: false,
          value: "M_ItemDesc",
          width: "10%",
          class: "blue lighten-4 black--text",
        },
        {
          text: "CABANG",
          align: "center",
          sortable: false,
          value: "M_BranchName",
          width: "20%",
          class: "blue lighten-4 black--text",
        },
        {
          text: "GUDANG",
          align: "center",
          sortable: false,
          value: "M_BranchName",
          width: "30%",
          class: "blue lighten-4 black--text",
        },
        // {
        //   text: "UNIT",
        //   align: "center",
        //   sortable: false,
        //   value: "ItemUnitName",
        //   width: "10%",
        //   class: "blue lighten-4 black--text",
        // },
        {
          text: "QTY",
          align: "center",
          sortable: false,
          value: "PoQty",
          width: "15%",
          class: "blue lighten-4 black--text",
        },
      ],
      summaryHeaders: [
        {
          text: "",
          align: "center",
          sortable: false,
          value: "expand",
          width: "5%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "ITEM",
          align: "center",
          sortable: false,
          value: "M_ItemCode",
          width: "10%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "QTY",
          align: "center",
          sortable: false,
          value: "PoQty",
          width: "10%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "HARGA",
          align: "center",
          sortable: false,
          value: "price",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "DISKON",
          align: "center",
          sortable: false,
          value: "price",
          width: "20%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "HARGA SETELAH DISKON",
          align: "center",
          sortable: false,
          value: "price",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "TOTAL",
          align: "center",
          sortable: false,
          value: "Total",
          width: "20%",
          class: "blue lighten-3 white--text",
        },
      ],
    };
  },
  computed: {
    statusOptions() {
      return this.$store.state.po.statusOptions;
    },
    dialogView: {
      get() {
        return this.$store.state.po.dialogView;
      },
      set(val) {
        this.$store.commit("po/update_dialogView", val);
      },
    },
    selectedPO: {
      get() {
        return this.$store.state.po.selectedPO;
      },
      set(val) {
        this.$store.commit("po/update_selectedPO", val);
      },
    },
    summary: {
      get() {
        return this.$store.state.po.summary;
      },
      set(val) {
        this.$store.commit("po/update_summary", val);
      },
    },
    loading: {
      get() {
        return this.$store.state.po.loading;
      },
      set(val) {
        this.$store.commit("po/update_loading", val);
      },
    },
  },
  methods: {
    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, ".");
      // }
      // Ubah ke float jika belum angka
      if (typeof value !== 'number') {
        value = parseFloat(value);
      }

      if (isNaN(value)) return '0,00';

      // Bulatkan dulu ke 2 desimal
      const fixed = value.toFixed(2); // hasil string, misal "16200000.00" atau "123456.70"
      const splitValue = fixed.split(".");

      const val = splitValue[0];       // bagian ribuan
      const decimal = splitValue[1];   // bagian desimal

      const formatted = val.replace(/\B(?=(\d{3})+(?!\d))/g, ".");

      return `${formatted},${decimal}`;
    },
    formatDate(date) {
      if (!date) return null;

      const [year, month, day] = date.split("-");
      return `${day}-${month}-${year}`;
    },
    formatRupiah(angka) {
      const format = new Intl.NumberFormat("id-ID", {
        style: "currency",
        currency: "IDR",
        minimumFractionDigits: 0,
      });
      return "Rp " + format.format(angka).replace("Rp", "").trim();
    },
  },
};
</script>

<style scoped>
.label-value subheading mb-2 {
  display: flex;
  flex-direction: column;
  margin-bottom: 1rem;
}

.label {
  font-weight: bold;
  margin-bottom: 0.25rem;
}

.value {
  font-size: 1rem;
}
</style>
