<!--suppress JSAnnotator -->
<template>
    <!-- Page, data-name contains page name which can be used in callbacks -->
    <div class="page " data-name="request-quote">
        <!-- page-with-subnavbar -->
        <!-- Top Navbar -->
        <div class="navbar">
            <div class="navbar-inner">
                <a href="#" class="link back">
                    <i class="icon icon-back"></i>
                </a>
                <div class="title sliding">{{@global.LANGUAGE.REQUEST_QUOTE_MSG00}}</div>
                <div class="right">

                    <a href="#" class="link icon-only filterMenuOpen">
                        <i class="f7-icons icon-filter size-18"></i>
                    </a>

                </div>
            </div>
        </div>

        <div class="toolbar tabbar tabbar-custom toolbar-top">
            <div class="toolbar-inner">
                <a href="#recentOrders" class="tab-link tab-link-active">
                    {{@global.LANGUAGE.REQUEST_QUOTE_MSG02}}
                </a>
                <a href="#historyOrders" class="tab-link">
                    {{@global.LANGUAGE.REQUEST_QUOTE_MSG06}}
                </a>
            </div>
        </div>
        <div class="bottom-section-wrapper  toolbar-bottom  bg-color-white">
            <div
                class="display-flex flex-direction-column  bottom-section-button-wrapper    justify-content-space-evenly">
               
				
				<a data-popup=".popup-fullscreen-newtemplate"
                    class="col popup-open link button button-fill color-green elevation-2 addRecent">
                    <i class="f7-icons icon-header-added"></i>
                    {{@global.LANGUAGE.REQUEST_QUOTE_MSG03}}
                </a>

            </div>
			
			
        </div>
		
		
        <!--<div class="searchbar-backdrop"></div>-->
        <div class="tabs-animated-wrap">
            <div class="tabs">
			
                <div class="page-content  page-content-recent-order tab tab-active" id="recentOrders">
                    <form class="searchbar searchbar-recent-order overflow-hidden">
                        <div class="searchbar-inner">
                            <div class="searchbar-input-wrap">
                                <input type="search" placeholder="{{@global.LANGUAGE.COM_MSG02}}"
                                    title="{{@global.LANGUAGE.COM_MSG02}}">
                                <i class="searchbar-icon"></i>
                                <span class="input-clear-button"></span>
                            </div>
                            <span class="searchbar-disable-button text-color-gray">{{@global.LANGUAGE.COM_MSG01}}</span>
                        </div>
                    </form>

                    <div class="block searchbar-not-found">
                        <div class="block-inner">{{@global.LANGUAGE.PROMPT_MSG008}}</div>
                    </div>




                    {{#if isRecentLoaded}}
                    <div
                        class="list media-list virtual-list no-chevron no-margin-top no-hairline-bottom searchbar-found recentOrdersList">
                        <!-- keep it empty -->
                    </div>
                    {{else}}
                    <div key="VirtualListPreloader" class="block block-strong text-align-center">
                        <div class="preloader color-red"></div>
                    </div>
                    {{/if}}



                </div>
				
                <div class="page-content  page-content-history-order tab " id="historyOrders">

                    <form class="searchbar searchbar-history-order overflow-hidden">
                        <div class="searchbar-inner">
                            <div class="searchbar-input-wrap">
                                <input type="search" placeholder="{{@global.LANGUAGE.COM_MSG02}}"
                                    title="{{@global.LANGUAGE.COM_MSG02}}">
                                <i class="searchbar-icon"></i>
                                <span class="input-clear-button"></span>
                            </div>
                            <span class="searchbar-disable-button text-color-gray">{{@global.LANGUAGE.COM_MSG01}}</span>
                        </div>
                    </form>

                    <div class="block searchbar-not-found">
                        <div class="block-inner">{{@global.LANGUAGE.PROMPT_MSG008}}</div>
                    </div>


                    {{#if isHistoryLoaded}}
                    <div
                        class="list media-list virtual-list no-chevron no-margin-top no-hairline-bottom searchbar-found historyOrdersList">
                        <!-- keep it empty -->
                    </div>
                    {{else}}
                    <div key="VirtualListPreloader" class="block block-strong text-align-center">
                        <div class="preloader color-red"></div>
                    </div>
                    {{/if}}


                </div>


            </div>
        </div>

    </div>



</template>


<script>
    // script must return component object
    return {
        data: function () {
            var self = this;

            var ret = {
                CurrentTab: 'recentOrders',
                isHistoryLoaded: false,
                isRecentLoaded: false,
                VirtualHistoryList: null,
                SearchbarHistory: null,
                SearchbarTasks: null,
                VirtualTasksList: null,
                SearchbarRecent: null,
                VirtualRecentList: null,
                ToolbarAdditionaClass: ' toolbar-size-2',
            };

            /* ret = self.$app.methods.getFromStorage('userInfo');
             ret.TimeZoneList = Protocol.Helper.getTimezoneList(ret.TimeZoneID || ret.TimeZone);
             ret.CurrentFormButtonSubmit = 'submit-form-user';*/

            return ret;
        },

        methods: {
            initRecentList: function (recentOrdersList) {
                let self = this;
                let listEl = self.$el.find('.recentOrdersList');


                self.VirtualRecentList = self.$app.virtualList.create({
                    el: listEl,
                    items: recentOrdersList || [],
                    //cache: false,
                    searchAll: function (query, items) {
                        var found = [];
						//console.log('search',items)
                        query = query.trim().toLowerCase();
                        for (var i = 0; i < items.length; i++) {
                            if (items[i].QuoteCode.toLowerCase().indexOf(query) >= 0 ||
                                items[i].QuoteEmail.toLowerCase().indexOf(query) >= 0 ||
                                query === '') found.push(i);
                        }

                        return found; //return array with mathced indexes
                    },
                    height: function (item) {
                        return self.$app.theme === 'ios' ? 75.75 : 81.3
                    },
                    renderItem: function (item, index) {
						console.log('item',item)

                        //let jobType = Protocol.Helper.getJobTypeByNumber(item.JobType);

                        let ret = `
                            <li data-code="${item.QuoteCode}">`;
                        ret += ` <div class="item-content">
    
                                                <div class="item-media">
                                                    <div class="user-icon text-align-center text-color-white   bg-color-red   display-flex align-items-center justify-content-center text-transform-uppercase">
                                                        ${index + 1}
                                                    </div>

                                                </div>
                                    <div class="item-inner">
                                        <div class="item-title-row">
                                                <div class="item-title weight-500 text-color-black text-transform-uppercase">
                                                   
                                                   #${item.OrderId}
                                                </div>
                                                <div class="item-after">
                                                    <a href="#"   class="link ripple-color-red bigger-touch-area recentOrderMenu"><i class="f7-icons icon-menu-asset size-18"></i></a>
                                                </div>
                                        </div>
                                        <div class="divider"></div>
                                        <div class="item-text">
                                                <div class="row no-gutter">
                                                    <div class="col-100 white-space-no-wrap" title="${item.QuoteTime.slice(0, 10)}">
                                                        <i class="f7-icons size-16 icon-input asset_list_icon text-color-lightgray vertical-middle"></i>
                                                        <span class="size-14 vertical-middle"> ${item.QuoteTime.slice(0, 10)}</span>
                                                    </div>
                                                   
                                                </div>
                                            </div>       
                                    </div>
                                 
                            </li>`;
                        return ret;
                    },
                    emptyRecent: `<li class="item-content">${LANGUAGE.COM_MSG139}</li>`
                });

                self.$setState({
                    isRecentLoaded: true
                });
                self.initSearchRecents();
            },
            initSearchRecents: function () {
                let self = this;

                self.SearchbarRecent = self.$app.searchbar.create({
                    el: self.$el.find('.searchbar-recent-order'),
                    searchContainer: self.$el.find('.recentOrdersList'),
                    searchIn: '.item-inner',
                    notFoudEl: self.$el.find('.searchbar-not-found'),
                    backdrop: false
                });
				
            },
            initHistoryList: function (historyList) {
                let self = this;
                let listEl = self.$el.find('.historyOrdersList');

                self.VirtualHistoryList = self.$app.virtualList.create({
                    el: listEl,
                    items: historyList || [],
                    //cache: false,
                    searchAll: function (query, items) {
                        var found = [];

                        query = query.trim().toLowerCase();
                        for (var i = 0; i < items.length; i++) {
                            if (items[i].QuoteCode.toLowerCase().indexOf(query) >= 0 ||
                                items[i].QuoteEmail.toLowerCase().indexOf(query) >= 0 ||
                                query === '') found.push(i);
                        }

                        return found; //return array with mathced indexes
                    },
                    height: function (item) {
                        return self.$app.theme === 'ios' ? 75.75 : 81.3
                    },
                    renderItem: function (item, index) {
						console.log('history',item)
                        let ret = `
                            <li data-code="${item.QuoteCode}">`;
                        ret += ` <div class="item-content">
    
                                                <div class="item-media">
                                                    <div class="user-icon text-align-center text-color-white   bg-color-red   display-flex align-items-center justify-content-center text-transform-uppercase">
                                                        ${index + 1}
                                                    </div>

                                                </div>
                                    <div class="item-inner">
                                        <div class="item-title-row">
                                                <div class="item-title weight-500 text-color-black text-transform-uppercase">
                                                   
                                                   #${item.OrderId}
                                                </div>
                                                <div class="item-after">
                                                    <a href="#"   class="link ripple-color-red bigger-touch-area historyOrderMenu"><i class="f7-icons icon-menu-asset size-18"></i></a>
                                                </div>
                                        </div>
                                        <div class="divider"></div>
                                        <div class="item-text">
                                                <div class="row no-gutter">
                                                    <div class="col-100 white-space-no-wrap" title="${item.QuoteTime.slice(0, 10)}">
                                                        <i class="f7-icons size-16 icon-input asset_list_icon text-color-lightgray vertical-middle"></i>
                                                        <span class="size-14 vertical-middle"> ${item.QuoteTime.slice(0, 10)}</span>
                                                    </div>
                                                   
                                                </div>
                                            </div>       
                                    </div>
                                 
                            </li>`;
                        return ret;
                    },
                    emptyHistory: `<li class="item-content">${LANGUAGE.COM_MSG139}</li>`
                });

                self.initSearchHistory();
            },
            initSearchHistory: function () {
                let self = this;

                self.SearchbarHistory = self.$app.searchbar.create({
                    el: self.$el.find('.searchbar-history-order'),
                    searchContainer: self.$el.find('.historyOrdersList'),
                    searchIn: '.item-inner',
                    notFoudEl: self.$el.find('.searchbar-not-found'),
                    backdrop: false
                });
            },



         

            getRecentList: function (MajorToken) {
                var self = this;
				
				var self = this;
				var data = {
                    CustomerCode: self.$root.MajorToken,
                    UserCode: self.$root.MinorToken,
                };

					self.$app.preloader.show();
					self.$app.request.getJSON(API_URL.RECENT_ORDERS + '&MajorToken=' + data.CustomerCode + '&MinorToken=' + data.UserCode, function (result, xhr, status) {
						self.$app.preloader.hide();
						if (result) {
							
							
							self.$setState({
								isRecentLoaded: true,
							});
							self.$app.utils.nextFrame(() => {
								self.initRecentList(result.Data.rows)
							});

							self.$app.methods.setInStorage({ name: 'recentOrdersList', data: result.Data.rows });
							
						} else {
							self.$app.dialog.alert('Something wrong, try again later');
						}

					},
						function (xhr, status) {
							self.$app.preloader.hide();
							if (!xhr) {
								self.$app.dialog.alert('Error occured at get order list ');
								return;
							}
						},
						'json');
				
			

            },
            getHistoryList: function () {
                var self = this;
				var self = this;
				var data = {
                    CustomerCode: self.$root.MajorToken,
                    UserCode: self.$root.MinorToken,
                };

					self.$app.preloader.show();
					self.$app.request.getJSON(API_URL.HISTORY_ORDERS + '&MajorToken=' + data.CustomerCode + '&MinorToken=' + data.UserCode, function (result, xhr, status) {
						self.$app.preloader.hide();
						if (result) {
							
							
							self.$setState({
								isHistoryLoaded: true,
							});
							self.$app.utils.nextFrame(() => {
								self.initHistoryList(result.Data.rows)
							});

							self.$app.methods.setInStorage({ name: 'historyOrdersList', data: result.Data.rows });
							
						} else {
							self.$app.dialog.alert('Something wrong, try again later');
						}

					},
						function (xhr, status) {
							self.$app.preloader.hide();
							if (!xhr) {
								self.$app.dialog.alert('Error occured at get order list ');
								return;
							}
						},
						'json');
				
            },
            

        },

        on: {
            pageInit: function (e, page) {
                var self = this;
                self.getRecentList(self.$app.data.MajorToken)
                self.getHistoryList(self.$app.data.MajorToken);
          
                
                var pageRecent = page.$el.find('.page-content-recent-order');
                var pageHistory = page.$el.find('.page-content-history-order');

                var filterMenuOpenEl = page.$el.find('.filterMenuOpen');

                filterMenuOpenEl.hide()
       
                var tabsEl = page.$pageEl.find('.tab');


                tabsEl.on('tab:show', function (page) {
                    if (this.id === "historyOrders") {
                        self.$setState({
                            CurrentTab: this.id,
                            ToolbarAdditionaClass: ''
                        });
                        filterMenuOpenEl.hide()
                    } else {
                        self.$setState({
                            CurrentTab: this.id,
                            ToolbarAdditionaClass: 'toolbar-size-2'
                        });
                        filterMenuOpenEl.hide()
                        self.SearchbarRecent.clear();

                        let buttonAddRecentOrder = self.$el.find('.addRecent');


                        buttonAddRecentOrder.on('click', function () {
                            self.$app.popup.open('.popup-fullscreen-newtemplate')
                            newtemplateView.router.navigate({
                                name: 'new-request-quote',
                                query: {
                                    code: ''
                                },
                            });
                        });
                    }

                    self.$setState({
                        CurrentTab: this.id
                    });


                });

                self.initSearchHistory()
                self.initSearchRecents()


                var buttonAddRecent = page.$el.find('.addRecent');

                buttonAddRecent.on('click', function () {

                    self.$app.popup.open('.popup-fullscreen-newtemplate')
                    newtemplateView.router.navigate({
                        name: 'new-request-quote',
                        query: {
                            code: ''
                        },
                    });

                });





                pageRecent.on('click', '.recentOrderMenu', function (e) {
                    var code = $$(e.target).closest('li').data('code');

                    self.$app.popover.create({
                        backdrop: false,
                        closeByOutsideClick: true,
                        targetEl: e.target,
                        content: '<div class="popover menu-popover" >' +
                            '<div class="popover-inner">' +
                            '<div class="list rightMenuListRecent">' +
                            '<ul>' +
                            '<a href="#" class="item-link editRecent list-button  popover-close"> View Order</a>' +

                            


                            '</ul>' +
                            '</div> ' +
                            '</div>' +
                            '</div>',
                        on: {
                            open: function (popover) {
                                
                                var buttonEdit = popover.$el.find('.editRecent');
                                buttonEdit.on('click', function () {
console.log('code',code)

                                    self.$app.popup.open('.popup-fullscreen-newtemplate')
                                    newtemplateView.router.navigate({
                                        name: 'new-request-quote',
                                        query: {
                                            code: code
                                        },
                                    });

                                });


                            },
                            closed: function (popover) {
                                popover.$el.remove();
                                popover.destroy();
                            }
                        }
                    }).open();
                });
				
				
				
				pageHistory.on('click', '.historyOrderMenu', function (e) {
                    var code = $$(e.target).closest('li').data('code');

                    self.$app.popover.create({
                        backdrop: false,
                        closeByOutsideClick: true,
                        targetEl: e.target,
                        content: '<div class="popover menu-popover" >' +
                            '<div class="popover-inner">' +
                            '<div class="list rightMenuListHistory">' +
                            '<ul>' +
                            '<a href="#" class="item-link editHistory list-button  popover-close"> View Order</a>' +

                           


                            '</ul>' +
                            '</div> ' +
                            '</div>' +
                            '</div>',
                        on: {
                            open: function (popover) {
                               
                                var buttonEdit = popover.$el.find('.editHistory');
                                buttonEdit.on('click', function () {


                                    self.$app.popup.open('.popup-fullscreen-newtemplate')
                                    newtemplateView.router.navigate({
                                        name: 'new-request-quote',
                                        query: {
                                            code: code
                                        },
                                    });

                                });


                            },
                            closed: function (popover) {
                                popover.$el.remove();
                                popover.destroy();
                            }
                        }
                    }).open();
                });

			},
            pageBeforeRemove: function () {

                if (this.VirtualHistoryList) {
                    this.VirtualHistoryList.destroy();
                }
                if (this.VirtualRecentList) {
                    this.VirtualRecentList.destroy();
                }
                if (this.SearchbarHistory) {
                    this.SearchbarHistory.destroy();
                }
                if (this.SearchbarRecent) {
                    this.SearchbarRecent.destroy();
                }
            }

        }
    };
</script>