<template>
    <div class="row">
        <div class="col">
            <loading-component style="height: 200px; top: 0;" v-if="isLoading"></loading-component>
            <div class="row flex-wrap"  v-if="!isLoading && order">
                <div class="col">
                    <div class="row m-b-30">
                        <div class="col bg-master-lightest padding-25">
                            <div class="row align-items-center">
                                <div class="col-12 col-lg-3">
                                    <div class="row justify-content-center">
                                        <div class="col-10">
                                            <a :href="route('order.qr.download', order.id)" target="_blank">
                                                <div class="peelable-corner overflow-hidden relative">
                                                    <!-- <img :src="'https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl={id:'+order.id+'}'" class="w-100"> -->
                                                    <img :src="this.$qr_code_img_url + order.id + '}'" class="w-100">
                                                </div>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="row m-b-20">
                                        <div class="col-auto">
                                            <h3 class="no-margin"><b>Order No.</b> {{order.reference}}</h3>
                                        </div>
                                        <div class="col d-flex">
                                            <div class="btn btn-xs btn-outline-danger b-rad-none pointer requestModal align-items-center d-flex" data-type="changeOrderNo" v-if="$store.getters.isSuperAdmin">Change Order Number</div>
                                            <!-- <div class="btn btn-xs btn-outline-danger b-rad-none pointer requestModal align-items-center d-flex m-l-10" data-type="helpMenu" v-if="$store.getters.isSuperAdmin">Help Menu</div> -->
                                            <modal-component class="animate__animated animate__fast animate__fadeIn" styleType="fill-in" type="changeOrderNo">
                                                <change-order-number-form-component :section="section" :data="order"></change-order-number-form-component>
                                            </modal-component>
                                            <!-- <modal-component class="animate__animated animate__fast animate__fadeIn" styleType="fill-in" type="helpMenu">
                                                <help-menu-form-component></help-menu-form-component>
                                            </modal-component> -->
                                        </div>
                                    </div>
                                    <div class="row m-b-20">
                                        <div class="col-12">
                                            <div class="row">
                                                <div class="col-auto d-flex align-items-center">
                                                    <h6 class="no-margin"><b>Remark:</b></h6>
                                                    <modal-component class="animate__animated animate__fast animate__fadeIn" type="orderRemark">
                                                        <remark-form-component module_type="Order" :data="order" :section="section"></remark-form-component>
                                                    </modal-component>
                                                </div>
                                                <div class="col-auto p-l-0" v-if="order.remarks.length == 0">
                                                    <div class="btn btn-xs btn-outline-info b-rad-none pointer requestModal" data-type="orderRemark">Add a Remark</div>
                                                </div>
                                                <div class="col d-flex align-items-center pl-3 pl-md-0" v-if="order.remarks.length >= 1">
                                                    <h6 class="no-margin">{{ order.remarks[0].content }}</h6>
                                                    <span class="btn btn-md btn-default m-l-10 requestModal" data-type="orderRemark">
                                                        <i class="fa fa-edit"></i>
                                                    </span>
                                                    <span class="btn btn-md btn-default m-l-5 requestModal" data-type="deleteOrderRemark">
                                                        <i class="fa fa-trash"></i>
                                                    </span>
                                                    <modal-component class="animate__animated animate__fast animate__fadeIn" type="deleteOrderRemark">
                                                        <delete-remark-form-component :section="section" :data="order.remarks[0]"></delete-remark-form-component>
                                                    </modal-component>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row m-b-20">
                                        <div class="col-12 col-sm-auto">
                                            <h6 class="no-margin"><b>Order Date:</b> {{order.created_at}}</h6>
                                        </div>
                                        <div class="col-12 col-sm-auto">
                                            <h6 class="no-margin"><b>Warehouse:</b> {{order.warehouse.name}} {{$store.getters.isAdmin ? order.warehouse.reference : ''}}</h6>
                                        </div>
                                        <div class="col col-sm" v-if="$store.getters.isAdmin">
                                            <a :href="route('customer.profile', order.company_module.marking)">
                                                <h6 class="no-margin"><b>Customer Marking:</b> {{order.company_module.marking}}</h6>
                                            </a>
                                        </div>
                                    </div>
                                    <div class="row m-b-10 align-items-center parentContainer" >
                                        <div class="col-auto">
                                            <h6 class="no-margin">
                                                <div class="row">
                                                    <div class="col-12 col-sm-auto pr-sm-0"><b>Delivery Address:</b>&nbsp;</div>
                                                    <div class="col-12 col-sm-auto pl-sm-0">{{order.address.reference}} <i class="fa fa-info-circle m-l-10"  v-tooltip:right="order.address.street_one + ' ' + (order.address.street_two ? order.address.street_two : '') + ', ' + (order.address.district ? order.address.district.name : '') + ', ' + order.address.post_code + ' ' + (order.address.state ? order.address.state.name : '') + ', ' + (order.address.country ? order.address.country.name : '')"></i></div>
                                                </div>
                                            </h6>
                                        </div>
                                        <div class="col">
                                            <div class="row" v-if="!order.address_change_request">
                                                <div class="col">
                                                    <div class="btn btn-xs btn-outline-danger b-rad-none pointer requestModal m-t-10 mt-sm-0" data-type="updateDeliveryAddress">Change Delivery Address</div>
                                                    <modal-component class="animate__animated animate__fast animate__fadeIn" styleType="stick-up" type="updateDeliveryAddress" size="large">
                                                        <change-order-address-form-component :data="order" :section="section" class="text-center"></change-order-address-form-component>
                                                    </modal-component>
                                                </div>
                                            </div>
                                            <div class="row parentContainer" v-if="order.address_change_request">
                                                <div class="col-auto p-r-0">
                                                    <div class="p-t-10 p-b-10 p-l-15 p-r-15 b-a b-danger fs-10 text-danger requestModal"  data-type="updateDeliveryAddress"><i class="fa fa-exclamation-circle m-r-10"></i>Your Delivery address change request is being reviewed</div>
                                                </div>
                                                <div class="col-auto bg-danger-light pointer requestModal" data-type="cancelAddressChangeRequest">
                                                    <i class="fa fa-times text-white lh-38"></i>
                                                </div>
                                                <modal-component small type="cancelAddressChangeRequest">
                                                    <div class="row">
                                                        <div class="col text-center">
                                                            <div class="row">
                                                                <div class="col text-center">
                                                                    <div class="row m-b-20">
                                                                        <div class="col">
                                                                            <h5 class="all-caps">Cancel Address Change Request</h5>
                                                                            <div class="fs-11">Are you sure you want to cancel your order delivery address change request?</div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="row">
                                                                        <div class="col p-r-5">
                                                                            <div data-dismiss="modal" class="btn btn-sm btn-default bg-master-lighter btn-block b-rad-none">Cancel</div>
                                                                        </div>
                                                                        <div class="col p-l-5">
                                                                            <div data-dismiss="modal" class="btn btn-sm btn-danger btn-block b-rad-none" @click="submit(route('api.order.address.status.update', order.address_change_request.id, 6), 'put', section, true, true)">Confirm</div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </modal-component>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row align-items-center">
                                        <div class="col-10">
                                            <h6 class="text-info"><span class="text-danger bold">Gentle reminder:</span> You need to send the QR code to your supplier to print and stick on your packages, this QR code is required for us to identify your packages when they arrives at our warehouse!</h6>
                                            <a :href="route('order.qr.download', order.id)" target="_blank">
                                                <button class="btn btn-sm btn-success bg-master b-rad-none all-caps">Download QR Code Pdf</button>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row m-b-30" v-if="order.invoices.length">
                        <div class="col">
                            <div class="row m-b-20">
                                <div class="col">
                                    <h4 class="bold">Invoices</h4>
                                    <p>You can view your invoices here and make payment.</p>
                                </div>
                            </div>
                            <div class="row bg-master-lightest p-t-15" v-for="invoice in order.invoices" v-if="invoice.type === 1">
                                <div class="col" v-if="getMergedInvoices(invoice).length > 1">
                                    <customer-payments-billing-with-storage-component :data="getMergedInvoices(invoice)" :storage="getStorageInfo(invoice)" invoice_status="Pending Payment" :section="section"></customer-payments-billing-with-storage-component>
                                </div>
                                <div class="col" v-else>
                                    <customer-payments-billing-component :data="invoice" invoice_status="Pending Payment" :section="section"></customer-payments-billing-component>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <order-package-v2-section-component v-if="!isLoading" :order_number="order_number"></order-package-v2-section-component>
        </div>
    </div>
