import VueSelect from '/Components/Common/VueSelect.js?v=3.4'
import InputSearch from '/Components/Common/InputSearch.js?v=3.4'
import DatePicker from '/Components/Common/DatePicker.js?v=3.4'
import SearchPanel from '/Components/Common/SearchPanelWrapper.js?v=3.4'
import Pager from '/Components/Common/Pager.js?v=3.4'
import NoRecords from '/Components/Common/NoRecords.js?v=3.4'
import ModalPopUp from '/Components/Common/ModalPopUp.js?v=3.4'
import { getLabelText } from '/Components/Common/utils.js?v=3.4'
import Loading from "/Components/Common/Loading.js?v=3.4"


export default {
    props: {
        globalFromDate: { type: String, required: true },
        globalToDate: { type: String, required: true },
        isLoggedInAsCustomer: { type: Boolean, required: true },
        isLoggedInAsReseller: { type: Boolean, required: true },
        sortPreference: { type: Object, required: true }
    },
    components: {
        SearchPanel,
        VueSelect,
        InputSearch,
        DatePicker,
        ModalPopUp,
        NoRecords,
        Pager,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            recordDetails: [],
            owners: {},
            search: {
                selectedOwner: '',
                vmName: '',
                subscriptionId: '',
                customerName: '',
                fromDateGlobal: this.globalFromDate,
                toDateGlobal: this.globalToDate,

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'CompanyName',
                sortDir: 'Asc',
                updateSorting: false
            },
            showClearButton: false,

            //***** START: Modal Popup *******
            showModal: false,
            modalTitle: '',
            yesText: '',
            parentContext: {},  //params to execute callback method related to current operation
            //***** END: Modal Popup *******
        }
    },
    methods: {
        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

            if (obj.submit == true)
                this.doSearch();
        },
        ownerChangeHandler: function (obj) {

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

        },
        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);
                    this.search.selectedOwner = this.owners.initialValue;

                })
           
        },
        getLabelText,
        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();
        },
        listRecords: async function () {

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

            await fetch("/RCC/VPS/VPSUsageReport.aspx/GetVMUpTimeReport", 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;
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {
             
            this.search.vmName = '';
            this.search.subscriptionId = '';
            this.search.customerName = '';

            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);
            });
        },
        fromDateSelectHandler: function (d) {
            this.search.fromDateGlobal = d.selectedDateStr;
        },
        toDateSelectHandler: function (d) {
            this.search.toDateGlobal = d.selectedDateStr;
        },
        mpModelEventHandler: function (obj) {
            //if (obj.submit == true) {
            //    if (obj.parentContext.op == "convert") {
            //        this.convertToPaidSubscriptions(obj);
            //    }
            //}

            this.recordDetails = [];
            this.showModal = false;
        },
        showUpTimeDetails: async function (vId) {

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                "vpsId": vId,
                "fromDateGlobal": this.search.fromDateGlobal,
                "toDateGlobal": this.search.toDateGlobal
            }
            postRequest.body = JSON.stringify(params);
            
            await fetch("/RCC/VPS/VPSUsageReport.aspx/GetVMUpTimeDetails", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.recordDetails = JSON.parse(data.d);
                    vm.showModal = true;
                    vm.parentContext = { op: "convert" };
                    vm.modalTitle = 'UpTime Detail';

                    //if (vm.recordDetails.length > 0) {
                    //    vm.totalRecords = vm.records.length;
                    //}
                }).catch(function (e) {
                    vm.recordDetails = [];
                    //vm.totalRecords = 0;
                    displayErrorMsg(e);
                });

                      
        },
    },
    created: async function () {

        this.search.sortDir = this.sortPreference.SortDirection;
        this.search.sortExpression = this.sortPreference.SortExpression;
        //alert(new Date(this.globalFromDate));
        //this.fromDateGlobal = new Date(this.globalFromDate).toDateString();
        //this.toDateGlobal = new Date(this.globalToDate).toDateString();

        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="body">
                    <div class="row">

                        <ModalPopUp v-if="showModal" :id="'showUpTime'" :parentContext="parentContext" :modalTitle="modalTitle" :yesButtonText="yesText" :noButtonText="yesText"
                            @onYes="mpModelEventHandler" @onNo="mpModelEventHandler">
                            <table class="table table-bordered table-striped table-hover table-layout-fixed" cellspacing="0" rules="all" border="1">
                                <tbody>
                                    <tr>
                                        <th class="col-xs-3">{{ getLabelText('SMI0240') }}</th>
                                        <th class="col-xs-5">{{ getLabelText('GN0000721') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strUptimeHours') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strDownTimeHours') }}</th>
                                    </tr>
                                    <tr v-for="record in recordDetails">
                                        <td>{{ record.VMName }}</td>
                                        <td>{{ record.RecordDate }}</td>
                                        <td>{{ record.UpTime }}</td>
                                        <td>{{ record.DownTime }}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </ModalPopUp>

                        <SearchPanel id='vpsuptimereport-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.customerName" v-if="!isLoggedInAsCustomer && !isLoggedInAsReseller" fieldName="customerName" :fieldLabel="getLabelText('GN0000268')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

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

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

                            <InputSearch :searchValue="search.subscriptionId" fieldName="subscriptionId" fieldDataType="Number" v-if="!isLoggedInAsCustomer && !isLoggedInAsReseller" :fieldLabel="getLabelText('String61')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.vmName" fieldName="vmName" :fieldLabel="getLabelText('SMI0240')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

                        </SearchPanel>

                        <div class="col-xs-12" v-if="isLoading">
                            <Loading/>
                        </div>
                        <div class="col-xs-12" v-else>
                        
                            <table v-if="records.length > 0" class="table table-bordered table-striped table-hover table-layout-fixed" cellspacing="0" rules="all" border="1">
                                <tbody>
                                    <tr>
                                        <th class="col-xs-3">{{ getLabelText('SMI0240') }}</th>
                                        <th class="col-xs-5">{{ getLabelText('GN0000850') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strUptimeHours') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strDownTimeHours') }}</th>
                                    </tr>
                                    <tr v-for="record in records">
                                        <td><a v-bind:href="'/RCC/VPS/VPSAccountDetail.aspx?OID=' + record.VPSID">{{ record.VMName }}</a></td>
                                        <td><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?CID=' + record.CustomerId">{{ '#' + record.CustomerId + ' ' + record.CustomerName + (record.CompanyName == '' ? '' : ' [' + record.CompanyName + ']') }}</a></td>
                                        <td><a @click.left.prevent="showUpTimeDetails(record.VPSID)">{{ record.UpTime }}</a></td>
                                        <td><a @click.left.prevent="showUpTimeDetails(record.VPSID)">{{ record.DownTime }}</a></td>
                                    </tr>

                                    <Pager :totalRecords="totalRecords" :pageSize="this.search.pageSize" :currentPage="this.search.pageIndex" @pagerChange="pagerChangeHandler" />
                                </tbody>
                            </table>

                            <NoRecords v-else />

                        </div>
                    </div>
                </div>
            </div>
        </div>
`
}
