<!--suppress JSAnnotator -->
<template>
    <!-- Page, data-name contains page name which can be used in callbacks -->
    <div class="page " data-name="reports-shedule-edit">
        <!-- 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">{{PageTitle}}</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-report-edit" class="col button button-fill color-green elevation-2"
                    tabindex="0">{{@global.LANGUAGE.COM_MSG06}}</label>
            </div>
        </div>

        <!-- Scrollable page content-->
        <form name="ReportEditForm" class="page-content">
            <!--  under-development -->
            <input type="hidden" name="Code" value="{{Code}}">
            <input type="submit" id="submit-form-report-edit" class="display-none" />

            <div class="list no-margin no-hairlines ">
                <ul>
                    <li>
                        <a class="item-link smart-select smart-select-init custom-smart-select custom-smart-select-type "
                            data-open-in="popover" data-close-on-select="true">
                            <select name="Type">
                                <option value="1" {{#js_if "this.Type == '1' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG00}}</option>
                                <option value="4" {{#js_if "this.Type == '4' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG01}}</option>
                                <option value="3" {{#js_if "this.Type == '3' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG02}}</option>
                                <option value="14" {{#js_if "this.Type == '14' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG77}}</option>
                                <option value="11" {{#js_if "this.Type == '11' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG80}}</option>
                                <option value="13" {{#js_if "this.Type == '13' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG78}}</option>
                                <option value="19" {{#js_if "this.Type == '19' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG109}}</option>
                                <option value="12" {{#js_if "this.Type == '12' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG79}}</option>
                                <option value="16" {{#js_if "this.Type == '16' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG152}}</option>
                                <option value="28" {{#js_if "this.Type == '28' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG197}}</option>
                                <option value="5" {{#js_if "this.Type == '5' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG03}}</option>
                                <option value="7" {{#js_if "this.Type == '7' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG05}}</option>
                                <option value="8" {{#js_if "this.Type == '8' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG07}}</option>
                                <option value="9" {{#js_if "this.Type == '9' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG08}}</option>
                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-header-reports"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.REPORT_PANEL_MSG28}}</div>
                                </div>
                            </div>
                        </a>
                    </li>
                    <li class="item-content item-input ">
                        <div class="item-media text-color-lightgray"><i class="f7-icons icon-profile-name "></i></div>
                        <div class="item-inner">
                            <div class="item-title item-label">{{@global.LANGUAGE.REPORT_PANEL_MSG32}}</div>
                            <div class="item-input-wrap ">
                                <input type="text" name="Name" value="{{Name}}"
                                    placeholder="{{@global.LANGUAGE.REPORT_PANEL_MSG33}}" maxlength="200" required>
                            </div>
                        </div>
                    </li>

                    {{#js_if "this.Type == '11' || this.Type == '14' "}}
                    <li key="geofenceList-key">
                        <a class="item-link smart-select smart-select-init custom-smart-select smartSelectGeofences"
                            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.COM_MSG141}}">
                            <select name="Geofences" multiple required validate>
                                {{#GeofenceList}}
                                <option value="{{Code}}" {{#if Selected}} selected {{/if}}>{{Name}}</option>
                                {{/GeofenceList}}
                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-admin-geofences"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.ASSET_ALARM_MSG12}}</div>
                                </div>
                            </div>
                        </a>
                    </li>
                    {{/js_if}}

                    {{#js_if "this.Type == '14' "}}
                    <li key="reportoptionList-key">
                        <a class="item-link smart-select smart-select-init custom-smart-select smartSelectReportoptions"
                            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.COM_MSG142}}">
                            <select name="Options" multiple required validate>
                                {{#OverviewOptionsList}}
                                <option value="{{Value}}" selected>{{Name}}</option>
                                {{/OverviewOptionsList}}
                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-notification"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.REPORT_ALERT_LIST_MSG31}}
                                    </div>
                                </div>
                            </div>
                        </a>
                    </li>
                    {{/js_if}}
                    {{#js_if "this.Type == '14' || this.Type == '9'"}}

                    <li key="alarmList-key">
                        {{#if selectAllAlarms}}
                        <a class="item-link smart-select smart-select-init custom-smart-select smartSelectAlarms"
                            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.COM_MSG56}}">
                            <select name="AlertList" multiple required validate>
                                {{#AlertList}}
                                {{#js_if "this.Name"}}
                                <option value="{{AlertId}}" selected>{{Name}}</option>
                                {{/js_if}}
                                {{/AlertList}}
                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-report-alarm-report"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.REPORT_ALERT_LIST_MSG32}}
                                    </div>
                                </div>
                            </div>
                        </a>
                        {{else}}


                        <a class="item-link smart-select smart-select-init custom-smart-select smartSelectAlarms"
                            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.COM_MSG56}}">
                            <select name="AlertList" multiple required validate>
                                {{#AlertList}}
                                <option value="{{AlertId}}" {{#if Selected}} selected {{/if}}>{{AlertName}}</option>
                                
                                {{/AlertList}}
                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-report-alarm-report"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.REPORT_ALERT_LIST_MSG32}}
                                    </div>
                                </div>
                            </div>
                        </a>

                        {{/if}}

                    </li>

                    <li>
                        <label class="item-checkbox item-content">
                            <input type="checkbox" name="selectAllAlarms" id="selectAllAlarms"  {{#if selectAllAlarms}} />
                            <div class="item-media text-color-lightgray">
                            </div>
                            <div class="item-inner">
                                <div class="item-title">Select all by default</div>
                                <div class="item-after">
                                    <i class="icon icon-checkbox"></i>
                                </div>
                            </div>
                        </label>
                    </li>
                    {{/js_if}}

                    {{#unless isDealer}}
                    <li key="assetList-key">

                        {{#if selectAllAssets}}
                        <a class="item-link smart-select smart-select-init custom-smart-select smartSelectAssets"
                            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.ASSET_GROUPS_MSG08}}">
                            <select name="Assets" multiple required validate>
                                {{#AssetList}}
                                <option value="{{Id}}" selected>{{Name}}</option>
                                {{/AssetList}}
                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-name"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.ASSET_GROUPS_MSG09}}</div>
                                </div>
                            </div>
                        </a>
                        {{else}}

                        <a class="item-link smart-select smart-select-init custom-smart-select smartSelectAssets"
                            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.ASSET_GROUPS_MSG08}}">
                            <select name="Assets" multiple required validate>
                                {{#AssetList}}
                                <option value="{{Id}}" {{#if Selected}} selected {{/if}}>{{Name}}</option>
                                {{/AssetList}}
                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-name"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.ASSET_GROUPS_MSG09}}</div>
                                </div>
                            </div>
                        </a>

                        {{/if}}
                    </li>
                    <li>
                        <label class="item-checkbox item-content">
                            <input type="checkbox" name="selectAllAssets" id="selectAllAssets" {{#if selectAllAssets}}
                                checked {{/if}} />
                            <div class="item-media text-color-lightgray">
                            </div>
                            <div class="item-inner">
                                <div class="item-title">Select all by default</div>
                                <div class="item-after">
                                    <i class="icon icon-checkbox"></i>
                                </div>
                            </div>
                        </label>
                    </li>
                    {{/unless}}

                    {{#js_if "this.Type == '1' "}}
                    <li key="TreshHoldNumber" class="item-content item-input ">
                        <div class="item-media text-color-lightgray"><i class="f7-icons icon-voltage "></i></div>
                        <div class="item-inner">
                            <div class="item-title item-label">{{@global.LANGUAGE.REPORT_PANEL_MSG21}}</div>
                            <div class="item-input-wrap ">
                                <input type="tel" name="TreshHoldNumber" value="{{TreshHoldNumber}}" maxlength="200"
                                    pattern="[0-9]*" data-error-message="Only numbers please!" required validate>
                            </div>
                        </div>
                    </li>
                    {{/js_if}}
                    <li>
                        <a class="item-link smart-select smart-select-init custom-smart-select custom-smart-select-frequency"
                            data-open-in="popover" data-close-on-select="true">
                            <select name="Frequency">
                                <option value="D" {{#js_if "this.Frequency == 'D' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG29}}</option>
                                <option value="W" {{#js_if "this.Frequency == 'W' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG30}}</option>
                                <option value="M" {{#js_if "this.Frequency == 'M' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.REPORT_PANEL_MSG31}}</option>

                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray"></div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.REPORT_PANEL_MSG20}}</div>
                                </div>
                            </div>
                        </a>
                    </li>
                    {{#js_if "this.Frequency == 'W' "}}
                    <li key="custom-smart-select-frequency-days">
                        <a class="item-link smart-select smart-select-init custom-smart-select custom-smart-select-frequency-days"
                            data-open-in="popover" data-close-on-select="true">
                            <select name="FrequencyDay">
                                <option value="0" {{#js_if "this.FrequencyDays == '0' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.COM_MSG38}}</option>
                                <option value="1" {{#js_if "this.FrequencyDays == '1' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.COM_MSG39}}</option>
                                <option value="2" {{#js_if "this.FrequencyDays == '2' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.COM_MSG40}}</option>
                                <option value="3" {{#js_if "this.FrequencyDays == '3' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.COM_MSG41}}</option>
                                <option value="4" {{#js_if "this.FrequencyDays == '4' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.COM_MSG42}}</option>
                                <option value="5" {{#js_if "this.FrequencyDays == '5' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.COM_MSG43}}</option>
                                <option value="6" {{#js_if "this.FrequencyDays == '6' " }} selected {{/js_if}}>
                                    {{@global.LANGUAGE.COM_MSG44}}</option>

                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray"></div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.REPORT_PANEL_MSG24}}</div>
                                </div>
                            </div>
                        </a>
                    </li>
                    {{/js_if}}
                    {{#js_if "this.Frequency == 'M' "}}
                    <li key="custom-smart-select-month-days-list">
                        <a class="item-link smart-select smart-select-init custom-smart-select custom-smart-select-month-days-list"
                            data-open-in="popover" data-close-on-select="true">
                            <select name="FrequencyDay">
                                {{#MonthDaysList}}
                                <option value="{{Value}}" {{#js_if "@root.FrequencyDays == this.Value " }} selected
                                    {{/js_if}}>{{Value}}</option>
                                {{/MonthDaysList}}
                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray"></div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.REPORT_PANEL_MSG25}}</div>
                                </div>
                            </div>
                        </a>
                    </li>
                    {{/js_if}}


                    <li class=" tooltip-init"
                        data-tooltip="{{#js_if 'this.AssetList.length == 1'}}{{@global.LANGUAGE.PROMPT_MSG057}}<br>{{@global.LANGUAGE.PROMPT_MSG058}}{{else}}{{@global.LANGUAGE.PROMPT_MSG0116}}{{/js_if}}">
                        <a class="item-link smart-select smart-select-init custom-smart-select custom-smart-select-groups {{#js_if 'this.AssetList.length == 1'}} disabled {{/js_if}}"
                            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.COM_MSG54}}">
                            <select name="AssetGroups" multiple>
                                {{#AssetGroupList}}
                                {{#js_if "this.Code != '000000'"}}
                                <option value="{{Code}}" {{#if Selected}} selected{{/if}}>{{Name}}</option>
                                {{/js_if}}
                                {{/AssetGroupList}}
                            </select>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-admin-groups"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.REPORT_PANEL_MSG53}}</div>
                                </div>
                            </div>
                        </a>
                    </li>
                    <li>
                        <div class="item-content item-input dateStartDatetimeWrapper">
                            <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"
                                        placeholder="{{@global.LANGUAGE.ASSET_PLAYBACK_MSG02}}"
                                        value="{{IntervalValueDate}}" maxlength="200" readonly required validate>
                                </div>
                            </div>
                        </div>
                    </li>
                    <li>
                        <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}}" {{#if Selected}} selected {{/if}}>
                                    {{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>



                </ul>
            </div>

        </form>
    </div>
</template>


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

            let ret = {};
            //let assetList = self.$app.methods.getAssetsByGroups();
            let contactList = self.$app.methods.getFromStorage('contactList');
            contactList = self.$app.methods.sortContactList(contactList);
            let monthDaysList = [];
            for (let i = 1; i <= 28; i++) {
                monthDaysList.push({ Value: i });
            }
            let overviewOptionsList = Protocol.Helper.getOverviewReportOptions();
            let geofenceList = Object.values(self.$app.methods.getFromStorage('geofenceList'));

            let assetGroupList = self.$app.methods.getAssetsByGroups({ NoGroupToBottom: true })
            let assetList = Object.values(self.$app.methods.getFromStorage('assetList'));
            let alarmList = Object.values(self.$app.methods.getFromStorage('alertList'));
            //AlarmList
			console.log('...',alarmList)


            ret = {
                PageTitle: LANGUAGE.REPORT_PANEL_MSG27,
                Type: self.$route.query.type,
                //Code: '000000',
                TreshHoldNumber: 10,
                //Frequency: '',
                //FrequencyDays: '',

                AlertList: alarmList,
                OverviewOptionsList: overviewOptionsList,
                ContactList: contactList,
                MonthDaysList: monthDaysList,
                GeofenceList: geofenceList,
                AssetList: assetList,
                AssetGroupList: assetGroupList,
                DatepickerFormat: 'DD/MM/YYYY',
                isDealer: self.$app.data.CustomerType === 2 || self.$app.data.CustomerType === 6,
                selectAllAssets: true,
                selectAllAlarms: true
            };

            if (self.$route.query.code) {
                ret.PageTitle = LANGUAGE.REPORT_PANEL_MSG138;
                ret.selectAllAssets = false
				ret.selectAllAlarms = false
                let scheduledList = self.$app.methods.getFromStorage('scheduledReportList');
                let details = self.$app.methods.findObjectByKey(scheduledList, 'Code', self.$route.query.code);

                //console.log(self.$route.query.code, 'self.$route.query.code')

                ret.Type = 1; // Low battery

 
                switch (details.ModelType) {

                    case 'LOW_POWER':
                        ret.Type = 1;
                        break;

                    case "DISCONNECT":
                        ret.Type = 4;
                        break;

                    case 'OVERVIEW':
                        ret.Type = 14;
                        break;
                    case 'ALARM_REPORT':
                        ret.Type = 9;
                        break;
                    case 'TRIP_REPORT':
                        ret.Type = 12;
                        break;
                    case 'GEOFENCE_REPORT':
                        ret.Type = 11;
                        break;

                }
                ret.Code = self.$route.query.code;
                ret.Name = details.Name;
                ret.Frequency = details.Type;
                ret.TreshHoldNumber = details.Threshold;
                ret.FrequencyDays = details.Value;

                if (contactList && contactList.length && details.ContactCodes && details.ContactCodes.length) {
                    for (let i = details.ContactCodes.length - 1; i >= 0; i--) {
                        contactList[contactList.findIndex(el => el.Code === details.ContactCodes[i])].Selected = true;
                    }
                }

                console.log('details', details)
                if (details.GroupCode && details.GroupCode !== 'ALL') {
                    let codesArr = details.GroupCode.split(',');
                    //console.log('codesArr', codesArr)
                    //console.log('assetList', assetList)
                    for (let i = 0; i < codesArr.length; i++) {
                        //assetList[assetList.findIndex(el => el.Code === codesArr[i])].Selected = true; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                    }
					
					
                }
				
				if (details.AssetIds.length) {	
					for (let i = 0; i < details.AssetIds.length; i++) {
					console.log('assetList',assetList, assetList[assetList.findIndex(el => el.Id === details.AssetIds[i])])
                        assetList[assetList.findIndex(el => el.Id === details.AssetIds[i])].Selected = true; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                    }
				}
				
				if (details.Alerts.length) {	
					for (let i = 0; i < details.Alerts.length; i++) {
					console.log('Alerts',alarmList, alarmList[alarmList.findIndex(el => el.AlertId == details.Alerts[i])])
                        alarmList[alarmList.findIndex(el => el.AlertId == details.Alerts[i])].Selected = true; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                    }
				}
				ret.isEdit = true
				
				
            }

            if (overviewOptionsList && overviewOptionsList.length) {
                overviewOptionsList.sort(function (a, b) {
                    if (a.Name < b.Name) return -1;
                    if (a.Name > b.Name) return 1;
                    return 0;
                });
            }

            console.log(ret);
            return ret;
        },
        methods: {
            getAlertList: function (data) {
                var self = this;
                //GET_REPORT_GET_ALERTLIST
                /*var data = {
                    MajorToken: userInfo.MajorToken,
                    MinorToken: userInfo.MinorToken,
                };*/
                self.$app.request.post(API_URL.GET_REPORT_ALERTLIST, data, function (result, xhr, status) {
                    if (result.MajorCode == '000') {
                        if (result.Data && result.Data.length) {
                            
							if(!self.isEdit){
								var alarmList = Object.values(self.formatAlertList(result.Data));
								self.$setState({
									AlertList: alarmList,
								});
							}
							
							/*if (self.Details?.Alerts?.length) {	
								for (let i = 0; i < self.Details.Alerts.length; i++) {
									console.log('Alerts',alarmList, alarmList[alarmList.findIndex(el => el.AlertId == self.Details.Alerts[i])])
										alarmList[alarmList.findIndex(el => el.AlertId == self.Details.Alerts[i])].Selected = true; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
									}
								}*/
							
                        }

                    } else {
                        self.$app.dialog.alert('Cant get Alert List');
                    }

                },
                    function (xhr, status) {
                        self.$app.dialog.alert('Error occured at Alert List ');
                    },
                    'json');
            },
            formatAlertList: function (list) {
                if (list && list.length) {
                    let userAlarmSettings = this.$app.methods.getFromStorage('userAlarmSettings');
                    for (var i = list.length - 1; i >= 0; i--) {
                        switch (list[i].AlertId) {
                            case Protocol.PositionAlerts.INPUT1.toString():
                                list[i].Name = userAlarmSettings && userAlarmSettings.Input1High ? userAlarmSettings.Input1High : Protocol.Helper.getAletTypeName(list[i].AlertId)
                                break
                            case Protocol.PositionAlerts.INPUT2.toString():
                                list[i].Name = userAlarmSettings && userAlarmSettings.Input2 ? userAlarmSettings.Input2 : Protocol.Helper.getAletTypeName(list[i].AlertId)
                                break
                            default:
                                list[i].Name = Protocol.Helper.getAletTypeName(list[i].AlertId);
                        }
                    }
                    list.sort(function (a, b) {
                        if (a.Name.toLowerCase() < b.Name.toLowerCase()) return -1;
                        if (a.Name.toLowerCase() > b.Name.toLowerCase()) return 1;
                        return 0;
                    });
                }
                return list;
            },
            getGeofenceList: function () {
                var self = this;
                //console.log('here');

                var userInfo = self.$app.methods.getFromStorage('userInfo');
                //GET_GROUP_LIST
                var data = {
                    MinorToken: userInfo.MinorToken,
                    MajorToken: userInfo.MajorToken,
                };

                // self.$app.preloader.show();
                self.$app.request.post(API_URL.GET_GEOFENCE_LIST, data, function (result, xhr, status) {
                    //self.$app.preloader.hide();
                    //console.log(result);
                    if (result && result.MajorCode == '000') {
                        if (result.Data) {
                            self.$app.methods.setInStorage({ name: 'geofenceList', data: result.Data });

                            self.$app.utils.nextFrame(() => {

                            });

                        }

                    } else {
                        self.$app.utils.nextFrame(function () {
                            leftView.router.back();
                        });
                        self.$app.dialog.alert('Something wrong at getGeofenceList');
                    }

                },
                    function (xhr, status) {
                        //self.$app.preloader.hide();
                        self.$app.dialog.alert('Error occured at getGeofenceList');
                    },
                    'json');

            },
            savetData: function (data) {
                let self = this;

                self.$app.preloader.show();
                self.$app.request.post(API_URL.SET_SCHEDULE_REPORT, data, function (result = {}, xhr, status) {
                    self.$app.preloader.hide();
                    //console.log('result saveData', result);
                    if (result.MajorCode == '000') {
                        if (leftView.router.history && leftView.router.history[leftView.router.history.length - 2].indexOf('/reports-scheduled/') != -1) {
                            leftView.router.back('/reports-scheduled/', { force: true });
                        } else {
                            leftView.router.back();
                        }

                    } else {
                        self.$app.dialog.alert('Something wrong, try again later');
                    }
                },
                    function (xhr, status) {
                        self.$app.preloader.hide();
                        self.$app.dialog.alert('Error occured at Get Report Data ');
                    },
                    'json');
            },




        },

        on: {

            pageInit: function (e, page) {
                let self = this;
                //console.log(leftView.router.history);  

                self.getGeofenceList()
                var userInfo = self.$app.methods.getFromStorage('userInfo');

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



                let form = page.$el.find('[name = "ReportEditForm"]');
                let frequencySelectEl = page.$el.find('[name = "Frequency"]');
                let reportTypeEl = page.$el.find('[name="Type"]');
                let StartDatetimeDateEl = page.$el.find('input[name = "StartDatetime"]');
                if (!self.isDealer) {
                    //data.AssetIds = page.$el.find('[name="Assets"]').val();
                }
                //data.AlarmIds = page.$el.find('[name="Alarms"]').val();

                self.StartDatetimeDatePicker = new MaterialDatetimePicker({
                    el: StartDatetimeDateEl[0],
                    format: self.DatepickerFormat,
                    openedBy: 'click',
                });

                frequencySelectEl.on('change', function () {
                    self.$setState({
                        Frequency: this.value,
                    });
                });

                reportTypeEl.on('change', function () {
                    self.$setState({
                        Type: this.value,
                    });
                });

                page.$el.on('click', '.dateStartDatetimeWrapper', function () {
                    if (self.StartDatetimeDatePicker) {
                        self.StartDatetimeDatePicker.open();
                    }
                });

                form.on('submit', function (e) {
                    e.preventDefault();
                    let frequencyVal = frequencySelectEl.val();
                    let code = page.$el.find('input[name="Code"]').val();
                    let threshold = page.$el.find('input[name="StartDatetime"]').val();
                    let reportType = reportTypeEl.val();
                    let AssetGroups = page.$el.find('[name="AssetGroups"]').val();
                    let features = page.$el.find('[name="Options"]').val();
                    let alerts = page.$el.find('[name="AlertList"]').val();
                    var assetsEl = page.$el.find('[name = "Assets"]');





                    if (!AssetGroups.length) {
                        AssetGroups = 'ALL';
                    } else {
                        AssetGroups = AssetGroups.toString();
                    }

                    let data = {
                        MajorToken: self.$app.methods.getFromStorage('userInfo').MajorToken,
                        MinorToken: self.$app.methods.getFromStorage('userInfo').MinorToken,
                        Name: page.$el.find('input[name="Name"]').val(),
                        Type: frequencyVal,
                        Value: frequencyVal === 'D' ? 0 : page.$el.find('[name="FrequencyDay"]').val(),
                        Threshold: threshold,
                        ContactCodes: page.$el.find('select[name="ContactList"]').val(),
                        GroupCode: AssetGroups,
                        GeofenceCodes: page.$el.find('select[name="Geofences"]').val(),
                        Features: features,
                        Alerts: alerts,
                        AssetIds: assetsEl.val()
                    };

                    switch (reportType) {
                        case '1':
                            data.ModelType = 'LOW_POWER';
                            data.Threshold = page.$el.find('input[name="TreshHoldNumber"]').val();
                            break;

                        case '4':
                            data.ModelType = 'DISCONNECT';
                            break;

                        case '14':
                            data.ModelType = 'OVERVIEW';
                            break;

                        case '9':
                            data.ModelType = 'ALARM_REPORT';
                            break;

                        case '12':
                            data.ModelType = 'TRIP_REPORT';
                            break;

                        case '11':
                            data.ModelType = 'GEOFENCE_REPORT';
                            break;

                    }
                    if (code) {
                        data.Code = code;
                    }

                    //console.log('data savetData', data);
                    self.savetData(data);

                    return false;
                });
                $$(page.$el).on('change', '[name = "selectAllAssets"]', function (el) {
                    self.$setState({
                        selectAllAssets: document.getElementById("selectAllAssets").checked,
                    });
                })
                $$(page.$el).on('change', '[name = "selectAllAlarms"]', function (el) {
                    self.$setState({
                        selectAllAlarms: document.getElementById("selectAllAlarms").checked,
                    });
                })



            },
            pageAfterOut: function () {

            },

        }
    };
</script>