<template>
    <v-dialog v-model="dialog_add_itemaset" persistent width="60vw">
        <v-card>
            <v-card-title class="headline grey lighten-2" primary title>
                TAMBAH REQUEST ASET
            </v-card-title>
            <v-card-text>
                <v-layout row wrap>
                    <v-flex xs12>
                        <v-text-field
                            v-model="keyword" hide-details outline 
                            label="cari" placeholder="nomor request aset"
                        ></v-text-field>
                    </v-flex>
                    <v-flex xs12 mt-2>
                        <v-data-table
                            :headers="headers" :items="list_requestaset.records" 
                            v-model="temp_selectedrequest" item-key="PurchaseRequestDetailID" 
                            class="elevation-1" hide-actions :loading="loading"
                        >
                            <template v-slot:headers="props">
                                <tr>
                                    <th class="blue lighten-3 white--text" style="width: 10%;">
                                        <v-checkbox
                                            :input-value="props.all" primary 
                                            :indeterminate="props.indeterminate"
                                            @click.native="toggleAll" hide-details
                                        ></v-checkbox>
                                    </th>
                                    <th v-for="header in props.headers" :key="header.text"
                                        :class="header.class" :style="{ width: header.width }"
                                    >{{ header.text }}</th>
                                </tr>
                            </template>
                            <template v-slot:items="props">
                                <tr>
                                    <td>
                                        <v-checkbox 
                                            v-model="props.selected" 
                                            primary hide-details
                                        ></v-checkbox>
                                    </td>
                                    <td class="text-xs-center pa-2">
                                        {{ props.item.PurchaseRequestNumber }}
                                    </td>
                                    <td class="text-xs-center pa-2">
                                        {{ props.item.M_ItemCode }}
                                    </td>
                                    <td class="text-xs-center pa-2">
                                        {{ props.item.M_ItemDesc }}
                                    </td>
                                    <td class="text-xs-center pa-2">
                                        {{ props.item.ItemUnitName }}
                                    </td>
                                    <td class="text-xs-center pa-2">
                                        {{ props.item.RequestQty }}
                                    </td>
                                </tr>
                            </template>
                        </v-data-table>
                    </v-flex>
                </v-layout>
            </v-card-text>
            <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn class="white--text" color="error" @click="batalrequest()">Batal</v-btn>
                <v-btn class="white--text" color="primary" @click="simpanrequest()">Simpan</v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script>
module.exports = {
    data() {
        return {
            keyword: "",
            loading: false,
            temp_selectedrequest: [],
            headers: [
                {
                    text: "NO PURCHASE REQ", align: "center", sortable: false,
                    value: "noreq", width: "20%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "KODE ITEM", align: "center", sortable: false,
                    value: "kode", width: "20%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "ITEM", align: "center", sortable: false,
                    value: "serve", width: "20%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "SATUAN", align: "center", sortable: false,
                    value: "unit", width: "20%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "REQ QTY", align: "center", sortable: false,
                    value: "qty", width: "10%", class: "pa-1 blue lighten-3 white--text",
                },
            ]
        }
    },
    computed: {
        dialog_add_itemaset: {
            get() {
                return this.$store.state.common.dialog_add_itemaset
            },
            set(val) {
                this.$store.commit('common/update_dialog_add_itemaset', val)
            }
        },
        list_requestaset: {
            get() {
                return this.$store.state.common.list_requestaset
            },
            set(val) {
                this.$store.commit('common/update_list_requestaset', 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)
            }
        }
    },
    methods: {
        searchrequest(search) {
            this.loading = true
            setTimeout(() => {
                this.$store.dispatch('common/lookupOrderRequest', search)
                this.loading = false
            }, 500);
        },
        toggleAll() {
            if (this.temp_selectedrequest.length > 0) {
                this.temp_selectedrequest = []
            } else {
                this.temp_selectedrequest = this.list_requestaset.records.slice()
            }
        },
        parseCurrency(value) {
            let cleanvalue = 0;
            if (!isNaN(value)) {
                cleanvalue = value;
            } else {
                cleanvalue = String(value).replace(/\./g, '');
                cleanvalue = cleanvalue.replace(',', '.');
            }
            return parseFloat(cleanvalue) || 0;
        },
        batalrequest() {
            this.temp_selectedrequest = []
            this.dialog_add_itemaset = false
        },
        simpanrequest() {
            let request = JSON.parse(JSON.stringify(this.temp_selectedrequest))
            let form = JSON.parse(JSON.stringify(this.form_orderaset))

            const prnumber = [...new Set(request.map(item => item.PurchaseRequestNumber))].join(', ')
            form.reference = prnumber
            
            const newitem = Object.values(request.reduce((acc, current) => {
                const itemcode = current.M_ItemCode
                if (!acc[itemcode]) {
                    acc[itemcode] = {
                        M_ItemID: current.M_ItemID,
                        M_ItemCode: itemcode,
                        M_ItemDesc: current.M_ItemDesc,
                        ItemUnitID: current.ItemUnitID,
                        ItemUnitName: current.ItemUnitName,
                        SupplierPrice: Number(current.SupplierPrice),
                        M_BranchName: current.M_BranchName,
                        RequestQty: 0.00,
                        DiskonAmount: 0.00,
                        DiskonType: 'R',
                        EndPrice: 0.00,
                        TempTotal: 0.00,
                        detail: []
                    }
                }

                acc[itemcode].RequestQty += Number(current.RequestQty)
                acc[itemcode].detail.push(current)
                acc[itemcode].EndPrice = acc[itemcode].SupplierPrice - acc[itemcode].DiskonAmount
                acc[itemcode].TempTotal = acc[itemcode].RequestQty * acc[itemcode].EndPrice
                return acc
            }, {}))

            let subtotal = newitem.reduce((sum, item) => sum + Number(item.TempTotal), 0)
            let disc = this.parseCurrency(form.valuediskon)
            if (form.typediskon == 'percent') {
                disc = subtotal * Number(form.valuediskon) / 100
            }

            let tax = this.parseCurrency(form.valuepajak)
            if (form.typepajak == 'percent') {
                tax = (subtotal - disc) * Number(form.valuepajak) / 100
            }

            let total = (subtotal - disc) + tax
            let summary = {
                subtotal: subtotal,
                diskon: disc,
                pajak: tax,
                total: total
            }

            this.item_orderaset = newitem
            this.form_orderaset = form
            this.summary_orderaset = summary
            this.temp_selectedrequest = []
            this.dialog_add_itemaset = false
        }
    },
    watch: {
        keyword(newval, oldval) {
            if (!newval) return
            if (newval === oldval) return
            if (newval.length < 1) return
            this.searchrequest(newval)
        },
    }
}
</script>