<template>
<v-dialog v-model="dialog_form_orderaset" persistent width="70vw">
    <v-card>
        <v-card-title class="headline grey lighten-2">FORM PO ASET</v-card-title>
        <v-card-text>
            <!-- first row -->
            <v-layout row wrap>
                <v-flex xs4>
                    <v-menu
                        v-model="menuPOdate" offset-y lazy min-width="290px" 
                        transition="scale-transition" max-width="290px" full-width
                        :nudge-right="40" :close-on-content-click="false"
                    >
                        <template v-slot:activator="{on}">
                            <v-text-field
                                v-model="formatPOdate" label="Tanggal PO" 
                                hide-details readonly v-on="on" outline
                            ></v-text-field>
                        </template>
                        <v-date-picker
                            v-model="form_orderaset.podate" no-title 
                            @input="menuPOdate = false"
                        ></v-date-picker>
                    </v-menu>
                </v-flex>
                <v-flex xs4 pl-2>
                    <v-autocomplete
                        :items="list_supplier" hide-details outline 
                        v-model="form_orderaset.supplierID" label="Vendor" 
                        item-text="SupplierName" item-value="SupplierID" 
                        @input="changeSupplierCabang()"
                    ></v-autocomplete>
                </v-flex>
                <v-flex xs4 pl-2>
                    <v-text-field
                        v-model="form_orderaset.reference" hide-details outline 
                        label="Referensi" placeholder="nomor request" readonly 
                    ></v-text-field>
                </v-flex>
            </v-layout>

            <!-- 2nd row -->
            <v-layout row wrap class="mt-2">
                <v-flex xs4>
                    <v-autocomplete
                        :items="list_branch" hide-details outline 
                        v-model="form_orderaset.branchcode" label="Cabang" 
                        item-text="M_BranchName" item-value="M_BranchCode" 
                        @input="changeSupplierCabang()"
                    ></v-autocomplete>
                </v-flex>
                <v-flex xs2 pl-2>
                    <v-autocomplete
                        :items="['absolute', 'percent']" label="Pajak (PPN)" 
                        v-model="form_orderaset.typepajak" hide-details 
                        @input="changeTypeTaxDiskon('tax')" outline 
                    ></v-autocomplete>
                </v-flex>
                <v-flex xs2 pl-2>
                    <v-text-field
                        v-if="form_orderaset.typepajak == 'percent'" label="Pajak" 
                        v-model="form_orderaset.valuepajak" hide-details outline 
                        placeholder="besar pajak dalam persen" suffix="%" 
                        @input="debounceCalcForm(form_orderaset)"
                    ></v-text-field>
                    <v-text-field
                        v-else label="Pajak" outline prefix="Rp."
                        v-model="form_orderaset.valuepajak" hide-details 
                        placeholder="besar pajak dalam rupiah" 
                        @input="debounceCalcForm(form_orderaset)"
                        @focus="handleFocus(form_orderaset, 'formtax')"
                        @blur="handleBlur(form_orderaset, 'formtax')"
                    ></v-text-field>
                </v-flex>
                <v-flex xs2 pl-2>
                    <v-autocomplete
                        :items="['absolute', 'percent']" hide-details 
                        v-model="form_orderaset.typediskon" label="Diskon" 
                        @input="changeTypeTaxDiskon('diskon')" outline 
                    ></v-autocomplete>
                </v-flex>
                <v-flex xs2 pl-2>
                    <v-text-field
                        v-if="form_orderaset.typediskon == 'percent'" label="Diskon" 
                        v-model="form_orderaset.valuediskon" hide-details outline 
                        placeholder="besar diskon dalam persen" suffix="%"
                        @input="debounceCalcForm(form_orderaset)"
                    ></v-text-field>
                    <v-text-field
                        v-else label="Diskon" outline prefix="Rp."
                        v-model="form_orderaset.valuediskon" hide-details 
                        placeholder="besar diskon dalam rupiah" 
                        @input="debounceCalcForm(form_orderaset)" 
                        @focus="handleFocus(form_orderaset, 'formdiskon')"
                        @blur="handleBlur(form_orderaset, 'formdiskon')"
                    ></v-text-field>
                </v-flex>
            </v-layout>

            <v-layout row wrap class="mt-2">
                <v-flex xs3>
                    <v-btn
                        block color="info" @click="addItemRequest()"
                        :disabled="form_orderaset.branchcode == '' || form_orderaset.supplierID == ''"
                    >TAMBAH ITEM</v-btn>
                </v-flex>
            </v-layout>

            <!-- table item -->
            <v-layout row wrap class="mt-2">
                <v-flex xs12 v-if="item_orderaset.length > 0">
                    <v-data-table
                        :headers="headers" :items="item_orderaset" :expand="expand"
                        item-key="M_ItemCode" class="elevation-1" hide-actions
                    >
                        <template v-slot:items="props">
                            <tr>
                                <td class="text-xs-center pa-2" 
                                    @click="props.expanded = !props.expanded"
                                >
                                    <v-icon>{{ props.expanded
                                        ? "keyboard_arrow_down"
                                        : "keyboard_arrow_right"
                                    }}</v-icon>
                                </td>
                                <td class="text-xs-center pa-2">
                                    {{ props.item.M_ItemDesc }}
                                </td>
                                <td class="text-xs-center pa-2">
                                    {{ props.item.RequestQty }}
                                </td>
                                <td class="text-xs-center pa-2">
                                    Rp. {{ formatCurrency(props.item.SupplierPrice) }}
                                </td>
                                <td class="text-xs-center pa-2">
                                    <v-layout row>
                                        <v-menu open-on-hover top offset-y attach>
                                            <v-btn slot="activator" color="primary" dark small>
                                                <span v-if="props.item.DiskonType == 'R'">Rp</span>
                                                <span v-else>%</span>
                                            </v-btn>

                                            <v-list>
                                                <v-list-tile
                                                    v-for="(name, index) in typedisc" :key="index"
                                                    @click="changeDiscountPerItem(name, props.item)"
                                                >
                                                    <v-list-tile-title>{{ name }}</v-list-tile-title>
                                                </v-list-tile>
                                            </v-list>
                                        </v-menu>
                                        <v-text-field
                                            v-if="props.item.DiskonType == 'R'" prefix="Rp." 
                                            v-model="props.item.DiskonAmount" hide-details 
                                            @input="debounceCalcItem(props.item)" solo 
                                            @focus="handleFocus(props.item, 'itemdiskon')"
                                            @blur="handleBlur(props.item, 'itemdiskon')"
                                        ></v-text-field>
                                        <v-text-field
                                            v-if="props.item.DiskonType == 'P'" suffix="%" min="0"
                                            v-model="props.item.DiskonAmount" hide-details solo
                                            @input="debounceCalcItem(props.item)" type="number"
                                        ></v-text-field>
                                    </v-layout>
                                </td>
                                <td class="text-xs-center pa-2">
                                    Rp. {{ formatCurrency(props.item.EndPrice) }}
                                </td>
                                <td class="text-xs-center pa-2">
                                    Rp. {{ formatCurrency(props.item.TempTotal) }}
                                </td>
                                <td class="text-xs-center pa-2">
                                    <v-btn
                                        color="red" dark @click="{}" 
                                        style="min-width: 40px; margin: 0;" small
                                    >
                                        <v-icon small>delete</v-icon>
                                    </v-btn>
                                </td>
                            </tr>
                        </template>
                        
                        <!-- expanded -->
                        <template v-slot:expand="props">
                            <v-card flat>
                                <v-card-text>
                                    <v-data-table
                                        :headers="headers_detail" class="elevation-0" 
                                        :items="props.item.detail" hide-actions
                                    >
                                        <template v-slot:items="detail">
                                        <tr>
                                            <td class="text-xs-center pa-2">
                                                {{ detail.item.M_ItemDesc }}
                                            </td>
                                            <td class="text-xs-center pa-2">
                                                {{ detail.item.PurchaseRequestNumber }}
                                            </td>
                                            <td class="text-xs-center pa-2">
                                                {{ detail.item.M_BranchName }}
                                            </td>
                                            <td class="text-xs-center pa-2">
                                                {{ detail.item.RequestQty }}
                                            </td>
                                            <td class="text-xs-center pa-2">
                                                {{ detail.item.ItemUnitName }}
                                            </td>
                                            <td class="text-xs-center pa-2">
                                                Rp. {{ formatCurrency(detail.item.SupplierPrice) }}
                                            </td>
                                            <td class="text-xs-center pa-2">
                                                <v-btn
                                                    color="red" flat @click="{}"
                                                    style="min-width: 40px; margin: 0;" small
                                                >
                                                    <v-icon>delete</v-icon>
                                                </v-btn>
                                            </td>
                                        </tr>
                                        </template>
                                    </v-data-table>
                                </v-card-text>
                            </v-card>
                        </template>

                        <!-- footer -->
                        <template v-slot:footer>
                            <tr>
                                <td colspan="1" class="text-xs-left pa-2"></td>
                                <td colspan="4" class="text-xs-left pa-2">
                                    <strong>JUMLAH</strong>
                                </td>
                                <td colspan="2" class="text-xs-right pa-2">
                                    <strong>
                                        Rp. {{ formatCurrency(summary_orderaset.subtotal) }}
                                    </strong>
                                </td>
                                <td colspan="1" class="text-xs-right pa-2"></td>
                            </tr>
                            <tr>
                                <td colspan="1" class="text-xs-left pa-2"></td>
                                <td colspan="4" class="text-xs-left pa-2">
                                    <strong>DISKON</strong>
                                </td>
                                <td colspan="2" class="text-xs-right pa-2">
                                    <strong>
                                        Rp. {{ formatCurrency(summary_orderaset.diskon) }}
                                    </strong>
                                </td>
                                <td colspan="1" class="text-xs-right pa-2"></td>
                            </tr>
                            <tr>
                                <td colspan="1" class="text-xs-left pa-2"></td>
                                <td colspan="4" class="text-xs-left pa-2">
                                    <strong>PAJAK</strong>
                                </td>
                                <td colspan="2" class="text-xs-right pa-2">
                                    <strong>
                                       Rp. {{ formatCurrency(summary_orderaset.pajak) }}
                                    </strong>
                                </td>
                                <td colspan="1" class="text-xs-right pa-2"></td>
                            </tr>
                            <tr>
                                <td colspan="1" class="text-xs-left pa-2"></td>
                                <td colspan="4" class="text-xs-left pa-2">
                                    <strong>TOTAL</strong>
                                </td>
                                <td colspan="2" class="text-xs-right pa-2">
                                    <strong>
                                        Rp. {{ formatCurrency(summary_orderaset.total) }}
                                    </strong>
                                </td>
                                <td colspan="1" class="text-xs-right pa-2"></td>
                            </tr>
                        </template>
                    </v-data-table>
                </v-flex>
            </v-layout>
        </v-card-text>

        <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn @click="batalOrder()" color="error" class="white--text">Batal</v-btn>
            <v-btn @click="simpanOrder()" color="primary" class="white--text">Simpan</v-btn>
        </v-card-actions>
    </v-card>