</template>
<script>
    export default {
        props: {
            order_number: {
                type: Number,
                required: true,
            }
        },
        data(){
            return {
                section: 'orderProfileV2Section',
                isLoading: true,
                order: null,
                addComment: false,
            }
        },
        computed: {
            pendingQueue () {
                return this.$store.getters.isInCompleteQueue(this.section);
            },
            orderStorageMap() {
                // Create a map to link parent invoice IDs to storageInvoiceIds
                const storageMap = {};
                if(this.order.storages){
                    for (const storage of this.order.storages) {
                        storageMap[storage.parentInvoiceId] = storage.storageInvoiceId;
                    }
                }
                return storageMap;
            }
        },
        watch: {
            pendingQueue(inComplete){
                if(inComplete){
                    this.fetchCompany();
                }
            }
        },
        created(){
            this.$store.dispatch('updateListQueue', {'name': this.section});
        },
        methods: {
            fetchCompany(){
                this.isLoading = true;
                this.submit(route('api.order.v2.show', this.order_number), 'get', this.section, false, false)
            },
            successHandler(response){
                this.$store.dispatch('completeList', {'name': this.section, 'data': []});
                this.isLoading = false;
                this.order = response.payload.data;
            },
            errorHandler(error, status){
                if(status == 404){
                    window.location.href = this.route('error.404');
                }
            },
            getStorageInfo(invoice) {
                const storageObject = this.findStorageInfoObject(invoice.id);
                return storageObject;
            },
            findStorageInfoObject(shippingInvoiceId) {
                if(this.order.storages){
                    return this.order.storages.find(storage => storage.parentInvoiceId === shippingInvoiceId);
                }
                return null;
            },
            getMergedInvoices(invoice){
                const storageInvoice = this.getStorageInvoice(invoice);
                const mergedArray = [
                    ...(invoice ? [invoice] : []),
                    ...(storageInvoice ? [storageInvoice] : []),
                ];
                return mergedArray;
            },
            getStorageInvoice(invoice) {
                // Retrieve the storageInvoiceId for the current shipping invoice from storage info (order.storages)
                const storageInvoiceId = this.orderStorageMap[invoice.id];

                // Find and return the storage invoice (type 16) from order.invoices
                const storageInvoice = this.order.invoices.find((invoice) => {
                    return invoice.type === 16 && invoice.id === storageInvoiceId;
                });

                return storageInvoice;
            },
        }
    }
</script>
