<template>
    <v-layout row wrap>
        <v-flex grow></v-flex>
        <v-flex shrink>
            <v-btn
                @click="tambahItem()" color="primary" class="white--text"
                :disabled="isFormEmpty()"
            >Tambah Item</v-btn>
        </v-flex>
        <v-flex xs12>
            <v-data-table :headers="headers" :items="selected_request_asset"
                :expand="expand" class="elevation-1" hide-actions item-key="M_ItemID">
                <!-- item request grouped -->
                <template v-slot:items="props">
                    <tr @click="props.expanded = !props.expanded">
                        <td class="text-xs-center pa-2">
                            <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">
                            <v-text-field
                                v-model="props.item.SupplierPrice"
                                hide-details prefix="Rp." solo :readonly="viewonlymode"
                                @input="$store.dispatch('orderAsset/recalculateOrderSummary')"
                                @focus="handleFocus(props.item, 'price')"
                                @blur="handleBlur(props.item, 'price')"
                            ></v-text-field>
                        </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="(item, index) in type_disc" :key="index"
                                            @click="changeDiscountPerItem(item.name, props.item)"
                                        >
                                            <v-list-tile-title>{{ item.name }}</v-list-tile-title>
                                        </v-list-tile>
                                    </v-list>
                                </v-menu>
                                <v-text-field
                                    v-if="props.item.DiskonType == 'R'" prefix="Rp." :readonly="viewonlymode"
                                    v-model="props.item.DiskonAmount" hide-details solo
                                    @input="$store.dispatch('orderAsset/recalculateOrderSummary')"
                                    @focus="handleFocus(props.item, 'diskon')"
                                    @blur="handleBlur(props.item, 'diskon')"
                                ></v-text-field>
                                <v-text-field
                                    v-if="props.item.DiskonType == 'P'" :readonly="viewonlymode"
                                    v-model="props.item.DiskonAmount" solo
                                    type="number" min="0" suffix="%" hide-details
                                    @input="$store.dispatch('orderAsset/recalculateOrderSummary')"
                                ></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="removeRequestItem(props.item)"
                                style="min-width: 40px; margin: 0;" small
                            >
                                <v-icon small>delete</v-icon>
                            </v-btn>
                        </td>
                    </tr>
                </template>

                <!-- expanded item request -->
                <template v-slot:expand="props">
                    <v-card flat>
                        <v-card-text>
                            <v-data-table
                                :headers="b_headers" class="elevation-0"
                                :items="props.item.detail" hide-actions
                                item-key="PurchaseRequestDetailID"
                            >
                                <template v-slot:items="det">
                                <tr>
                                    <td class="text-xs-center pa-2">{{ det.item.M_ItemDesc }}</td>
                                    <td class="text-xs-center pa-2">{{ det.item.PurchaseRequestNumber }}</td>
                                    <td class="text-xs-center pa-2">{{ det.item.M_BranchName }}</td>
                                    <td class="text-xs-center pa-2">
                                        <v-text-field
                                            v-model="det.item.RequestQty" hide-details
                                            solo type="number" min="0" :readonly="viewonlymode"
                                            @input="$store.dispatch('orderAsset/recalculateOrderSummary')"
                                        ></v-text-field>
                                    </td>
                                    <td class="text-xs-center pa-2">{{ det.item.ItemUnitName }}</td>
                                    <td class="text-xs-center pa-2">
                                        Rp. {{ formatCurrency(det.item.SupplierPrice) }}
                                    </td>
                                    <td class="text-xs-center pa-2">
                                        <v-btn
                                            color="red" flat @click="removeRequestDetail(det.item)"
                                            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>
            </v-data-table>
        </v-flex>
    </v-layout>
</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 {
            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",
                },
            ],
            b_headers: [
                {
                    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",
                }
            ],
            type_disc: [{name: 'percent'}, {name: 'nominal'}]
        }
    },
    computed: {
        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);
            }
        },
        viewonlymode() {
            return this.$store.state.common.viewonlymode;
        }
    },
    methods: {
        isFormEmpty() {
            const form = this.form_order_asset;
            if (this.viewonlymode) {
                return true;
            }

            if (form.supplierID != "" && form.branchID != "") {
                return false;
            }

            return true;
        },
        tambahItem() {
            this.$store.commit("orderAsset/update_dialog_select_asset", true);
        },
        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;
        },
        handleFocus(item, field) {
            if (field == 'price') {
                const currprice = item.SupplierPrice;
                const parsedprice = this.parseCurrency(currprice);
                item.SupplierPrice = parsedprice;
            }

            if (field == 'diskon') {
                const currdisc = item.DiskonAmount;
                const parseddisc = this.parseCurrency(currdisc);
                item.DiskonAmount = parseddisc;
            }
        },
        handleBlur(item, field) {
            if (field == 'price') {
                const currprice = item.SupplierPrice;
                const parsedprice = this.parseCurrency(currprice);
                item.SupplierPrice = this.formatCurrency(parsedprice);
            }

            if (field == 'diskon') {
                const currdisc = item.DiskonAmount;
                const parseddisc = this.parseCurrency(currdisc);
                item.DiskonAmount = this.formatCurrency(parseddisc);
            }
        },
        removeRequestItem(item) {
            const current = JSON.parse(JSON.stringify(this.selected_request_asset));
            let newitem = current.filter(ele => ele.M_ItemCode != item.M_ItemCode);

            this.selected_request_asset = newitem;
            this.$store.dispatch('orderAsset/recalculateOrderSummary');
        },
        removeRequestDetail(item) {
            const current = JSON.parse(JSON.stringify(this.selected_request_asset));
            let changed = current.find(ele => ele.M_ItemCode == item.M_ItemCode);
            let newdetail = changed.detail.filter(
                d => d.PurchaseRequestDetailID != item.PurchaseRequestDetailID
            );

            if (newdetail.length > 0) {
                changed.detail = newdetail;
                this.selected_request_asset = current;
                this.$store.dispatch('orderAsset/recalculateOrderSummary');
            } else {
                this.removeRequestItem(changed);
            }
        },
        changeDiscountPerItem(type, item) {
            if (type == 'percent') {
                item.DiskonType = 'P'
                item.DiskonAmount = 0.00
            } else {
                item.DiskonType = 'R'
                item.DiskonAmount = 0.00
            }

            this.$store.dispatch('orderAsset/recalculateOrderSummary');
        }
    },
    watch: { }
}
</script>
