<template>
    <v-dialog v-model="dialog_create_order" persistent width="80vw">
        <v-card class="style-card">
            <v-card-title class="headline grey lighten-2">
                {{ viewonlymode
                        ? "VIEW ORDER ASSET"
                        : selected_orderaset.PurchaseOrderID
                            ? "EDIT ORDER ASET"
                            : "BUAT ORDER ASET"
                }}
            </v-card-title>
            <template>
                <div class="style-content">
                    <v-stepper non-linear v-model="steps">
                        <v-stepper-header>
                            <v-stepper-step editable step="1" @click="steps = 1">
                                FORM ORDER ASET
                            </v-stepper-step>
                            <v-divider></v-divider>
                            <v-stepper-step editable step="2" @click="steps = 2">
                                FORM KONTRAK ASET
                            </v-stepper-step>
                            <v-divider></v-divider>
                            <v-stepper-step editable step="3" @click="steps = 3">
                                ITEM ORDER ASET
                            </v-stepper-step>
                        </v-stepper-header>

                        <v-stepper-items>
                            <v-stepper-content step="1">
                                <form-order-asset></form-order-asset>
                            </v-stepper-content>

                            <v-stepper-content step="2">
                                <form-kontrak-asset></form-kontrak-asset>
                            </v-stepper-content>

                            <v-stepper-content step="3">
                                <form-item-request-asset></form-item-request-asset>
                                <dialog-select-request-asset></dialog-select-request-asset>
                            </v-stepper-content>
                        </v-stepper-items>
                    </v-stepper>
                    <v-card-text>
                        <v-layout v-for="(item, index) in summary_items" :key="index"
                            row wrap align-center>
                                <v-flex xs2 pa-1>
                                    <strong>{{ item.label }}</strong>
                                </v-flex>
                                <v-flex grow></v-flex>
                                <v-flex xs2 pa-1 class="text-xs-right">
                                    <strong>Rp. {{ formatCurrency(item.value) }}</strong>
                                </v-flex>
                        </v-layout>
                    </v-card-text>
                </div>
            </template>
            <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn @click="batalOrderAsset()" color="error" class="white--text">Batal</v-btn>
                <v-btn :disabled="viewonlymode" @click="simpanOrderAsset()" color="primary" class="white--text">Simpan</v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<style scoped>
.style-card {
  max-height: 60vh;
  display: flex;
  flex-direction: column;
}

.style-content {
  overflow-y: auto;
  flex: 1 1 auto;
  min-height: 0;
}
</style>

