<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 REQUEST DETAIL <span class="text-h6 font-weight-bold" v-if="act === 'edit'"> {{selectedMainTable.prNumber}}</span>
        </v-card-title>
        <v-card-text class="pt-0 pb-0">
          <v-form ref="formDetail" v-model="validationDetail" lazy-validtion>
            <v-layout wrap>
              <v-flex xs12>
                <v-text-field
                  v-model="xDescriptionDetail"
                  label="Deskripsi"
                  :rules="descriptionRules"
                  required
                ></v-text-field>
              </v-flex>
              <v-flex xs12>
                <v-text-field
                  v-model="xAmountRequest"
                  type="number"
                  label="Jumlah"
                  :min="1"
                  :rules="amountRules"
                  required
                ></v-text-field>
              </v-flex>
              <v-flex xs12>
                <v-autocomplete label="Item Unit" v-model="selected_item_unit"
                    :items="item_units" :search-input.sync="search_item_unit"
                    auto-select-first no-filter item-text="ItemUnitName"
                    return-object
                    no-data-text="Pilih Item Unit"
                    >
                    <template slot="item" slot-scope="{ item }">
                        <v-list-tile-content>
                            <v-list-tile-title v-text="item.ItemUnitName"></v-list-tile-title>
                        </v-list-tile-content>
                    </template>
                </v-autocomplete> 
              </v-flex>
              <v-flex xs12>
                <!-- <v-text-field
                  v-model="xEstimationPrice"
                  label="Harga"
                  type="number"
                  :min="1"
                  prefix="Rp "
                  :rules="priceRules"
                  required
                  :hint="convertMoney(xEstimationPrice)"
                ></v-text-field> -->
                <v-text-field 
                  v-model="xEstimationPrice" 
                  label="Harga"><template v-slot:append-outer>
                    <span class="text-h4 font-weight-bold">{{formatAngka(xEstimationPrice)}}</span>
                  </template>
                </v-text-field>
              </v-flex>
              <v-flex xs12>
                <!-- <v-text-field
                  v-model="total_price"
                  label="Total Harga"
                  type="number"
                  prefix="Rp "
                  readonly
                  :hint="convertMoney(total_price)"
                ></v-text-field> -->
                <v-text-field 
                  v-model="total_price" 
                  label="Total Harga"><template v-slot:append-outer>
                    <span class="text-h4 font-weight-bold">{{formatAngka(total_price)}}</span>
                  </template>
                </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 v-if="act === 'new'" color="primary" dark @click="saveDetail()"
            >Simpan</v-btn
          >
          <v-btn
            v-if="act === 'edit'"
            color="primary"
            dark
            @click="updateDetail()"
            >Simpan Perubahan</v-btn
          >
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-layout>
</template>

<script>
module.exports = {
  name: "AddRequestDetailDialog",
  data() {
    return {
      descriptionRules: [(v) => !!v || "Deskripsi harus diisi"],
      amountRules: [(v) => (!!v && v > 0) || "Jumlah harus diisi"],
      priceRules: [(v) => (!!v && v > 0) || "Harga harus diisi"],
      validationDetail: false,
    };
  },
  mounted() {
    this.$store.dispatch("requester/getUnit", this.search_item_unit)
  },
  computed: {
    selectedMainTable() {
      return this.$store.state.requester.selectedMainTable;
    },
    selectedDetailTable() {
      return this.$store.state.requester.selectedDetailTable;
    },
    xDescriptionDetail: {
      get() {
        return this.$store.state.requester.xDescriptionDetail;
      },
      set(val) {
        this.$store.commit("requester/updateXDescriptionDetail", val);
      },
    },
    xAmountRequest: {
      get() {
        return this.$store.state.requester.xAmountRequest;
      },
      set(val) {
        this.$store.commit("requester/updateXAmountRequest", val);
      },
    },
    xEstimationPrice: {
      get() {
        return this.$store.state.requester.xEstimationPrice;
      },
      set(val) {
        this.$store.commit("requester/updateXEstimationPrice", val);
      },
    },
    dialogDetail: {
      get() {
        return this.$store.state.requester.dialogDetail;
      },
      set(val) {
        this.$store.commit("requester/updateDialogDetail", val);
      },
    },
    act() {
      return this.$store.state.requester.act;
    },
    total_price() {
      return this.$store.state.requester.total_price;
    },
    item_units() {
      return this.$store.state.requester.item_units;
    },
    selected_item_unit: {
      get() {
        return this.$store.state.requester.selected_item_unit;
      },
      set(val) {
        this.$store.commit("requester/updateSelectedItemUnit", val);
      },
    },
    search_item_unit: {
      get() {
        return this.$store.state.requester.search_item_unit;
      },
      set(val) {
        this.$store.commit("requester/updateSearchItemUnit", val);
      },
    },
    act() {
      return this.$store.state.requester.act;
    },
  },
  methods: {
    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;
      }
    },
    closeDialogDetail() {
      this.$store.commit("requester/updateXDescriptionDetail", "");
      this.$store.commit("requester/updateXAmountRequest", 0);
      this.$store.commit("requester/updateXEstimationPrice", 0);
      this.$refs.formDetail.resetValidation();
      this.$store.commit("requester/updateDialogDetail", false);
    },
    saveDetail() {
      if (this.$refs.formDetail.validate()) {
        this.$store.dispatch("requester/saveDetail", {
          PRID: this.selectedMainTable.PurchaseRequestDirectID,
          PRDDescriptionDetail: this.xDescriptionDetail,
          PRDAmountRequest: this.xAmountRequest,
          PRDEstimationPrice: this.xEstimationPrice,
          PRDItemUnitID: this.selected_item_unit.ItemUnitID,
        });
      }
    },
    updateDetail() {
      if (this.$refs.formDetail.validate()) {
        this.$store.dispatch("requester/updateDetail", {
          PRID: this.selectedMainTable.PurchaseRequestDirectID,
          PRDID: this.selectedDetailTable.PurchaseRequestDirectDetailID,
          PRDDescriptionDetail: this.xDescriptionDetail,
          PRDAmountRequest: this.xAmountRequest,
          PRDEstimationPrice: this.xEstimationPrice,
          PRDItemUnitID: this.selected_item_unit.ItemUnitID,
        });
      }
    },
    calculateTotalPrice() {
      let total_price = this.xAmountRequest * this.xEstimationPrice;
      this.$store.commit("requester/updateTotalPrice", total_price);
    },
    thr_search_item_unit: _.debounce(function () {
        this.$store.dispatch("requester/getUnit", this.search_item_unit)
    }, 1000),
  },
  watch: {
    dialogDetail(val, old) {
      if (val) {
       // this.$refs.formDetail.reset();
       // this.$refs.formDetail.resetValidation();
      }
    },
    xAmountRequest(val, old) {
      if (val <= 0) {
        this.$store.commit("requester/updateXAmountRequest", 0);
      }
      this.calculateTotalPrice();
    },
    xEstimationPrice(val, old) {
      if (val < 0) {
        this.$store.commit("requester/updateXEstimationPrice", 0);
      }
      this.calculateTotalPrice();
    },
    search_item_unit(val, old) {
        if (val == old) return;
        if (!val) return;
        if (val.length < 1) return;
        if (this.$store.state.requester.loadingAutocomplete == 1) return;
        this.thr_search_item_unit();
    },
  },
};
</script>
