<!--suppress JSAnnotator -->
<template>
    <!-- Page, data-name contains page name which can be used in callbacks -->
    <div class="page " data-name="asset-playback">
        <!-- page-with-subnavbar -->
        <!-- Top Navbar -->
        <div class="navbar">
            <div class="navbar-inner">
                <div class="left">
                    <a href="#" class="link back">
                        <i class="icon icon-back"></i>
                    </a>
                </div>
                <div class="title sliding">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG00}}</div>
                <div class="right">
                    <!-- <a href="#" class="link">
                                                 <i class="f7-icons icon-notification"></i>
                                             </a>    -->
                </div>
            </div>
        </div>
        <div class="bottom-section-wrapper bottom-section-button-wrapper bg-color-white">
            <div class="row">
                <label for="submit-form-playback" class="col button button-fill color-green elevation-2" tabindex="0">{{@global.LANGUAGE.COM_MSG00}}</label>
            </div>
        </div>
        <!-- Scrollable page content-->
        <form name="AssetPlaybackForm" class="page-content">
            <input type="hidden" name="IMEI" value="{{IMEI}}">
            <input type="hidden" name="Id" value="{{Id}}">
            <input type="submit" id="submit-form-playback" class="display-none" />
            <div class="block-title text-color-darkgray">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG00}}</div>
            <div class="block">
                <p>{{@global.LANGUAGE.PROMPT_MSG039}}</p>
            </div>
            <div class="list ">
                <ul>
                    <li>
                        <div class="item-content three-rows">
                            <!-- <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-name"></i>
                                </div> -->
                            <div class="item-inner">
                                <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG00}}</div>
                                <div class="item-after">{{Name}}</div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="item-content">
                            <!-- <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-imei"></i>
                                </div> -->
                            <div class="item-inner">
                                <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG01}}</div>
                                <div class="item-after">{{IMEI}}</div>
                            </div>
                        </div>
                    </li>
                    {{#if SolutionType}}
                    <li>
                        <div class="item-content">
                            <!-- <div class="item-media text-color-lightgray">

                            </div> -->
                            <div class="item-inner">
                                <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG18}}</div>
                                <div class="item-after">{{SolutionType}}</div>
                            </div>
                        </div>
                    </li>
                    {{/if}}
                    {{#if Registration}}
                    <li>
                        <div class="item-content">
                            <!-- <div class="item-media text-color-lightgray">

                                </div> -->
                            <div class="item-inner">
                                <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG15}}</div>
                                <div class="item-after">{{Registration}}</div>
                            </div>
                        </div>
                    </li>
                    {{/if}}
                    {{#if Describe1}}
                    <li>
                        <div class="item-content">
                            <!-- <div class="item-media text-color-lightgray">

                                </div> -->
                            <div class="item-inner">
                                <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG16}}</div>
                                <div class="item-after">{{Describe1}}</div>
                            </div>
                        </div>
                    </li>
                    {{/if}}
                    {{#if Describe2}}
                    <li>
                        <div class="item-content">
                            <!-- <div class="item-media text-color-lightgray">

                                </div> -->
                            <div class="item-inner">
                                <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG17}}</div>
                                <div class="item-after">{{Describe2}}</div>
                            </div>
                        </div>
                    </li>
                    {{/if}}
                </ul>
            </div>
            <div class="list no-hairlines">
                <ul>
                    <li class="item-content">
                        <div class="item-inner">
                            <div class="item-title">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG01}}</div>
                            <div class="item-after">
                                <label class="toggle">
                                    <input type="checkbox" name="checkbox-optimized" checked="checked">
                                    <span class="toggle-icon"></span>
                                </label>
                            </div>
                        </div>
                    </li>
                    <li class="item-content">
                        <div class="item-inner">
                            <div class="item-title">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG22}}</div>
                            <div class="item-after">
                                <label class="toggle">
                                    <input type="checkbox" name="checkbox-hidezerosignal" checked="checked">
                                    <span class="toggle-icon"></span>
                                </label>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="item-content item-input startDateTimeWrapper" data-input-name="StartDateTime">
                            <div class="item-media text-color-lightgray">
                                <i class="f7-icons icon-calendar"></i>
                            </div>
                            <div class="item-inner">
                                <div class="item-title item-label">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG02}}</div>
                                <div class="item-input-wrap">
                                    <input type="text" name="StartDateTime" class="StartDateTime" placeholder="{{@global.LANGUAGE.ASSET_PLAYBACK_MSG02}}" value="{{StartDateTime}}" maxlength="200" readonly>
                                </div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="item-content item-input endDateTimeWrapper" data-input-name="EndDateTime">
                            <div class="item-media text-color-lightgray">
                                <i class="f7-icons icon-calendar"></i>
                            </div>
                            <div class="item-inner">
                                <div class="item-title item-label">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG03}}</div>
                                <div class="item-input-wrap">
                                    <input type="text" name="EndDateTime" placeholder="{{@global.LANGUAGE.ASSET_PLAYBACK_MSG03}}" value="{{EndDateTime}}" maxlength="200" readonly>
                                </div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <label class="item-checkbox item-content">
                            <input type="checkbox" name="SendByEmail" />
                            <div class="item-media text-color-lightgray">
                                <i class="f7-icons icon-email"></i>
                            </div>
                            <div class="item-inner">
                                <div class="item-title">{{@global.LANGUAGE.COM_MSG118}}</div>
                                <div class="item-after">
                                    <i class="icon icon-checkbox"></i>
                                </div>
                            </div>
                        </label>
                    </li>
                    {{#if ContactListShow}}
                        {{#if ContactList}}
                        <li key="NotificationTo">
                            <a class="item-link smart-select smart-select-init custom-smart-select custom-smart-select-contact-list" data-open-in="popup" data-searchbar="true" data-searchbar-placeholder="{{@global.LANGUAGE.COM_MSG02}}" data-append-searchbar-not-found="{{@global.LANGUAGE.PROMPT_MSG008}}" data-page-title = "{{@global.LANGUAGE.REPORT_PANEL_MSG23}}">
                                <select name="ContactList" multiple required validate>
                                    {{#ContactList}}
                                    {{#if EMail}}
                                    <option value="{{Code}}" data-display-as="{{EMail}}">{{FullName}}({{EMail}})</option>
                                    {{/if}}
                                    {{/ContactList}}
                                </select>
                                <div class="item-content item-input">
                                    <div class="item-media text-color-lightgray">
                                        <i class="f7-icons icon-email"></i>
                                    </div>
                                    <div class="item-inner">
                                        <div class="item-title item-label">{{@global.LANGUAGE.REPORT_PANEL_MSG23}}</div>
                                    </div>
                                </div>
                            </a>
                        </li>
                        {{else}}
                        <div key="PreloaderContactList" class="block text-align-center">
                            <div class="preloader color-red"></div>
                        </div>
                        {{/if}}
                    {{/if}}
                </ul>
                {{#if ContactListShow}}
                <div class="block-footer">
                    <p>{{@global.LANGUAGE.PROMPT_MSG0108}}</p>
                </div>
                {{/if}}
            </div>
        </form>
    </div>
</template>
<script>
// script must return component object
return {
    data: function() {
        var self = this;
        var ret = {};
        //app.methods.storageSetupTime();
        if (self.$route.params) {
            if (self.$route.params.imei) {
                var assetList = self.$app.methods.getFromStorage('assetList');
                var asset = assetList[self.$route.params.imei];
                //console.log(asset);
                var today = moment().format('MMMM DD YYYY, HH:mm');
                var yesterday = moment().subtract(1, 'days').format('MMMM DD YYYY, HH:mm');

                if (asset) {
                    ret = {
                        Name: asset.Name,
                        IMEI: asset.IMEI,
                        Id: asset.Id,
                        SolutionType: asset.SolutionType,
                        Registration: asset.Registration,
                        Describe1: asset.Describe1,
                        Describe2: asset.Describe2,
                        Describe3: asset.Describe3,
                        Describe4: asset.Describe4,
                        EngineCapacity: asset.EngineCapacity,

                        StartDateTime: yesterday,
                        EndDateTime: today,
                    };






                } else {
                    console.log('There is no asset with such imei');
                }
            } else {
                console.log('There is no imei param');
            }
        } else {
            console.log('There is no params');
        }
        //console.log(ret);
        return ret;
    },
    methods: {
        getPlaybackData: function(data, optimizedState) {
            var self = this;
            
            self.$app.dialog.progress(LANGUAGE.COM_MSG08, !Template7.global.DEALER_PRELOADER_COLOR_CLASS ? '' : Template7.global.DEALER_PRELOADER_COLOR_CLASS);
            self.$app.request.get(API_URL.GET_PLAYBACK_ARR_WITHOUTADDRESSES, data, function(result, xhr, status) {
                   console.log(result);
                   // self.$app.dialog.close();
                    if (result.MajorCode == '000' && result.Data) {
                        var hisArray = result.Data.HisArry;
                        if (!hisArray.length) {
						console.log('hisArray.length',hisArray.length)
                            //self.$app.methods.customNotification({ text: LANGUAGE.COM_MSG35 });
							self.$app.dialog.close();
                            self.$app.dialog.alert(LANGUAGE.COM_MSG35, LANGUAGE.ASSET_PLAYBACK_MSG00, function() {  });
                        } else {
                            self.$app.methods.setInStorage({
                                name: 'historyArray',
                                data: hisArray,
                            });
                            self.$app.methods.setInStorage({
                                name: 'historyEvents',
                                data: result.Data.HisEvents && result.Data.HisEvents.length ? result.Data.HisEvents : []
                            });
                     

                            leftView.router.navigate({
                                name: 'asset-playback-show',
                                params: {
                                    imei: self.IMEI,
                                    optimisedState: optimizedState,
                                    isIgnore: data.IsIgnore,
                                    from: data.From,
                                    to: data.To,
                                },
                            },
                            {
                            	//reloadPrevious: true,
                                /*ignoreCache: true */
                            });

                        }
                    } else if (result.MajorCode == '100' && result.MinorCode == '1002') {
                        self.$app.dialog.alert(LANGUAGE.ASSET_PLAYBACK_MSG04, LANGUAGE.ASSET_PLAYBACK_MSG00, function() { app.dialog.close(); });
                        //app.methods.customDialog({ title: LANGUAGE.ASSET_PLAYBACK_MSG00, text: LANGUAGE.ASSET_PLAYBACK_MSG04});
                    } else {
                        //app.methods.customDialog({ title: LANGUAGE.ASSET_PLAYBACK_MSG00, text: LANGUAGE.COM_MSG36});
                        self.$app.dialog.alert(LANGUAGE.ASSET_PLAYBACK_MSG19, LANGUAGE.ASSET_PLAYBACK_MSG00, function() { app.dialog.close(); });
                    }

                },
                function(xhr, status) {
                    self.$app.dialog.close();
                    self.$app.dialog.alert('Error occured at get Playback data');
                },
                'json');
        },
        getContactList: function(data={}){
            var self = this;

            self.$app.request.post(API_URL.GET_CONTACT_USERS_LIST, data, function (result, xhr, status) {
                    self.$app.preloader.hide();
                    //console.log(result);
                    if (result && result.length) {
                        self.$app.methods.setInStorage({name:'contactList', data:result });
                        var contactList = self.$app.methods.sortContactList(result);
                        self.$setState({
                            //ContactListLoaded: true,
                            ContactList: contactList
                        });
                    }

                },
                function (xhr, status) {
                    self.$app.preloader.hide();
                    self.$app.dialog.alert('Error occurred at Get Contact List ');
                },
                'json');
        },


    },

    on: {
        pageInit: function(e, page) {
            var self = this;
            var form = page.$el.find('[name = "AssetPlaybackForm"]');
            var startDateTimeWrapper = page.$el.find('.startDateTimeWrapper');
            var endDateTimeWrapper = page.$el.find('.endDateTimeWrapper');
            var startDateTimeEl = page.$el.find('input[name="StartDateTime"]');
            var endDateTimeEl = page.$el.find('input[name="EndDateTime"]');
            var sendByEmailEl = page.$el.find('[name="SendByEmail"]');
            var datepickerFormat = 'MMMM DD YYYY, HH:mm';
            var optimizedSwitcher = page.$el.find('input[name="checkbox-optimized"]');
            var isIgnoreSwitcher = page.$el.find('input[name="checkbox-hidezerosignal"]');
            var userInfo = self.$app.methods.getFromStorage('userInfo');

            //console.log(self , 'self')


            self.getContactList({MajorToken: userInfo.MajorToken, MinorToken: userInfo.MinorToken});

            var startPicker = new MaterialDatetimePicker({
                el: startDateTimeEl[0],
                format: datepickerFormat,
                openedBy: 'click',
            });
            var endPicker = new MaterialDatetimePicker({
                el: endDateTimeEl[0],
                format: datepickerFormat,
                openedBy: 'click',
            });

            startDateTimeWrapper.on('click', function() {
                startPicker.open();
            });
            endDateTimeWrapper.on('click', function() {
                endPicker.open();
            });

            sendByEmailEl.on('change', function () {
                self.$setState({
                    ContactListShow: this.checked,
                });
            });

            //startDateTimeWrapper.on('submit', (val) => console.log(`data: ${val}`));

            //picker.on('submit', (val) => console.log(`data: ${val}`));

            form.on('submit', function(e) {
                e.preventDefault();
                let contactListEl = page.$el.find('[name="ContactList"]');
                let tz = moment().format("ZZ");
					let formatTz = tz.slice(0, -2)
					let intTz =  parseInt(formatTz)

                  //  .utc().utcOffset(userInfo.UserInfo.TimeZone * -1 + intTz)
                let from = startDateTimeEl.val();
                let to = endDateTimeEl.val();

               //~ from = moment(from, datepickerFormat).utc().utcOffset(userInfo.UserInfo.TimeZone * -1 + intTz).format(window.COM_TIMEFORMAT2);
               //~ to = moment(to, datepickerFormat).utc().utcOffset(userInfo.UserInfo.TimeZone * -1 + intTz).format(window.COM_TIMEFORMAT2);
			   
			   from = moment(from, datepickerFormat).utc().format(window.COM_TIMEFORMAT2);
               to = moment(to, datepickerFormat).utc().format(window.COM_TIMEFORMAT2);


                if (sendByEmailEl.is(':checked')){
                    let contactCodes = contactListEl.val();
                    let recipients = [];
                    if(contactCodes.length && self.ContactList){
                        for (var i = contactCodes.length - 1; i >= 0; i--) {
                            recipients.push(self.ContactList.find(x => x.Code === contactCodes[i]).EMail);
                        }
                    }

                    /*let offsetZZformat = self.$app.methods.convertTimZoneValToZZformat(userInfo.UserInfo.TimeZone);
                    let data = {
                        Assets: [
                            {
                                Name: self.Name,
                                IMEI: self.IMEI,
                                Id: self.Id,
                                Make: self.Describe1,
                                Model: self.Describe2,
                                Color: self.Describe3,
                                Year: self.Describe4,
                                Registration: self.Registration,
                                EngineCapacity: self.EngineCapacity,
                            },
                        ],
                        DateFrom: from, // UTC!
                        DateTo: to, // UTC!
                        extension: "pdf", // pdf, xlsx, json, html
                        Logo: self.$app.data.AppDetails.logoExternal ? self.$app.data.AppDetails.logoExternal : 'https://client.quikloc8.com/resources/images/login/client/logo.png',
                        MajorToken: userInfo.MajorToken,
                        MinorToken: userInfo.MinorToken,
                        Recipients: recipients,
                        displayTimeZone: self.$app.methods.findTimeZoneNameByOffset(offsetZZformat),
                    };

                    self.$app.methods.sendReportPlaybackOnEmail(data, function(){
                        //success
                        self.$app.methods.customNotification({text: LANGUAGE.PROMPT_MSG0109});
                    });*/
                    let templateData = {
                        MinorToken: self.$root.MinorToken,
                        MajorToken: self.$root.MajorToken,
                        TimeZone: userInfo.TimeZone,
                        Code: self.Id?.toString(),
                        From: from,
                        To: to,
                        IMEI: self.IMEI,
                        Logo: self.$app.data.logoExternal,
                    };
                    let data = {
                        PaperKind: 9,
                        Orientation: 1,
                        Url: API_URL.REPORT_PLAYBACK_URL_TEMPLATE + '?' + self.$app.utils.serializeObject(templateData),

                        recipients: recipients
                    };

                    self.$app.preloader.show();
                    self.$app.methods.sendReportPlaybackOnEmail(data, function(downloadLink){
                        self.$app.preloader.hide();

                        self.$app.methods.customNotification({ text: "An email will be sent once it's ready" });

                        //success
                        //self.$app.methods.customNotification({text: LANGUAGE.PROMPT_MSG067});
                        // self.$app.methods.customDialog({
                        //     text: LANGUAGE.PROMPT_MSG0135,
                        //     buttons: [
                        //         {
                        //             text: LANGUAGE.COM_MSG134,
                        //         },
                        //         {
                        //             text: LANGUAGE.COM_MSG31,
                        //             onClick: function () {
                        //                 self.$app.methods.openExternal(downloadLink)
                        //             }
                        //         }
                        //     ]
                        // });
                    }, function () {
                        self.$app.preloader.hide();
                        //err
                    });
                }else{
                    let data = {
                        MinorToken: userInfo.MinorToken,
                        //MajorToken: userInfo.MajorToken,
                        Code: page.$el.find('input[name="Id"]').val()?.toString(),
                        From: from,
                        To: to,
                        IsIgnore: isIgnoreSwitcher.is(':checked')
                    };

                    self.getPlaybackData(data, optimizedSwitcher.is(':checked'));
                }


                return false;
            });


        },
        pageAfterOut: function() {
            /*var toggleAll = self.$app.toggle.get('.toggle-all-alarm');
            console.log(toggleAll);*/
        },

    }
};
</script>