<template>
  <div>
    <v-dialog v-model="dialogDelete" persistent width="500">
      <v-card>
        <v-card-title class="headline grey lighten-2" primary-title>
          KONFIRMASI
        </v-card-title>

        <v-card-text>
          Apakah anda yakin untuk menghapus
          <span style="font-weight: bold;">{{
            selectedPO.PurchaseOrderNumber
          }}</span>
          ??
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="red" :disabled="loading" :loading="loading" flat @click="dialogDelete = false">
            Tidak
          </v-btn>
          <v-btn color="green" :disabled="loading" :loading="loading" flat @click="deletePO()">
            Ya
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="dialogConfirmation" persistent width="500">
      <v-card>
        <v-card-title class="headline grey lighten-2" primary-title>
          KONFIRMASI
        </v-card-title>

        <v-card-text>
          Apakah anda yakin untuk mengunci
          <span style="font-weight: bold;">{{
            selectedPO.PurchaseOrderNumber
          }}</span>
          untuk melanjutkan ke proses approve?
          <p style="font-style: italic;" class="mt-3">
            *Setelah dikunci PO tidak dapat di edit
          </p>
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="red" :disabled="loading" :loading="loading" flat @click="dialogConfirmation = false">
            Tidak
          </v-btn>
          <v-btn color="green" :disabled="loading" :loading="loading" flat @click="requestOrder()">
            Ya
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-snackbar v-model="snackbar.state" :color="snackbar.type" :timeout="6000" multi-line top>
      {{ snackbar.message }}
      <v-btn flat @click="snackbar.state = false">
        Close
      </v-btn>
    </v-snackbar>
    <v-toolbar color="primary" dark>
      <v-toolbar-title class="white--text">PURCHASE ORDER</v-toolbar-title>
      <v-spacer></v-spacer>
      <v-btn icon @click="openDialogAdd()">
        <v-icon>add_box</v-icon>
      </v-btn>
    </v-toolbar>
    <v-card>
      <v-layout row wrap class="px-2 py-2">
        <v-flex xs3>
          <v-menu v-model="menuSelectedDate" :close-on-content-click="false" transition="scale-transition"
            :nudge-right="40" lazy offset-y max-width="290px" min-width="290px">
            <template v-slot:activator="{ on }">
              <v-text-field :value="selectedDateFormatted" label="Tanggal Mulai" readonly class="mr-2"
                outline hide-details v-on="on"></v-text-field>
            </template>
            <v-date-picker no-title hide-details v-model="selectedDate"
              @input="menuSelectedDate = false"></v-date-picker>
          </v-menu>
        </v-flex>
        <v-flex xs3>
          <v-menu v-model="menuSelectedDateEnd" :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 class="mr-2" outline
                hide-details v-on="on"></v-text-field>
            </template>
            <v-date-picker no-title hide-details v-model="selectedDateEnd"
              @input="menuSelectedDateEnd = false"></v-date-picker>
          </v-menu>
        </v-flex>
        <v-flex xs3>
          <v-select :items="statusOptions" label="Status" hide-details class="mini-select mr-2" v-model="selectedStatus"
            item-text="title" return-object outline></v-select>
        </v-flex>
        <v-flex xs3>
          <v-text-field v-model="search" label="Cari..." placeholder="NO. PO" class="mr-2" outline hide-details>
          </v-text-field>
        </v-flex>
      </v-layout>
    </v-card>
    <v-card class="pa-2 mt-2">
      <div style="height: 60vh; overflow-y: scroll;">
        <v-data-table :headers="headers" :items="poList" :loading="loading" hide-actions class="elevation-1">
          <template v-slot:items="props">
            <td class="text-xs-center">{{ props.item.PurchaseOrderNumber }}</td>
            <td class="text-xs-center">{{ deFormatedDate(props.item.PurchaseOrderDate) }}</td>
            <td class="text-xs-left">{{ props.item.SupplierName }}</td>
            <td class="text-xs-center">
              <p class="my-0 p-0">
                <kbd>{{ props.item.PurchaseOrderWarehouseType }}</kbd>
              </p>
              <p class="my-0 p-0">
                {{ props.item.WarehouseName }}
              </p>
            </td>
            <td class="text-xs-left">{{ props.item.PurchaseOrderNote }}</td>
            <td class="text-xs-right">
              {{ props.item.PurchaseOrderGrandTotal != null ? oneMoney(props.item.PurchaseOrderGrandTotal) : '0' }}
            </td>

            <td class="text-xs-center">
              <v-chip color="blue" v-if="props.item.PurchaseOrderStatus === 'Draft'" text-color="white">{{
                props.item.PurchaseOrderStatus }}
              </v-chip>
              <v-chip color="warning" v-else-if="props.item.PurchaseOrderStatus === 'Pending'" text-color="white">{{
                props.item.PurchaseOrderStatus }}
              </v-chip>
              <v-chip color="green" v-else-if="props.item.PurchaseOrderStatus === 'Approved'" text-color="white">{{
                props.item.PurchaseOrderStatus }}
              </v-chip>
              <v-chip color="red" v-else-if="props.item.PurchaseOrderStatus === 'Rejected'" text-color="white">{{
                props.item.PurchaseOrderStatus }}
              </v-chip>
              <v-chip color="primary" v-else-if="props.item.PurchaseOrderStatus === 'Completed'" text-color="white">{{
                props.item.PurchaseOrderStatus }}
              </v-chip>
              <v-chip v-else text-color="white">{{ props.item.PurchaseOrderStatus }}
              </v-chip>
            </td>

            <td class="text-xs-center">
              <div v-if="props.item.PurchaseOrderStatus === 'Draft'" class="gap-0">
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-btn icon :disabled="loading" @click="openDialogConfirmation(props.item)" v-on="on" class="mx-0 px-0">
                      <v-icon color="blue">check_circle</v-icon>
                    </v-btn>
                  </template>
                  <span>Confirm PO</span>
                </v-tooltip>
                
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-btn icon :disabled="loading" @click="openDialogDelete(props.item)" v-on="on" class="mx-0 px-0">
                      <v-icon color="red">delete</v-icon>
                    </v-btn>
                  </template>
                  <span>Delete PO</span>
                </v-tooltip>
                
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-btn icon :disabled="loading || props.item.PurchaseOrderStatus !== 'Draft'" @click="openDialogEdit(props.item)" v-on="on" class="mx-0 px-0">
                      <v-icon color="blue">edit</v-icon>
                    </v-btn>
                  </template>
                  <span>Edit PO</span>
                </v-tooltip>
              </div>
              
              <div v-if="props.item.PurchaseOrderStatus !== 'Draft'">
                <!-- * Update 1 Juli 2025: * -->
                <!-- ** Approval dipisah ke halaman 'Approval PO' -->
                <!-- <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-btn icon :disabled="loading || props.item.PurchaseOrderStatus == 'Approved'"
                      @click="approvePO(props.item)" v-on="on" class="mx-0 px-0">
                      <v-icon color="green">done_all</v-icon>
                    </v-btn>
                  </template>
                  <span>Approve PO</span>
                </v-tooltip> -->
                
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-btn icon :disabled="loading" @click="openDialogView(props.item)" v-on="on" class="mx-0 px-0">
                      <v-icon color="blue">visibility</v-icon>
                    </v-btn>
                  </template>
                  <span>View PO</span>
                </v-tooltip>
                
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-btn icon :disabled="loading" @click="doPrint(props.item)" v-on="on" class="mx-0 px-0">
                      <v-icon color="red">picture_as_pdf</v-icon>
                    </v-btn>
                  </template>
                  <span>PDF PO</span>
                </v-tooltip>
              </div>
            </td>
          </template>
        </v-data-table>
      </div>
    </v-card>
    <v-card class="text-xs-left pa-2">
      <v-pagination v-model="selectedPage" :length="totalPage"></v-pagination>
    </v-card>
    <po-form></po-form>
    <po-view></po-view>
    <one-dialog-print :title="printtitle" :width="printwidth" :height="700" :status="openprint" :urlprint="urlprint"
      @close-dialog-print="openprint = false"></one-dialog-print>
  </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: {
    "po-form": httpVueLoader("./poForm.vue"),
    "po-view": httpVueLoader("./dialogView.vue"),
    'one-dialog-print': httpVueLoader('../../common/oneDialogPrintX.vue'),
  },
  data() {
    return {
      menuSelectedDate: false,
      menuSelectedDateEnd: false,
      msgAlertDeleteOrReject: "",
      dialogAlertRejectRequest: false,
      dialogAlertDeleteDetail: false,
      amountRules: [(v) => v >= 0 || "Jumlah harus diisi"],
      validationDetail: false,
      formatreport: "pdf",
      urlprint: "",
      printtitle: '',
      printwidth: '100%',
      headers: [
        {
          text: "NO PO",
          align: "center",
          sortable: false,
          value: "no",
          width: "5%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "TANGGAL",
          align: "center",
          sortable: false,
          value: "no",
          width: "5%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "VENDOR",
          align: "center",
          sortable: false,
          value: "no",
          width: "20%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "GUDANG",
          align: "center",
          sortable: false,
          value: "no",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "KETERANGAN",
          align: "center",
          sortable: false,
          value: "",
          width: "25%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "TOTAL",
          align: "center",
          sortable: false,
          value: "",
          width: "10%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "STATUS",
          align: "center",
          sortable: false,
          value: "",
          width: "10%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "AKSI",
          align: "center",
          sortable: false,
          value: "",
          width: "10%",
          class: "blue lighten-3 white--text",
        },
      ],
      detailHeaders: [
        {
          text: "KODE ITEM",
          align: "center",
          sortable: false,
          value: "no",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "NAMA ITEM",
          align: "left",
          sortable: false,
          value: "requestDate",
          width: "35%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "QTY",
          align: "left",
          sortable: false,
          value: "requestDate",
          width: "15%",
          class: "blue lighten-3 white--text",
        },
        {
          text: "HARGA",
          align: "left",
          sortable: false,
          value: "requestDate",
          width: "25%",
          class: "blue lighten-3 white--text",
        },
      ],
    };
  },
  mounted() {
    this.$store.dispatch("po/searchData");
    this.$store.dispatch("po/getItemCategory");
  },
  computed: {
    statusOptions() {
      return this.$store.state.po.statusOptions;
    },
    selectedDate: {
      get() {
        return this.$store.state.po.selectedDate;
      },
      set(val) {
        this.$store.commit("po/update_selectedDate", val);
        this.$store.dispatch("po/searchData");
      },
    },
    selectedStatus: {
      get() {
        return this.$store.state.po.selectedStatus;
      },
      set(val) {
        this.$store.commit("po/update_selectedStatus", val);
        this.$store.dispatch("po/searchData");
      },
    },
    statusOptions: {
      get() {
        return this.$store.state.po.statusOptions;
      },
      set(val) {
        this.$store.commit("po/update_statusOptions", val);
      },
    },
    selectedPO: {
      get() {
        return this.$store.state.po.selectedPO;
      },
      set(val) {
        this.$store.commit("po/update_selectedPO", val);
      },
    },
    dialogConfirmation: {
      get() {
        return this.$store.state.po.dialogConfirmation;
      },
      set(val) {
        this.$store.commit("po/update_dialogConfirmation", val);
      },
    },
    selectedDateEnd: {
      get() {
        return this.$store.state.po.selectedDateEnd;
      },
      set(val) {
        this.$store.commit("po/update_selectedDateEnd", val);
        this.$store.dispatch("po/searchData");
      },
    },

    search: {
      get() {
        return this.$store.state.po.search;
      },
      set(val) {
        this.$store.commit("po/update_search", val);
        this.$store.dispatch("po/searchData");
      },
    },
    selectedDateFormatted() {
      return this.formatDate(this.selectedDate);
    },
    endDateFormatted() {
      return this.formatDate(this.selectedDateEnd);
    },
    poList() {
      return this.$store.state.po.poList;
    },
    snackbar: {
      get() {
        return this.$store.state.po.snackbar;
      },
      set(val) {
        this.$store.commit("po/update_snackbar", val);
      },
    },
    totalPage: {
      get() {
        return this.$store.state.po.totalPage;
      },
      set(val) {
        this.$store.commit("po/update_totalPage", val);
      },
    },
    selectedPage: {
      get() {
        return this.$store.state.po.selectedPage;
      },
      set(val) {
        this.$store.commit("po/update_selectedPage", val);
        this.$store.dispatch("po/searchData");
      },
    },
    loading: {
      get() {
        return this.$store.state.po.loading;
      },
      set(val) {
        this.$store.commit("po/update_loading", val);
      },
    },
    dialogForm: {
      get() {
        return this.$store.state.po.dialogForm;
      },
      set(val) {
        this.$store.commit("po/update_dialogForm", val);
      },
    },
    dialogFormAct: {
      get() {
        return this.$store.state.po.dialogFormAct;
      },
      set(val) {
        this.$store.commit("po/update_dialogFormAct", val);
      },
    },
    dialogDelete: {
      get() {
        return this.$store.state.po.dialogDelete;
      },
      set(val) {
        this.$store.commit("po/update_dialogDelete", val);
      },
    },
    dialogView: {
      get() {
        return this.$store.state.po.dialogView;
      },
      set(val) {
        this.$store.commit("po/update_dialogView", val);
      },
    },
    openprint: {
      get() {
        return this.$store.state.po.open_print;
      },
      set(val) {
        this.$store.commit("po/update_open_print", val);
      },
    },
  },
  methods: {
    doPrint(val) {
      // console.log(val)
      this.printwidth = 1028
      this.printtitle = ""
      let user = one_user()
      tm = Date.now()
      var rptname = 'rpt_po_001'
      var formatrpt = this.formatreport

      this.urlprint = "/birt/run?__report=report/one/accounting/" + rptname + ".rptdesign&__format=" + formatrpt + "&PID=" + val.PurchaseOrderID + "&username=" + user.M_StaffName + "&tm=" + tm
      // console.log(this.urlprint)

      this.$store.commit("po/update_open_print", true)
    },
    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}`;
    },
    openDialogConfirmation(data) {
      this.selectedPO = data;
      this.dialogConfirmation = true;
    },
    openDialogDelete(data) {
      this.selectedPO = data;
      this.dialogDelete = true;
    },
    async requestOrder() {
      try {
        // First, update the backend
        await this.$store.dispatch("po/requestOrder");
        
        setTimeout(() => {
          window.location.reload();
        }, 1000); // Short delay to allow the snackbar to be visible
      } catch (error) {
        console.error("Error confirming order:", error);
        this.snackbar = {
          state: true,
          type: "error", 
          message: "Gagal mengkonfirmasi Purchase Order"
        };
      }
    },
    deletePO() {
      this.$store.dispatch("po/deleteOrder");
    },
    openDialogAdd() {
      this.$store.dispatch("po/resetForm");
      this.dialogForm = true;
    },
    openDialogView(data) {
      this.selectedPO = data;
      this.$store.dispatch("po/resetForm");
      this.dialogView = true;
      this.$store.dispatch("po/getItemUpdate");
    },
    openDialogEdit(data) {
      console.log("Open Dialog Edit dengan Param: ", JSON.parse(JSON.stringify(data)));
      this.selectedPO = data;
      this.dialogFormAct = "EDIT";
      this.dialogForm = true;
      this.$store.dispatch("po/assignEdit");
      this.$store.dispatch("po/getItemUpdate");
    },
    formatRupiah(angka) {
      const format = new Intl.NumberFormat("id-ID", {
        style: "currency",
        currency: "IDR",
        minimumFractionDigits: 0,
      });
      return "Rp " + format.format(angka).replace("Rp", "").trim();
    },
    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")}`;
    },
    approvePO(data) {
      if (data.PurchaseOrderID != '') {
        this.$store.dispatch("po/approveOrder", { poID: data.PurchaseOrderID });
      }
    }
  },
  watch: {
    dialogApprove(val, old) { },
  },
};
</script>