</v-dialog>
</template>

<script>
module.exports = {
    data() {
        return {
            menuPOdate: false,
            expand: false,
            headers: [
                {
                    text: "", align: "center", sortable: false,
                    value: "item", width: "5%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "ITEM", align: "center", sortable: false,
                    value: "item", width: "15%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "JUMLAH", align: "center", sortable: false,
                    value: "qty", width: "10%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "HARGA", align: "center", sortable: false,
                    value: "price", width: "15%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "DISKON", align: "center", sortable: false,
                    value: "disc", width: "20%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "HARGA SETELAH DISKON", align: "center", sortable: false,
                    value: "disc", width: "15%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "TOTAL", align: "center", sortable: false,
                    value: "disc", width: "15%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "AKSI", align: "center", sortable: false,
                    value: "disc", width: "5%", class: "pa-1 blue lighten-3 white--text",
                }
            ],
            headers_detail: [
                {
                    text: "NAMA PRODUK", align: "center", sortable: false,
                    value: "prod", width: "20%", class: "pa-1 blue lighten-4 black--text",
                },
                {
                    text: "NO REQUEST", align: "center", sortable: false,
                    value: "noreq", width: "20%", class: "pa-1 blue lighten-4 black--text",
                },
                {
                    text: "REQUESTER", align: "center", sortable: false,
                    value: "req", width: "20%", class: "pa-1 blue lighten-4 black--text",
                },
                {
                    text: "JUMLAH", align: "center", sortable: false,
                    value: "qty", width: "10%", class: "pa-1 blue lighten-4 black--text",
                },
                {
                    text: "UNIT", align: "center", sortable: false,
                    value: "unit", width: "10%", class: "pa-1 blue lighten-4 black--text",
                },
                {
                    text: "HARGA", align: "center", sortable: false,
                    value: "price", width: "15%", class: "pa-1 blue lighten-4 black--text",
                },
                {
                    text: "AKSI", align: "center", sortable: false,
                    value: "act", width: "5%", class: "pa-1 blue lighten-4 black--text",
                }
            ],
            typedisc: ["absolute", "percent"]
        }
    },
    computed: {
        dialog_form_orderaset: {
            get() {
                return this.$store.state.common.dialog_form_orderaset;
            },
            set(val) {
                this.$store.commit('common/update_dialog_form_orderaset', val);
            }
        },
        form_orderaset: {
            get() {
                return this.$store.state.common.form_orderaset;
            },
            set(val) {
                this.$store.commit('common/update_form_orderaset', val);
            }
        },
        item_orderaset: {
            get() {
                return this.$store.state.common.item_orderaset;
            },
            set(val) {
                this.$store.commit('common/update_item_orderaset', val);
            }
        },
        summary_orderaset: {
            get() {
                return this.$store.state.common.summary_orderaset
            },
            set(val) {
                this.$store.commit('common/update_summary_orderaset', val)
            }
        },
        formatPOdate() {
            return this.formatDate(this.form_orderaset.podate);
        },
        list_supplier() {
            return this.$store.state.common.list_supplier;
        },
        list_branch() {
            return this.$store.state.common.list_branch;
        }
    },
    methods: {
        formatDate(date) {
            if (!date) return null;
            const [year, month, day] = date.split('-');
            return `${day}-${month}-${year}`;
        },
        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 = 0;
            if (!isNaN(value)) {
                cleanvalue = value;
            } else {
                cleanvalue = String(value).replace(/\./g, '');
                cleanvalue = cleanvalue.replace(',', '.');
            }
            return parseFloat(cleanvalue) || 0;
        },
        handleFocus(item, type) {
            if (type == 'itemprice') {
                const currentval = item.SupplierPrice
                const parsedval = this.parseCurrency(currentval)
                item.SupplierPrice = parsedval
            }

            if (type == 'itemdiskon') {
                const currentdisc = item.DiskonAmount
                const parseddisc = this.parseCurrency(currentdisc)
                item.DiskonAmount = parseddisc
            }

            if (type == 'formdiskon') {
                const currdisc = item.valuediskon
                const formdisc = this.parseCurrency(currdisc)
                item.valuediskon = formdisc
            }

            if (type == 'formtax') {
                const currtax = item.valuepajak
                const formtax = this.parseCurrency(currtax)
                item.valuepajak = formtax
            }
        },
        handleBlur(item, type) {
            switch (type) {
                case 'itemprice':
                    const currentval = item.SupplierPrice
                    const parsedval = this.parseCurrency(currentval)
                    item.SupplierPrice = this.formatCurrency(parsedval)
                    break;
                case 'itemdiskon':
                    const currentdisc = item.DiskonAmount
                    const parseddisc = this.parseCurrency(currentdisc)
                    item.DiskonAmount = this.formatCurrency(parseddisc)
                    break;
                case 'formdiskon':
                    const currdisc = item.valuediskon
                    const formdisc = this.parseCurrency(currdisc)
                    item.valuediskon = this.formatCurrency(formdisc)
                    break;
                case 'formtax':
                    const currtax = item.valuepajak
                    const formtax = this.parseCurrency(currtax)
                    item.valuepajak = this.formatCurrency(formtax)
                    break;
                default:
                    break;
            }
        },
        changeSupplierCabang() {
            this.item_orderaset = []
            this.debounceCalcForm(this.form_orderaset)
        },
        changeTypeTaxDiskon(type) {
            let form = this.form_orderaset
            switch (type) {
                case 'tax':
                    form.valuepajak = 0
                    break;
                case 'diskon':
                    form.valuediskon = 0
                    break;
                case 'kontrak':
                    
                    break;            
                default:
                    break;
            }
            this.calculateFormSummary(form)
        },
        addItemRequest() {
            this.$store.dispatch('common/lookupOrderRequest', 'SR')
            this.$store.commit('common/update_dialog_add_itemaset', true)
        },
        changeDiscountPerItem(name, item) {
            switch (name) {
                case 'percent':
                    item.DiskonType = 'P'
                    item.DiskonAmount = 0.00
                    break;
                case 'absolute':
                    item.DiskonType = 'R'
                    item.DiskonAmount = 0.00
                    break;
                default:
                    break;
            }
            this.calculateItemSummary(item)
        },
        calculateItemSummary(item) {
            let current = JSON.parse(JSON.stringify(this.item_orderaset))
            let changed = current.find(ele => ele.M_ItemCode == item.M_ItemCode)

            const newqty = item.detail.reduce((sum, ele) => sum + Number(ele.RequestQty), 0)

            let itemprice = this.parseCurrency(changed.SupplierPrice)
            let currentdiskon = 0
            if (item.DiskonType == 'R') {
                currentdiskon = this.parseCurrency(changed.DiskonAmount)
            }

            if (item.DiskonType == 'P' && Number(changed.DiskonAmount) > 0) {
                let percent = Number(changed.DiskonAmount)
                currentdiskon = itemprice * percent / 100
            }

            changed.RequestQty = newqty
            changed.EndPrice = itemprice - currentdiskon
            changed.TempTotal = changed.EndPrice * changed.RequestQty

            this.item_orderaset = current

            /* update footer summary */ 
            let summary = JSON.parse(JSON.stringify(this.summary_orderaset))
            const subtotal = current.reduce((sum, acc) => sum + Number(acc.TempTotal), 0)
            summary.subtotal = subtotal
            this.summary_orderaset = summary

            this.calculateFormSummary(this.form_orderaset)
        },
        calculateFormSummary(form) {
            let summary = JSON.parse(JSON.stringify(this.summary_orderaset))

            /* calculate diskon value */ 
            let valuediskon = this.parseCurrency(form.valuediskon)
            if (form.typediskon == 'percent' && valuediskon > 0) {
                let percent = valuediskon
                let value = (summary.subtotal * percent) / 100
                summary.diskon = value
            } else {
                let absolute = valuediskon
                summary.diskon = absolute
            }

            /* calculate tax value */ 
            let valuepajak = this.parseCurrency(form.valuepajak)
            if (form.typepajak == 'percent' && valuepajak > 0) {
                let percent = valuepajak
                let value = (summary.subtotal - summary.diskon) * percent / 100
                summary.pajak = value
            } else {
                let absolute = valuepajak
                summary.pajak = absolute
            }

            summary.total = (summary.subtotal - summary.diskon) + summary.pajak
            this.summary_orderaset = summary
        },
        batalOrder() {

        },
        simpanOrder() {

        }
    },
    watch: {
        
    },
    created() {
        this.debounceCalcForm = _.debounce((form) => {
            this.calculateFormSummary(form)
        }, 500)
        this.debounceCalcItem = _.debounce((item) => {
            this.calculateItemSummary(item)
        }, 500)
    },
    destroyed() {
        this.debounceCalcItem = null
        this.debounceCalcForm = null
    },
}
</script>