import VueSelect from '/Components/Common/VueSelect.js?v=3.9'
import InputSearch from '/Components/Common/InputSearch.js?v=3.9'
import SearchPanel from '/Components/Common/SearchPanelWrapper.js?v=3.9'
import OperationsPanel from "/Components/Common/OperationsPanelWrapper.js?v=3.9"
import Pager from '/Components/Common/Pager.js?v=3.9'
import NoRecords from '/Components/Common/NoRecords.js?v=3.9'
import DatePicker from '/Components/Common/DatePicker.js?v=3.9'
import DoubleScrollGridWrapper from '/Components/Common/DoubleScrollGridWrapper.js?v=3.9'
import { getLabelText, getStatusString } from '/Components/Common/utils.js?v=3.9'
import Loading from "/Components/Common/Loading.js?v=3.9"

export default {
    props: {
        readOnly: { type: Boolean, required: true },
        customerId: { type: String, required: true },
        isLoggedInAsReseller: { type: Boolean, required: true },
        isLoggedInAsCustomer: { type: Boolean, required: true },
        showCustomerNumber: { type: Boolean, required: true },
        lastSuccessSyncFromDate: { type: String, required: true },
        lastSuccessSyncToDate: { type: String, required: true },
        sortPreference: { type: Object, required: true }
    },
    components: {
        OperationsPanel,
        SearchPanel,
        VueSelect,
        InputSearch,
        NoRecords,
        Pager,
        DatePicker,
        DoubleScrollGridWrapper,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            owners: {},
            statuses: accountStatusList,
            search: {
                selectedOwner: '',
                exchOrgId: '',
                mailboxId: '',
                clientId: (this.customerId != '0' ? this.customerId : ''),
                customerName: '',
                orgName: '',
                domainName: '',
                deviceType: '',
                deviceId: '',
                deviceModel: '',
                deviceFriendlyName: '',
                deviceImei: '',
                deviceStatus: '',
                clientVersion: '',
                deviceUserAgent: '',
                syncStatus: '',
                deviceOS: '',
                devicePolicyApplied: '',
                lastSuccessSyncFrom: this.lastSuccessSyncFromDate,
                lastSuccessSyncTo: this.lastSuccessSyncToDate,
                mailbox: '',
                clientCompanyName: '',

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'MailboxId',
                sortDir: 'Asc',
                updateSorting: false
            },
            showClearButton: false,
            colsWidthSum: 10552,
        }
    },
    methods: {
        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

            if (obj.submit == true)
                this.doSearch();
        },
        getLabelText,
        getStatusString,
        sortBy: function (exp) {

            if (this.search.sortExpression != exp) {
                this.search.sortExpression = exp;
                this.search.sortDir = "Asc";
            }
            else
                this.search.sortDir = this.search.sortDir == "Asc" ? "Desc" : "Asc";

            this.search.updateSorting = true;
            this.doSearch();
        },
        ownerChangeHandler: async function (obj) {

            this.search.selectedOwner = obj.selectedValue;
            setOwnerCookie(obj.selectedValue);

            if (this.subresellers.show) {
                await this.ListSubResellers();
            }

        },
        listOwners: async function () {

            var vm = this;

            await fetch("/webservices/machpanelservice.asmx/GetOwners", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.owners = JSON.parse(data.d);                    
                    vm.search.selectedOwner = vm.owners.initialValue;

                })
                .catch(function (e) {
                    displayErrorMsg(e);
                });

        },
        listRecords: async function () {

            var vm = this;
            vm.isLoading = true;
            let postRequest = { ...fetchPost };
            postRequest.body = JSON.stringify(vm.search);

            await fetch("/RCC/Exchange/MailboxDevices.aspx/GetMailboxDevices", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.search.updateSorting = false;
                    vm.records = JSON.parse(data.d);
                    if (vm.records.length > 0) {
                        vm.totalRecords = vm.records[0].TotalRecords;
                    }
                });
            vm.isLoading = false;
        },
        exportToExcel: function () {
            var vm = this;

            let postRequest = { ...fetchPost };
            postRequest.body = JSON.stringify(vm.search);

            fetch("/RCC/Exchange/MailboxDevices.aspx/ExportToExcel", postRequest)
                .then(response => response.json()).then((data) => {
                    if (data && data.d && data.d != '')
                        window.open('/DownloadHandler.ashx', "_blank");
                })
                .catch(function (e) {
                    displayErrorMsg(e);
                });

        },
        fromDateSelectHandler: function (d) {
            this.search.lastSuccessSyncFrom = d.selectedDateStr;
        },
        toDateSelectHandler: function (d) {
            this.search.lastSuccessSyncTo = d.selectedDateStr;
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {
            this.search.selectedOwner = this.owners.initialValue;
            this.search.exchOrgId = '';
            this.search.mailboxId = '';
            this.search.clientId = (this.customerId != '0', this.customerId, '');
            this.search.customerName = '';
            this.search.orgName = '';
            this.search.domainName = '';
            this.search.deviceType = '';
            this.search.deviceId = '';
            this.search.deviceModel = '';
            this.search.deviceFriendlyName = '';
            this.search.deviceImei = '';
            this.search.deviceStatus = '';
            this.search.clientVersion = '';
            this.search.deviceUserAgent = '';
            this.search.syncStatus = '';
            this.search.deviceOS = '';
            this.search.devicePolicyApplied = '';
            this.search.mailbox = '';
            this.search.clientCompanyName = '';

            this.search.pageIndex = 1;

            updateSelectInterface();    //Required to update SOL control in case of html select.
            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
    },
    created: async function () {

        this.search.sortDir = this.sortPreference.SortDirection;
        this.search.sortExpression = this.sortPreference.SortExpression;

        var vm = this;

        await this.listOwners().then(this.listRecords).catch(function (e) {
            vm.records = [];
            vm.totalRecords = 0;
            vm.isLoading = false;
            displayErrorMsg(e);
        });

    },
    template: `

        <div class="col-xs-12">
            <div class="card">
                <div class="header"><h3>{{ getLabelText('MailboxDevices') }}</h3></div>
                <div class="body">
                    <div class="row">

                        <OperationsPanel>
                            <a @click.prevent="exportToExcel" class="btn btn-primary waves-effect btnAction" v-if="!readOnly" >{{getLabelText("Ex001")}}</a>
                        </OperationsPanel>

                        <SearchPanel id='mailboxdevices-list' :showClearButton="showClearButton" @onSearch='doSearch' @onClear='doClearSearch'>

                            <div :class="searchContainerDivClass" v-if="owners.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="owners.items" :selectedValue="this.search.selectedOwner" @selectchange="ownerChangeHandler" />
                                </div>
                            </div>

                            <InputSearch :searchValue="search.exchOrgId" fieldName="exchOrgId" v-if="!isLoggedInAsCustomer" fieldDataType="Number" :fieldLabel="getLabelText('OrganizationID')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.mailboxId" fieldName="mailboxId" v-if="!isLoggedInAsCustomer" fieldDataType="Number" fieldLabel="Mailbox Id" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.orgName" fieldName="orgName" :fieldLabel="getLabelText('DGN1110608')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.domainName" fieldName="domainName" :fieldLabel="getLabelText('DGN1110516')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.clientId" fieldName="clientId" fieldDataType="Number" v-if="!isLoggedInAsCustomer" :fieldLabel="getLabelText('GN0000715')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.customerName" fieldName="customerName" v-if="!isLoggedInAsCustomer" :fieldLabel="getLabelText('GN0000268')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.clientCompanyName" fieldName="clientCompanyName" v-if="!isLoggedInAsCustomer" :fieldLabel="getLabelText('CustomerCompanyName')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.mailbox" fieldName="mailbox" :fieldLabel="getLabelText('USM0191')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.deviceType" fieldName="deviceType" :fieldLabel="getLabelText('SPT002214')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.deviceId" fieldName="deviceId" :fieldLabel="getLabelText('DeviceID')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.deviceModel" fieldName="deviceModel" :fieldLabel="getLabelText('DeviceModel')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.deviceFriendlyName" fieldName="deviceFriendlyName" :fieldLabel="getLabelText('DeviceFriendlyName')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.deviceImei" fieldName="deviceImei" :fieldLabel="getLabelText('DeviceImei')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.deviceStatus" fieldName="deviceStatus" :fieldLabel="getLabelText('SPT002206')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.clientVersion" fieldName="clientVersion" :fieldLabel="getLabelText('ClientVersion')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.deviceUserAgent" fieldName="deviceUserAgent" :fieldLabel="getLabelText('DeviceUserAgent')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.syncStatus" fieldName="syncStatus" :fieldLabel="getLabelText('SyncStatus')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.deviceOS" fieldName="deviceOS" :fieldLabel="getLabelText('DeviceOS')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.devicePolicyApplied" fieldName="devicePolicyApplied" :fieldLabel="getLabelText('DevicePolicyApplied')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

                            <br/><div :class="searchContainerDivClass">
                                <div class="row">
                                    <div class="col-xs-12 row-label">
                                        <label>{{ getLabelText('LastSuccessSyncFromDate') + ': ' }}</label>
                                    </div>
                                    <DatePicker id='fromDateGlobal1' wrapperClass="col-xs-12" :default-val="search.lastSuccessSyncFrom" @onDateSelected='fromDateSelectHandler' :is-required='true'></DatePicker>
                                </div>
                            </div>

                            <div :class="searchContainerDivClass">
                                <div class="row">
                                    <div class="col-xs-12 row-label">
                                        <label>{{ getLabelText('LastSuccessSyncToDate') + ': ' }}</label>
                                    </div>
                                    <DatePicker id='toDateGlobal2' wrapperClass="col-xs-12" :default-val="search.lastSuccessSyncTo" @onDateSelected='toDateSelectHandler' :is-required='true'></DatePicker>
                                </div>
                            </div>

                        </SearchPanel>

                         <div class="col-xs-12" v-if="isLoading">
                            <Loading/>
                        </div>
                    <div class="col-xs-12" v-else>
                            <DoubleScrollGridWrapper :colsWidthSum="colsWidthSum" v-if="records.length > 0">
                            <table class="table table-bordered table-striped table-hover table-layout-fixed" cellspacing="0" rules="all" border="1" :style="'border-collapse:collapse;width:'+ colsWidthSum + 'px'">
                                <tbody>
                                    <tr>
                                        <th style="width: 250px"><a href="#" @click.prevent="sortBy('MailBoxDisplayName')">{{ getLabelText('USM0191') }}</a></th>
                                        <th style="width: 250px"><a href="#" @click.prevent="sortBy('OrganizationName')">{{ getLabelText('DGN1110608') }}</a></th>
                                        <th style="width: 250px"><a href="#" @click.prevent="sortBy('DeviceType')">{{ getLabelText('SPT002214') }}</a></th>
                                        <th style="width: 250px">{{ getLabelText('DeviceID') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceModel') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceImei') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceFriendlyName') }}</th>
                                        <th style="width: 250px">{{ getLabelText('ClientVersion') }}</th>
                                        <th style="width: 250px">{{ getLabelText('String385') }}</th>
                                        <th style="width: 250px">{{ getLabelText('StatusNote') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceAccessState') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceUserAgent') }}</th>
                                        <th style="width: 250px">{{ getLabelText('SyncStatus') }}</th>
                                        <th style="width: 250px">{{ getLabelText('SPT002206') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceOS') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceOSLanguage') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceWipeSentTime') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceWipeRequestTime') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceWipeAckTime') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DevicePhoneNumber') }}</th>
                                        <th style="width: 250px">{{ getLabelText('MailboxLogReport') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceEnableOutboundSMS') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceMobileOperator') }}</th>
                                        <th style="width: 250px">{{ getLabelText('FAM0057') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceGuid') }}</th>
                                        <th style="width: 250px">{{ getLabelText('IsRemoteWipeSupported') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceAccessStateReason') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DeviceAccessControlRule') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DevicePolicyApplied') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DevicePolicyApplicationStatus') }}</th>
                                        <th style="width: 250px">{{ getLabelText('LastDeviceWipeRequestor') }}</th>
                                        <th style="width: 250px">{{ getLabelText('ClientType') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DaysSinceFirstSync') }}</th>
                                        <th style="width: 250px">{{ getLabelText('DaysSinceLastSync') }}</th>
                                        <th style="width: 250px">{{ getLabelText('NumberOfFoldersSynced') }}</th>
                                        <th style="width: 250px">{{ getLabelText('LastPingHeartbeat') }}</th>
                                        <th style="width: 250px">{{ getLabelText('FirstSyncTime') }}</th>
                                        <th style="width: 250px">{{ getLabelText('LastPolicyUpdateTime') }}</th>
                                        <th style="width: 250px">{{ getLabelText('LastSyncAttemptTime') }}</th>
                                        <th style="width: 250px">{{ getLabelText('LastSuccessSync') }}</th>
                                        <th style="width: 250px">{{ getLabelText('SyncStateUpgradeTime') }}</th>
                                        <th style="width: 250px">{{ getLabelText('RecordTimeStamp') }}</th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td><a v-bind:href="'/RCC/Exchange/ExAccountDetail.aspx?oID=' + record.OrganizationID + '&CS=' + record.MailboxId + '&spass=3'" target='_blank'>{{ record.MailBoxDisplayName + ' [' + record.UPN + ']' }}</a></td>
                                        <td><a v-bind:href="'/RCC/Clients/ExH.aspx?SubId=' + record.ExchHostingID" target='_blank'>{{ record.ExchHostingID + ' - ' + record.OrganizationName }}</a></td>
                                        <td>{{ record.DeviceType }}</td>
                                        <td>{{ record.DeviceID }}</td>
                                        <td>{{ record.DeviceModel }}</td>
                                        <td>{{ record.DeviceImei }}</td>
                                        <td>{{ record.DeviceFriendlyName }}</td>
                                        <td>{{ record.ClientVersion }}</td>
                                        <td>{{ record.Status }}</td>
                                        <td>{{ record.StatusNote }}</td>
                                        <td>{{ record.DeviceAccessState }}</td>
                                        <td>{{ record.DeviceUserAgent }}</td>
                                        <td>{{ record.SyncStatus }}</td>
                                        <td>{{ record.DeviceStatus }}</td>
                                        <td>{{ record.DeviceOS }}</td>
                                        <td>{{ record.DeviceOSLanguage }}</td>
                                        <td>{{ record.DeviceWipeSentTime }}</td>
                                        <td>{{ record.DeviceWipeRequestTime }}</td>
                                        <td>{{ record.DeviceWipeAckTime }}</td>
                                        <td>{{ record.DevicePhoneNumber }}</td>
                                        <td>{{ record.MailboxLogReport }}</td>
                                        <td>{{ record.DeviceEnableOutboundSMS }}</td>
                                        <td>{{ record.DeviceMobileOperator }}</td>
                                        <td>{{ record.Identity }}</td>
                                        <td>{{ record.Guid }}</td>
                                        <td>{{ record.IsRemoteWipeSupported }}</td>
                                        <td>{{ record.DeviceAccessStateReason }}</td>
                                        <td>{{ record.DeviceAccessControlRule }}</td>
                                        <td>{{ record.DevicePolicyApplied }}</td>
                                        <td>{{ record.DevicePolicyApplicationStatus }}</td>
                                        <td>{{ record.LastDeviceWipeRequestor }}</td>
                                        <td>{{ record.ClientType }}</td>
                                        <td>{{ record.DaysSinceFirstSync }}</td>
                                        <td>{{ record.DaysSinceLastSync }}</td>
                                        <td>{{ record.NumberOfFoldersSynced }}</td>
                                        <td>{{ record.LastPingHeartbeat }}</td>
                                        <td>{{ record.FirstSyncTime }}</td>
                                        <td>{{ record.LastPolicyUpdateTime }}</td>
                                        <td>{{ record.LastSyncAttemptTime }}</td>
                                        <td>{{ record.LastSuccessSync }}</td>
                                        <td>{{ record.SyncStateUpgradeTime }}</td>
                                        <td>{{ record.RecordTimeStamp }}</td>

                                    </tr>

                                </tbody>
                            </table>
                            </DoubleScrollGridWrapper>

                            <table v-if="records.length > 0" class="table table-bordered table-striped table-hover">
                                <tbody>
                                    <Pager :totalRecords="this.totalRecords" :pageSize="this.search.pageSize" :currentPage="this.search.pageIndex" @pagerChange="pagerChangeHandler" />
                                </tbody>
                            </table>

                            <NoRecords v-else />
                            
                        </div>
                    </div>
                </div>
            </div>
        </div>
`
}
