<template>
<v-dialog v-model="dialog_select_item" persistent width="60vw">
    <v-card class="style-limit-heightcard">
        <v-card-title class="headline grey lighten-2" primary title>
            TAMBAH ITEM REQUEST
        </v-card-title>
        <v-card-text class="style-limit-heightcontent">
            <v-flex xs12>
                <v-text-field label="Cari" hide-details outline
                    v-model="keyword" placeholder="Nama item, nomor request"
                ></v-text-field>
            </v-flex>
            <v-flex xs12 mt-2>
                <v-data-table :headers="headers" :items="requested_asset.records" class="elevation-1"
                    v-model="selected_local" item-key="PurchaseRequestDetailID" 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-start pa-2">
                                {{ props.item.Requestedby }} <br>
                                {{ props.item.M_BranchName }}
                            </td>
                            <td class="text-xs-start pa-2">
                                {{ props.item.M_ItemCode }} <br>
                                {{ 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-card-text>
        <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn @click="batalTambah()" color="error" class="white--text">Batal</v-btn>
            <v-btn @click="simpanItem()" color="primary" class="white--text">Simpan</v-btn>
        </v-card-actions>
    </v-card>
</v-dialog>
</template>

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

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

<script>
module.exports = {
    data() {
        return {
            keyword: "",
            loading: false,
            selected_local: [],
            headers: [
                {
                    text: "NO PURCHASE REQ", align: "center", sortable: false,
                    value: "noreq", width: "20%", class: "pa-1 blue lighten-3 white--text",
                },
                {
                    text: "REQUESTER", 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_select_item: {
            get() {
                return this.$store.state.orderAsset.dialog_select_asset;
            },
            set(val) {
                this.$store.commit("orderAsset/update_dialog_select_asset", val);
            }
        },
        form_order_asset: {
            get() {
                return this.$store.state.orderAsset.form_order_asset;
            },
            set(val) {
                this.$store.commit("orderAsset/update_form_order_asset", val);
            }
        },
        requested_asset: {
            get() {
                return this.$store.state.orderAsset.requested_asset
            },
            set(val) {
                this.$store.commit('orderAsset/update_requested_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);
            }
        }
    },
    methods: {
        isFormEmpty() {
            const form = this.form_order_asset;
            if (form.supplierID != "" && form.branchID != "") {
                return false;
            }

            return true;
        },
        cariRequest(newval) {
            this.loading = true;
            setTimeout(() => {
                this.$store.dispatch("orderAsset/searchItemRequest", newval);
                this.loading = false;
            }, 500);
        },
        tambahItem() {
            this.cariRequest("")
            this.dialog_select_item = true;
        },
        toggleAll() {
            if (this.selected_local.length) {
                this.selected_local = [];
            } else {
                this.selected_local = this.requested_asset.records.slice();
            }
        },
        simpanItem() {
            const requestedAsset = JSON.parse(JSON.stringify(this.selected_local));
            let form_asset = JSON.parse(JSON.stringify(this.form_order_asset));

            const PRnumber = [...new Set(requestedAsset.map(item => item.PurchaseRequestNumber))].join(', ');
            form_asset.reference = PRnumber;

            const selected = Object.values(requestedAsset.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_request_asset = selected;
            this.form_order_asset = form_asset;
            this.$store.dispatch("orderAsset/recalculateOrderSummary");
            this.selected_local = [];
            this.dialog_select_item = false;
        },
        batalTambah() {
            this.requested_asset = {
                records: [],
                total: 0
            };
            this.selected_local = [];
            this.dialog_select_item = false;
        }
    },
    watch: {
        dialog_select_item(val) {
            if (val) {
                this.cariRequest("");
                let current = [];
                let newly = this.selected_request_asset
                newly.forEach((item) => {
                    current.push(...item.detail);
                });

                this.selected_local = current;
            }
        },
        keyword(newval, oldval) {
            if (!newval) return;
            if (newval == oldval) return;
            if (newval.length < 1) return;
            this.cariRequest(newval);
        }
    }
}
</script>