<script>
module.exports = {
    data() {
        return {
            steps: 1
        }
    },
    components: {
        'form-order-asset': httpVueLoader('./form-order-asset.vue'),
        'form-kontrak-asset': httpVueLoader('./form-kontrak-asset.vue'),
        'form-item-request-asset': httpVueLoader('./form-item-request-asset.vue'),
        'dialog-select-request-asset': httpVueLoader('./dialog-select-request-asset.vue')
    },
    computed: {
        loading_process() {
            return this.$store.state.common.loading_process;
        },
        dialog_create_order: {
            get() {
                return this.$store.state.orderAsset.dialog_create_order
            },
            set(val) {
                this.$store.commit("orderAsset/update_dialog_create_order", val)
            }
        },
        form_kontrak: {
            get() {
                return this.$store.state.kontrakAsset.form_kontrak
            },
            set(val) {
                this.$store.commit("kontrakAsset/update_form_kontrak", val);
            }
        },
        form_order_asset: {
            get() {
                return this.$store.state.orderAsset.form_order_asset;
            },
            set(val) {
                this.$store.commit("orderAsset/update_form_order_asset", val);
            }
        },
        selected_request_asset: {
            get() {
                return this.$store.state.orderAsset.selected_request_asset
            },
            set(val) {
                this.$store.commit("orderAsset/update_selected_request_asset", val)
            }
        },
        summary_order: {
            get() {
                return this.$store.state.orderAsset.summary_order;
            },
            set(val) {
                this.$store.commit("orderAsset/update_summary_order", val);
            }
        },
        summary_items() {
            if (!this.summary_order) return [];
            return [
                {label: 'JUMLAH', value: this.summary_order.subtotal},
                {label: 'DISKON', value: this.summary_order.diskon},
                {label: 'PAJAK', value: this.summary_order.pajak},
                {label: 'DOWN PAYMENT', value: this.summary_order.downpayment},
                {label: 'TOTAL', value: this.summary_order.total}
            ]
        },
        viewonlymode() {
            return this.$store.state.common.viewonlymode;
        },
        selected_orderaset() {
            return this.$store.state.common.selected_orderaset;
        }
    },
    methods: {
        formatCurrency(value) {
            const num = parseFloat(value);
            if (isNaN(num)) return 0;
            return num.toFixed(2).replace('.', ',').replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        },
        parseCurrency(value) {
            let cleanValue = String(value).replace(/\./g, '');
            cleanValue = cleanValue.replace(',', '.');
            return parseFloat(cleanValue) || 0;
        },
        simpanOrderAsset() {
            if (!this.loading_process) {
                let formOrder = JSON.parse(JSON.stringify(this.form_order_asset));
                let formKontrak = JSON.parse(JSON.stringify(this.form_kontrak));
                let requestItem = JSON.parse(JSON.stringify(this.selected_request_asset));
                let summaryOrder = JSON.parse(JSON.stringify(this.summary_order));

                if (requestItem.length < 1) {
                    const snac = { color: 'warning', msg: 'Item masih kosong', state: true };
                    this.$store.commit("common/update_snackbar", snac);
                    return;
                }

                /* make sure the value is not in IDR format */
                formOrder.valuepajak = this.parseCurrency(formOrder.valuepajak);
                formOrder.valuediskon = this.parseCurrency(formOrder.valuediskon);
                formKontrak.besarNilai_cicilan = this.parseCurrency(formKontrak.besarNilai_cicilan);
                formKontrak.besarNilai_downpayment = this.parseCurrency(formKontrak.besarNilai_downpayment);

                requestItem.forEach(item => {
                    item.SupplierPrice = this.parseCurrency(item.SupplierPrice);
                    item.DiskonAmount = this.parseCurrency(item.DiskonAmount);
                });

                let param = {
                    ...formOrder,
                    assetAttachmentID: 0,
                    contractName: formKontrak.nama_kontrak,
                    contractDate: formKontrak.tanggal_kontrak,
                    contractStart: formKontrak.tanggalAwal_kontrak,
                    contractEnd: formKontrak.tanggalAkhir_kontrak,
                    contractDuration: formKontrak.durasi_cicilan,
                    installmentNumber: formKontrak.jumlah_cicilan,
                    installmentDate: formKontrak.tanggalBayar_cicilan,
                    installmentPayAmount: formKontrak.besarNilai_cicilan,
                    installmentDownPaymentType: formKontrak.type_downpayment,
                    installmentDownPayment: formKontrak.besarNilai_downpayment,
                    detail: requestItem,
                    summary: summaryOrder
                }

                if (!this.selected_orderaset.PurchaseOrderID) {
                    this.$store.dispatch("kontrakAsset/saveOrderAsset", param);
                } else {
                    param.PurchaseOrderID = this.selected_orderaset.PurchaseOrderID;
                    param.assetAttachmentID = this.selected_orderaset.assetAttachmentID,
                    param.SupplierDownpaymentID = this.selected_orderaset.SupplierDownpaymentID;
                    this.$store.dispatch("kontrakAsset/editOrderAsset", param);
                }
            } else {
                const snac = { color: 'warning', msg: 'Proses masih berjalan', state: true };
                this.$store.commit("common/update_snackbar", snac);
            }
        },
        batalOrderAsset() {
            this.form_order_asset = {
                podate: moment(new Date()).format('YYYY-MM-DD'),
                supplierID: "",
                reference: "",
                branchID: "",
                typepajak: "percent",
                valuepajak: 0,
                typediskon: "percent",
                valuediskon: 0
            };
            this.form_kontrak = {
                nama_kontrak: '',
                tanggal_kontrak: moment(new Date()).format('YYYY-MM-DD'),
                tanggalAwal_kontrak: moment(new Date()).format('YYYY-MM-DD'),
                tanggalAkhir_kontrak: moment(new Date()).format('YYYY-MM-DD'),
                durasi_cicilan: 1,
                jumlah_cicilan: 1,
                tanggalBayar_cicilan: 1,
                besarNilai_cicilan: 0,
                type_downpayment: 'percent',
                besarNilai_downpayment: 0
            };
            this.selected_request_asset = [];
            this.summary_order = {
                subtotal: 0,
                diskon: 0,
                pajak: 0,
                downpayment: 0,
                total_before_downpayment: 0,
                total: 0
            };

            this.$store.commit("common/update_viewonlymode", false);
            this.$store.commit('common/update_selected_orderaset', {});
            this.dialog_create_order = false;
        }
    }
}
</script>
