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 Pager from '/Components/Common/Pager.js?v=3.4'
import NoRecords from '/Components/Common/NoRecords.js?v=3.4'
import { getLabelText, getStatusString } 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 },
        customerId: { type: String, required: true },
        isLoggedInAsCustomer: { type: Boolean, required: true },
        allowtoAddVM: { type: Boolean, required: true },
        sortPreference: { type: Object, required: true }
    },
    components: {
        SearchPanel,
        VueSelect,
        InputSearch,
        NoRecords,
        Pager,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            owners: {},
            statuses: accountStatusList,
            search: {
                selectedOwner: '',
                subscriptionId: '',
                clientId: (this.customerId != '0' ? this.customerId : ''),
                customerName: '',
                vmName: '',
                clientCompanyName: '',
                selectedStatus: '',
                strLabel: '',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'VPSId',
                sortDir: 'Desc',
                updateSorting: false
            },
            showClearButton: false,
        }
    },
    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);

        },
        statusChangeHandler: function (obj) {
            this.search.selectedStatus = 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 = 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/VPS/VPSAccounts.aspx/GetVPSAccounts", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.search.updateSorting = false;
                    vm.records = JSON.parse(data.d);
                    if (vm.records.length > 0)
                        this.totalRecords = this.records[0].Counter;
                });
            vm.isLoading = false;
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {

            this.search.subscriptionId = '';
            this.search.clientId = (this.customerId != '0', this.customerId, '');
            this.search.customerName = '';
            this.search.vmName = '';
            this.search.clientCompanyName = '';
            this.search.selectedStatus = this.statuses.initialValue;
            this.search.strLabel = '';

            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);
            });
        },
        getAccountStatus: function (s, IsSingleVM, SubStatus) {
            let Status = parseInt(s);
            // alert(SubStatus);
            if (SubStatus == 1) {
                if (Status == 1)
                    return this.getLabelText('GN0000222');
                else if (Status == 3)
                    return this.getLabelText('GN00001545');
                else if (Status == 4)
                    return this.getLabelText('GN0000348');
                else if (Status == 7 || Status == 0) //pending cancel or pending delete
                    return this.getLabelText('SPT002056');
                else if (Status == 8)
                    return this.getLabelText('SPT002057');
                else if (Status == 9)
                    return this.getLabelText('SPT002058');
                else if (IsSingleVM && Status == 10)
                    return this.getLabelText('GN0000222');
                else if (Status == 10)
                    return this.getLabelText('SPT002059');
                else
                    return '';
            }
            else if (SubStatus == 3)
                return this.getLabelText('GN00001545');
            else if (SubStatus == 4)
                return this.getLabelText('GN0000348');
            else if (SubStatus == 7 || Status == 0) //pending cancel or pending delete
                return this.getLabelText('SPT002056');
            else if (SubStatus == 8)
                return this.getLabelText('SPT002057');
            else if (SubStatus == 9)
                return this.getLabelText('SPT002058');
            else
                return '';

        },
    },
    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">

                        <SearchPanel id='vpsaccounts-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.subscriptionId" fieldName="subscriptionId" fieldDataType="Number" :fieldLabel="getLabelText('SPT002807')" :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.clientCompanyName" fieldName="clientCompanyName" v-if="!isLoggedInAsCustomer" :fieldLabel="getLabelText('CustomerCompanyName')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.customerName" fieldName="customerName" v-if="!isLoggedInAsCustomer" :fieldLabel="getLabelText('GN0000268')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.vmName" fieldName="vmName" :fieldLabel="getLabelText('VPS002')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

                            <div :class="searchContainerDivClass" v-if="statuses.show">
                                <div class="form-group form-float">
                                    <VueSelect :useTranslation="true" :options="statuses.items" :selectedValue="this.search.selectedStatus" @selectchange="statusChangeHandler" />
                                </div>
                            </div>

                            <InputSearch :searchValue="search.strLabel" fieldName="strLabel" :fieldLabel="getLabelText('SubscriptionLabel')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

                        </SearchPanel>

                        <div class="col-xs-12" v-if="isLoading">
                            <Loading/>
                        </div>
                        <div class="col-xs-12" v-else>
                            <table class="table table-bordered table-striped table-hover" v-if="records.length > 0">
                                <tbody>
                                    <tr>
                                        <th class="col-xs-1 align-center">{{getLabelText('String385')}}</th>
                                        <th class="col-xs-3"><a href="#" @click.prevent="sortBy('VPSId')">{{ getLabelText('DGN1119987') }}</a></th>
                                        <th class="col-xs-2" v-if="!isLoggedInAsCustomer"><a href="#" @click.prevent="sortBy('CustomerId')">{{ getLabelText('GN0000850') }}</a></th>
                                        <th class="col-xs-3"><a href="#" @click.prevent="sortBy('VMName')">{{ getLabelText('M0902') }}</a></th>
                                        <th class="col-xs-1 hidden-xs" v-if="owners.show">{{ getLabelText('SPT002811') }}</th>
                                        <th class="col-xs-1 align-center">{{ getLabelText('GN0000360') }}</th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td class="align-center">{{ getAccountStatus(record.Status, record.IsSingleVM, record.SubStatus) }}</td>

                                        <td>
                                            <table class="table small">
                                                <tbody>
                                                    <tr>
                                                        <td class="col-xs-4 row-label">{{ getLabelText('SPT002807') }}: </td>
                                                        <td class="col-xs-8">
                                                            <a v-bind:href="'/RCC/Clients/VPS.aspx?SubID=' + record.VPSHostingId">{{ record.VPSHostingId }}</a>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td class="col-xs-4 row-label">{{ getLabelText('GN000141') }}: </td>
                                                        <td class="col-xs-8">{{ record.PackageName }}</td>
                                                    </tr>
                                                    <tr v-if="record.Label != ''">
                                                        <td class="col-xs-6 row-label">{{ getLabelText('SubscriptionLabel') }}: </td>
                                                        <td class="col-xs-6"> {{ record.Label }}</td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </td>

                                        <td v-if="!isLoggedInAsCustomer"><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?CID=' + record.CustomerId">{{ '#' + record.CustomerId + ' ' + record.Name + (record.CustCompanyName != '' ? ' [' + record.CustCompanyName + ']' : '') }} </a></td>

                                        <td>
                                            <table class="table small">
                                                <tbody>
                                                    <tr>
                                                        <td class="col-xs-4 row-label">{{ getLabelText('strName') }}: </td>
                                                        <td class="col-xs-8">
                                                            <a v-bind:href="'/RCC/Clients/VPS.aspx?SubID=' + record.VPSHostingId">{{ record.VMName }}</a>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td class="col-xs-4 row-label">{{ getLabelText('NetBIOS') }}: </td>
                                                        <td class="col-xs-8">{{ record.VMHostName }}</td>
                                                    </tr>
                                                    <tr>
                                                        <td class="col-xs-6 row-label">{{ getLabelText('DEV1130') }}: </td>
                                                        <td class="col-xs-6"> {{ (record.State == '--' ? record.State : record.State + ' [' + record.TimeUpdated + ']') }}</td>
                                                    </tr>
                                                    <tr>
                                                        <td class="col-xs-4 row-label">{{ getLabelText('strGeneration') }}: </td>
                                                        <td class="col-xs-8">{{ record.Generation }}</td>
                                                    </tr>
                                                    <tr v-if="owners.show">
                                                        <td class="col-xs-4 row-label">{{ getLabelText('strHost') }}: </td>
                                                        <td class="col-xs-8">{{ record.IP }}</td>
                                                    </tr>
                                                    <tr>
                                                        <td class="col-xs-4 row-label">{{ getLabelText('strOS') }}: </td>
                                                        <td class="col-xs-8">{{ record.OSStr }}</td>
                                                    </tr>
                                                    <tr>
                                                        <td class="col-xs-4 row-label">{{ getLabelText('strCPU') }}: </td>
                                                        <td class="col-xs-8">{{ record.CPUCores }}</td>
                                                    </tr>
                                                    <tr>
                                                        <td class="col-xs-4 row-label">{{ getLabelText('strRAM') }}: </td>
                                                        <td class="col-xs-8">{{ record.RAM  + ' MB'}}</td>
                                                    </tr>
                                                    <tr>
                                                        <td class="col-xs-4 row-label">{{ getLabelText('strPrimaryDisk') }}: </td>
                                                        <td class="col-xs-8">{{ record.TotalDiskSpace + ' GB' }}</td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </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" v-bind:class="[{'disabled':(record.Status != 1 && !(record.IsSingleVM && record.Status == 10) || record.ResellerPackage == 1)}, 'btn btn-primary waves-effect']">{{ getLabelText('L0086') }}</a>
                                            <a v-if="!readOnly" v-bind:href="'/RCC/Clients/VPS.aspx?SubID=' + record.VPSHostingId + '&TI=2&AddVPS=1'" v-bind:class="[{'disabled':(record.Status != 1 || !allowtoAddVM || record.IsSingleVM)}, 'btn btn-primary waves-effect btnAction']">{{ getLabelText('SMI0217') }}</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>
`
}
