<template>
<v-dialog v-model="dialog_select_itemjasa" persistent width="60vw">
    <v-card>
        <v-card-title class="headline grey lighten-2" primary title>
            TAMBAH REQUEST JASA
        </v-card-title>
        <v-card-text>
            <v-layout row wrap>
                <v-flex xs12>
                    <v-text-field
                        label="Cari" hide-details outline
                        v-model="keyword" placeholder="nomor request jasa"
                    ></v-text-field>
                </v-flex>
                <v-flex xs12 mt-2>
                    <v-data-table
                        :headers="headers" :items="list_requestjasa.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 color="primary" class="white--text" @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 JASA", align: "center", sortable: false,
                    value: "kode", width: "20%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "JASA", 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_select_itemjasa: {
            get() {
                return this.$store.state.poservice.dialog_select_itemjasa
            },
            set(val) {
                this.$store.commit("poservice/update_dialog_select_itemjasa", val)
            }
        },
        form_pojasa: {
            get() {
                return this.$store.state.poservice.form_pojasa
            },
            set(val) {
                this.$store.commit("poservice/update_form_pojasa", val)
            }
        },
        list_requestjasa: {
            get() {
                return this.$store.state.poservice.list_requestjasa
            },
            set(val) {
                this.$store.commit("poservice/update_list_requestjasa", val)
            }
        },
        selected_requestjasa: {
            get() {
                return this.$store.state.poservice.selected_requestjasa
            },
            set(val) {
                this.$store.commit("poservice/update_selected_requestjasa", val)
            }
        },
        summary_pojasa: {
            get() {
                return this.$store.state.poservice.summary_pojasa
            },
            set(val) {
                this.$store.commit("poservice/update_summary_pojasa", val)
            }
        },
    },
    methods: {
        searchRequest(search) {
            this.loading = true;
            setTimeout(() => {
                this.$store.dispatch("poservice/lookupRequestJasa", search);
                this.loading = false;
            }, 500);
        },
        toggleAll() {
            if (this.temp_selectedrequest.length) {
                this.temp_selectedrequest = [];
            } else {
                this.temp_selectedrequest = this.list_requestjasa.records.slice();
            }
        },
        batalRequest() {
            this.temp_selectedrequest = []
            this.dialog_select_itemjasa = false
        },
        simpanRequest() {
            const requestjasa = JSON.parse(JSON.stringify(this.temp_selectedrequest))
            let formjasa = JSON.parse(JSON.stringify(this.form_pojasa))

            const prnumber = [...new Set(requestjasa.map(item => item.PurchaseRequestNumber))].join(', ')
            formjasa.reference = prnumber
            
            const newly = Object.values(requestjasa.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
            }, {}))

            this.selected_requestjasa = newly
            this.form_pojasa = formjasa

            let subtotal = newly.reduce((sum, item) => sum + Number(item.TempTotal), 0)
            let total = (subtotal - formjasa.valuediskon) + formjasa.valuepajak
            let summary = {
                subtotal: subtotal,
                diskon: formjasa.valuediskon,
                pajak: formjasa.valuepajak,
                total: total
            }

            this.summary_pojasa = summary
            this.temp_selectedrequest = []
            this.dialog_select_itemjasa = false
        },
    },
    watch: {
        dialog_select_itemjasa(val) {
            if (val) {
                let current = []
                let newly = this.selected_requestjasa

                newly.forEach(item => {
                    current.push(...item.detail)
                });
                this.temp_selectedrequest = current
            }
        },
        keyword(newVal, oldVal) {
            if (!newVal) return;
            if (newVal === oldVal) return;
            if (newVal.length < 1) return;
            this.searchRequest(newVal);
        }
    },
}
</script>