import VueSelect from '/Components/Common/VueSelect.js?v=3.4'
import InputSearch from '/Components/Common/InputSearch.js?v=3.4'
import SearchPanel from '/Components/Common/SearchPanelWrapper.js?v=3.4'
import OperationsPanel from '/Components/Common/OperationsPanelWrapper.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 DoubleScrollGridWrapper from '/Components/Common/DoubleScrollGridWrapper.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: {
        readOnly: { type: Boolean, required: true },
        companyIdFilter: { type: String, required: false, default: '0' },
        hideColumnsDueToQuota: { type: Boolean, required: true },
        isLoggedInAsCustomer: { type: Boolean, required: true },
        isLoggedInAsReseller: { type: Boolean, required: true },
        sortPreference: { type: Object, required: true }
    },
    components: {
        SearchPanel,
        OperationsPanel,
        VueSelect,
        InputSearch,
        DoubleScrollGridWrapper,
        NoRecords,
        Pager,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            owners: {},
            search: {
                selectedOwner: (this.companyIdFilter != '0' ? this.companyIdFilter : ''),
                customerName: '',
                vmName: '',
                serverNode: '',
                companyName: '',

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

            if (obj.submit == true)
                this.doSearch();
        },
        ownerChangeHandler: async 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;

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

        },
        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/GetVPSUsageReport", 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/VPS/VPSUsageReport.aspx/ExportToExcel", postRequest)
                .then(response => response.json()).then((data) => {
                    if (data && data.d && data.d != '')
                        window.open('/DownloadHandler.ashx', "_blank");
                    // console.log(data.d);
                })
                .catch(function (e) {
                    displayErrorMsg(e);
                });

        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {
            
            this.search.customerName = '';
            this.search.vmName = '';
            this.search.serverNode = '';
            this.search.companyName = '';

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

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

                        <SearchPanel id='vpsusagereport-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" fieldName="customerName" :fieldLabel="getLabelText('GN0000268')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.companyName" fieldName="companyName" :fieldLabel="getLabelText('GN00001077')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.serverNode" v-if="!isLoggedInAsCustomer" fieldName="serverNode" :fieldLabel="getLabelText('strServerNode')" :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>

                        <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" v-if="!isLoggedInAsCustomer">{{ getLabelText('GN0000850') }}</th>
                                        <th style="width: 200px"><a href="#" @click.prevent="sortBy('PackageName')">{{ getLabelText('GN000141') }}</a></th>
                                        <th style="width: 150px" v-if="!isLoggedInAsCustomer && !isLoggedInAsReseller"><a href="#" @click.prevent="sortBy('ServerNode')">{{ getLabelText('DGN1110254') }}</a></th>
                                        <th style="width: 150px" v-if="owners.show"><a href="#" @click.prevent="sortBy('OwnerName')">{{ getLabelText('SPT002811') }}</a></th>
                                        <th style="width: 150px"><a href="#" @click.prevent="sortBy('VMName')">{{ getLabelText('SMI0240') }}</a></th>
                                        <th style="width: 150px"><a href="#" @click.prevent="sortBy('CPUCores')">{{ getLabelText('strProcessors') }}</a></th>
                                        <th style="width: 150px"><a href="#" @click.prevent="sortBy('RAM')">{{ getLabelText('HVServer11') }}</a></th>
                                        <th style="width: 150px" v-if="!hideColumnsDueToQuota"><a href="#" @click.prevent="sortBy('BandWidthAllowedPerMonth')">{{ getLabelText('strBandWidthAllowed') }}</a></th>
                                        <th style="width: 150px" v-if="!hideColumnsDueToQuota">{{ getLabelText('strBandwidthUsedCurrentMonth') }}</th>
                                        <th style="width: 150px" v-if="!hideColumnsDueToQuota">{{ getLabelText('strLastBandWidthUseddate') }}</th>
                                        <th style="width: 150px">{{ getLabelText('GN00001560') }}</th>
                                        <th style="width: 150px">{{ getLabelText('strLicenseKey') }}</th>
                                        <th style="width: 150px">{{ getLabelText('strNoofDisks') }}</th>
                                        <th style="width: 150px">{{ getLabelText('strTotalDisksSpace') }}</th>
                                        <th style="width: 150px">{{ getLabelText('strPublicNICCount') }}</th>
                                        <th style="width: 150px">{{ getLabelText('strPrivateNICCount') }}</th>
                                        <th style="width: 150px">{{ getLabelText('strTotalPublicIPs') }}</th>
                                        <th style="width: 150px">{{ getLabelText('strTotalPrivateIPs') }}</th>
                                        <th style="width: 100px">{{ getLabelText('Shielded') }}</th>
                                        <th style="width: 100px">{{ getLabelText('SDNEnabled') }}</th>
                                        <th style="width: 200px"><a href="#" @click.prevent="sortBy('DateCreated')">{{ getLabelText('GN00001496') }}</a></th>
                                    </tr>
                                    <tr v-for="record in records">
                                        <td v-if="!isLoggedInAsCustomer"><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?CID=' + record.CustomerId">{{ '#' + record.CustomerId + ' ' + record.CustomerName + (record.CompanyName == '' ? '' : ' [' + record.CompanyName + ']') }}</a></td>
                                        <td>{{ record.PackageName }}</td>
                                        <td v-if="!isLoggedInAsCustomer && !isLoggedInAsReseller">{{ record.ServerNode }}</td>
                                        <td v-if="owners.show && record.OwnerId == 0">{{ record.OwnerName }}</td>
                                        <td v-else-if="owners.show"><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?RD=1&CID='+record.OwnerId+'&Src=C'">{{ record.OwnerName }}</a></td>
                                        <td><a v-bind:href="'/RCC/VPS/VPSAccountDetail.aspx?OID=' + record.VPSId">{{ record.VMName }}</a></td>
                                        <td>{{ record.CPUCores }}</td>
                                        <td>{{ record.RAM }} </td>
                                        <td v-if="!hideColumnsDueToQuota">{{ record.BandWidthAllowedPerMonth }} </td>
                                        <td v-if="!hideColumnsDueToQuota">{{ record.CurrentMonthBandWidthUsage }} </td>
                                        <td v-if="!hideColumnsDueToQuota">{{ record.LastBandwidthUsedDateStr }} </td>
                                        <td>{{ record.SealedImageType }} </td>
                                        <td>{{ record.LicenseKey }} </td>
                                        <td>{{ record.NoofDisks }} </td>
                                        <td>{{ record.TotalDisksSpace }} </td>
                                        <td>{{ record.PublicNICCount }} </td>
                                        <td>{{ record.PrivateNICCount }} </td>
                                        <td>{{ record.PublicIPCount }} </td>
                                        <td>{{ record.PrivateIPCount }} </td>
                                        <td>{{ (record.Shielded == 1 ? getLabelText('GN000195') : getLabelText('GN0000860')) }} </td>
                                        <td>{{ (record.SDNEnabled == 0 ? getLabelText('strNo') : getLabelText('strYes')) }} </td>
                                        <td>{{ record.DateCreated }} </td>
                                    </tr>

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

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

                        <NoRecords v-else />

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