import VueSelect from '/Components/Common/VueSelect.js?v=3.4'
import InputSearch from '/Components/Common/InputSearch.js?v=3.4'
import InputTextArea from "/Components/Common/InputTextArea.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 ModalPopUp from '/Components/Common/ModalPopUp.js?v=3.4'
import Pager from '/Components/Common/Pager.js?v=3.4'
import DatePicker from '/Components/Common/DatePicker.js?v=3.4'
import NoRecords from '/Components/Common/NoRecords.js?v=3.4'
import Loading from "/Components/Common/Loading.js?v=3.4"
import { getLabelText, getSubscriptionURL, getStatusString, getShortDate } from '/Components/Common/utils.js?v=3.4'

export default {
    props: {
        readOnly: { type: Boolean, required: true },
        companyId: { type: String, required: true },
        customerId: { type: String, required: true },
        showConvertToPaid: { type: Boolean, required: true },
        showWHMCS: { type: Boolean, required: true },
        sortPreference: { type: Object, required: true }
    },
    components: {
        SearchPanel,
        OperationsPanel,
        ModalPopUp,
        VueSelect,
        InputSearch,
        InputTextArea,
        NoRecords,
        DatePicker,
        Pager,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            owners: {},
            statuses: accountStatusList,
            producttypes: {},
            search: {
                selectedOwner: '',
                subscriptionId: '',
                clientId: (this.customerId != '0' ? this.customerId : ''),
                customerName: '',
                domainName: '',
                soldPackageName: '',
                notes: '',
                companyName: '',
                selectedProductType: '-1',
                selectedStatus: '0',
                trial: '-1',
                strLabel: '',
                WHMCSId: '',
                showDeleted: false,

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'ID',
                sortDir: 'Asc',
                updateSorting: false
            },
            showClearButton: false,
            useTranslation: true,

            comments: '',
            cbSendInvoice: true,
            convertDate: '',

            //***** START: Modal Popup *******
            showModal: false,
            modalTitle: '',
            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();
        },
        getLabelText,
        getSubscriptionURL,
        getStatusString,
        getShortDate,
        handleGlobalSearch: function () {
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            var searchQueryType = '';
            var searchQueryValue = '';

            for (var i = 0; i < hashes.length; i++) {
                var hash = hashes[i].split('=');
                if (hash[0].toLowerCase() == 'op') {
                    searchQueryType = decodeURI(hash[1]);
                }
                else if (hash[0].toLowerCase() == 'status') {
                    searchQueryType = 'status';
                    searchQueryValue = decodeURI(hash[1]);
                }
                else if (hash[0].toLowerCase() == 'val') {
                    searchQueryValue = decodeURI(hash[1]);
                }
            }

            if (searchQueryType != '' && searchQueryValue != '') {
                if (searchQueryType == 'S1')
                    this.search.subscriptionId = searchQueryValue;
                else if (searchQueryType == 'S2')
                    this.search.soldPackageName = searchQueryValue;
                else if (searchQueryType == 'S3')
                    this.search.domainName = searchQueryValue;
                else if (searchQueryType == 'S4')
                    this.search.clientId = searchQueryValue;
                else if (searchQueryType == 'S5')
                    this.search.notes = searchQueryValue;
                else if (searchQueryType == 'status')
                    this.search.selectedStatus = searchQueryValue;
            }
        },
        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();
        },
        checkAll: function (checked) {
            //this.records.map(obj => obj.IsItemSelected = checked);

            this.records.map(record => {
                if (!(record.Status != 1 && record.Status != 3) && !(record.PackageTypeId == 8 || record.PackageTypeId == 10 || record.PackageTypeId == 24 || record.PackageTypeId == 25))
                    record.IsItemSelected = checked;
            });
        },
        showActionButton: function () {
            return this.records.find(obj => obj.IsItemSelected);
        },
        checkAllChecked: function () {
            return !this.records.find(obj => !obj.IsItemSelected);
        },
        productTypeChangeHandler: function (obj) {
            this.search.selectedProductType = obj.selectedValue;
        },
        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;

                });

        },
        listProductTypes: function () {

            var vm = this;

            let postRequest = { ...fetchPost };
            var params = {
                ShowActiveDirectoryType: true,
                ShowMiscProductType: true,
                ShowDedicatedHostingType: true,
                ShowSSLProductType: true,
                ShowDomainNameProductType: true,
                CompanyId: this.companyId,
                CustomerId: this.customerId
            };
            postRequest.body = JSON.stringify(params);

            fetch("/webservices/machpanelservice.asmx/GetProductTypes", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.producttypes = JSON.parse(data.d);

                    vm.search.selectedProductType = vm.producttypes.initialValue;
                });

        },
        listRecords: async function () {

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

            await fetch("/RCC/Clients/Subscriptions.aspx/GetSubscriptionsList", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.search.updateSorting = false;
                    vm.records = JSON.parse(data.d);
                    vm.isLoading = false;

                    if (vm.records.length > 0)
                        vm.totalRecords = vm.records[0].Counter;
                    vm.records.map(obj => ({ ...obj, IsItemSelected: false }));

                });

            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.search.customerName = '';
            this.search.domainName = '';
            this.search.soldPackageName = '';
            this.search.notes = '';
            this.search.companyName = '';
            this.search.selectedProductType = this.producttypes.initialValue;
            this.search.selectedStatus = this.statuses.initialValue;
            this.search.trial = '-1';
            this.search.strLabel = '';
            this.search.WHMCSId = '';
            this.search.showDeleted = false;

            this.search.pageIndex = 1;

            updateSelectInterface();    //Required to update SOL control in case of html select.
            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;

            vm.isLoading = true;

            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });;
        },
        dateSelectHandler: function (d) {
            this.convertDate = d.selectedDate;
        },
        exportToExcel: function () {
            var vm = this;

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

            fetch("/RCC/Clients/Subscriptions.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);
                });

        },
        suspendResumeSubscriptions: function (flag) {
            let selectedRecords = this.records.filter(a => a.IsItemSelected);

            if (selectedRecords == null || selectedRecords == undefined || selectedRecords.length <= 0) {
                alert(this.getLabelText('PlzSelectSubscription'));
            }
            else {

                var vm = this;

                let postRequest = { ...fetchPost };
                let params = {
                    data: {
                        //selectedItems: selectedRecords,
                        selectedItems: selectedRecords.map(it => ({
                            "Id": it.Id,
                            "PackageTypeId": it.PackageTypeId,
                            "Status": it.Status,
                            "DomainName": it.DomainName,
                            "PackageType": it.PackageType,
                            "CompanyId": it.CompanyId
                        })),
                    },
                    IsSuspend: flag
                };
                postRequest.body = JSON.stringify(params);

                fetch("/RCC/Clients/Subscriptions.aspx/SuspendResumeSubscriptions", postRequest)
                    .then(response => response.json()).then((data) => {

                        //if (data.d == true || data.d == 'true') {
                        this.doSearch();
                        displaySuccessMsg(data.d); //this.getLabelText('EGN0000011'));
                        //}

                    }).catch(function (e) {
                        displayErrorMsg(e);
                    });
            }
        },
        clearPopUpControls: function () {
            this.comments = '';
            this.convertDate = '';
            this.cbSendInvoice = true;
        },
        mpModelEventHandler: function (obj) {
            if (obj.submit == true) {
                if (obj.parentContext.op == "convert") {
                    this.convertToPaidSubscriptions(obj);
                }
            }

            this.clearPopUpControls();
            this.showModal = false;
        },
        confirmActionConvertToPaid: function (e) {

            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

            if (disabledValue === 'true' || disabledValue === true)
                return false;

            let selectedRecords = this.records.filter(a => a.IsItemSelected);
            //console.log(selectedRecords);
            //return;
            if (selectedRecords == null || selectedRecords == undefined || selectedRecords.length <= 0) {
                alert(this.getLabelText('PlzSelectSubscription'));
            }
            else {
                this.showModal = true;
                this.parentContext = { selectedRecords: selectedRecords, op: "convert" };
                this.modalTitle = this.getLabelText('StrConversionDate');
            }
        },
        convertToPaidSubscriptions: function (obj) {
            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                data: {
                    //selectedItems: obj.parentContext.selectedRecords
                    selectedItems: obj.parentContext.selectedRecords.map(it => ({
                        "Id": it.Id,
                        "PackageTypeId": it.PackageTypeId,
                        "Status": it.Status,
                        "DomainName": it.DomainName,
                        "PackageType": it.PackageType,
                        "CompanyId": it.CompanyId,
                        "CustomerId": it.CustomerId,
                        "Trial": it.Trial
                    })),
                },
                comments: vm.comments,
                convertDate: vm.convertDate,
                cbSendInvoice: vm.cbSendInvoice
            };
            postRequest.body = JSON.stringify(params);

            fetch("/RCC/Clients/Subscriptions.aspx/ConvertToPaidSubscriptions", postRequest)
                .then(response => response.json()).then((data) => {

                    //if (data.d == true || data.d == 'true') {
                    this.doSearch();
                    displaySuccessMsg(data.d); //this.getLabelText('EGN0000011'));
                    //}

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

        },
    },
    created: async function () {

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

        var vm = this;
        vm.isLoading = true;

        await this.listOwners().then(this.listStatuses).then(this.listProductTypes).then(this.handleGlobalSearch).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('M0005') }}</h3></div>
                <div class="body">
                    <div class="row">

                        <ModalPopUp v-if="showModal" :parentContext="parentContext" :modalTitle="modalTitle" @onYes="mpModelEventHandler" @onNo="mpModelEventHandler"
                            :yesButtonText="getLabelText('GN0000858')" :noButtonText="getLabelText('GN0000572')">
                            <div class="row">
                                <div class="col-md-3 col-sm-3 col-xs-12 row-label">
                                    <label>{{ '* ' + getLabelText('StrConversionDate') + ':' }}</label>
                                </div>
                                <DatePicker wrapperClass="col-md-3 col-sm-9 col-xs-12" @onDateSelected='dateSelectHandler' is-required='true'></DatePicker>
                            </div>
                            <div class="row">
                                <div class="col-sm-3 col-xs-12 row-label">
                                    <label>{{ '* ' + getLabelText('GN000148') + ':' }}</label>
                                </div>
                                <div class="col-sm-9 col-xs-12">
                                    <InputTextArea id="txtComments" v-model:fieldValue="comments" fieldRows="5" />
                                </div>
                            </div>
                            <div class="row"> 
                                <div class="col-sm-3 col-xs-12 row-label">
                                    <label>{{ getLabelText('GN000116') + ':' }}</label>
                                </div>
                                <div class="col-sm-9 col-xs-12">
                                    <div class="form-group">
                                        <input type="checkbox" v-model="cbSendInvoice" />
                                    </div>
                                </div>
                            </div>
                        </ModalPopUp>

                        <OperationsPanel>
                            <a v-show="!readOnly && showActionButton()" @click="suspendResumeSubscriptions(true)" class="btn btn-primary waves-effect btnAction">{{ getLabelText('DGN1110276') }}</a>
                            <a v-show="!readOnly && showActionButton()" @click="suspendResumeSubscriptions(false)" class="btn btn-primary waves-effect">{{ getLabelText('GN0001269') }}</a>
                            <a v-if="!readOnly && showConvertToPaid" @click="confirmActionConvertToPaid" class="btn btn-primary waves-effect btnAction" >{{ getLabelText('StrConvertToPaid') }}</a>
                            <a @click="exportToExcel" class="btn btn-primary waves-effect btnAction" >{{ getLabelText('strExport') }}</a>
                        </OperationsPanel>

                        <SearchPanel id='subscriptions-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.WHMCSId" fieldName="WHMCSId" fieldDataType="Number" v-if="showWHMCS" :fieldLabel="getLabelText('USM0159')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.clientId" fieldName="clientId" fieldDataType="Number" :fieldLabel="getLabelText('GN0000715')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.customerName" fieldName="customerName" :fieldLabel="getLabelText('GN0000268')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.domainName" fieldName="domainName" :fieldLabel="getLabelText('GN000125')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.soldPackageName" fieldName="soldPackageName" :fieldLabel="getLabelText('GN000141')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.notes" fieldName="notes" :fieldLabel="getLabelText('GN00001336')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.companyName" fieldName="companyName" :fieldLabel="getLabelText('GN00001077')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

                            <div :class="searchContainerDivClass" v-if="producttypes.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="producttypes.items" :selectedValue="search.selectedProductType" @selectchange="productTypeChangeHandler" />
                                </div>
                            </div>

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

                            <div :class="searchContainerDivClass">
                                <div class="form-group form-float">
                                    <select v-model="search.trial" class="vue-select">
                                        <option value="-1">{{getLabelText("SelectTrail")}}</option>
                                        <option value="1">{{getLabelText("GN00001544")}}</option>
                                        <option value="0">{{getLabelText("GN0000267")}}</option>
                                    </select>
                                </div>
                            </div>

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

                            <div :class="searchContainerDivClass">
                                <label for="showDeleted" class="checkbox-inline">
                                    <input type="checkbox" id="showDeleted" v-model="search.showDeleted"  />{{getLabelText('ShowDeleted')}}
                                </label>
                            </div>

                        </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" v-if="!readOnly">                                           
                                            <label for="CheckAll" class="checkbox-inline">
                                                <input type="checkbox" id="CheckAll" :checked="checkAllChecked()" @change="checkAll($event.target.checked);" />{{getLabelText('String385')}}
                                            </label>
                                        </th>
                                        <th class="col-xs-4">{{ getLabelText('DGN1119987') }}</th>
                                        <th class="col-xs-3"><a href="#" @click.prevent="sortBy('Name')">{{ getLabelText('GN0000850') }}</a></th>
                                        <th class="col-xs-1"><a href="#" @click.prevent="sortBy('Owner')">{{ getLabelText('Exh505') }}</a></th>
                                        <th class="col-xs-1">{{ getLabelText('GN00001489') }}</th>
                                        <th class="col-xs-2"><a href="#" @click.prevent="sortBy('StartDate')">{{ getLabelText('GN00001547') }}</a></th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td class="align-center" v-if="!readOnly">
                                            <label v-bind:for="'cb' + record.Id" class="checkbox-inline">
                                                <input type="checkbox" v-bind:id="'cb' + record.Id + '_' + record.PackageTypeId" v-model="record.IsItemSelected" :disabled="((record.Status != 1 && record.Status != 3) && (record.PackageTypeId == 8 || record.PackageTypeId == 10 || record.PackageTypeId == 24 || record.PackageTypeId == 25) ? true : null)" />{{getStatusString(record.Status)}}
                                            </label>
                                        </td>

                                        <td>
                                            <table class="table small">
                                                <tbody>
                                                    <tr>
                                                        <td class="col-xs-4 row-label">{{ getLabelText('GN0000678') }}: </td>
                                                        <td class="col-xs-8">
                                                            <a v-bind:href="getSubscriptionURL(record.PackageTypeId, record.Id, false)">{{ record.Id }}</a>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td class="col-xs-4 row-label">{{ getLabelText('GN000170') }}: </td>
                                                        <td class="col-xs-8">{{ record.DomainName + (record.Package != '' ? ' (' + record.Package + ')' : '') }}</td>
                                                    </tr>
                                                        <tr>
                                                            <td class="col-xs-4 row-label">{{ getLabelText('GN000140') }}: </td>
                                                            <td class="col-xs-8"> {{ getLabelText(record.PackageType) }}</td>
                                                        </tr>
                                                        <tr>
                                                            <td class="col-xs-4 row-label">{{ getLabelText('StrIsTrial') }}: </td>
                                                            <td class="col-xs-8">{{ (record.Trial ? getLabelText('Yes') : getLabelText('No'))}}</td>
                                                        </tr>
                                                        <tr>
                                                            <td class="col-xs-4 row-label">{{ getLabelText('GN000141') }}: </td>
                                                            <td class="col-xs-8" v-html="record.Package + (!showWHMCS || record.WHMCSHostingId == 0 ? '' : '<br />' + record.WHMCSHostingId)"></td>
                                                        </tr>
                                                        <tr>
                                                            <td class="col-xs-4 row-label">{{ getLabelText('GN00001489') }}: </td>
                                                            <td class="col-xs-8" v-if="record.AddonCount == 0">--</td>
                                                            <td class="col-xs-8" v-else v-html="record.Addons"></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><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?RD=1&CID='+record.CustomerId+'&Src=Sub'">{{ record.CustomerId + ' ' + record.Name + (record.CustCompanyName != '' ? ' [' + record.CustCompanyName + ']' : '') }} </a></td>

                                        <td v-if="record.OwnerId == 0">{{ record.Owner }}</td>
                                        <td v-else><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?RD=1&CID='+record.OwnerId+'&RD=1'">{{ record.Owner }}</a></td>

                                        <td v-if="record.AddonCount == 0">{{ record.AddonCount }} </td>
                                        <td v-else><a v-bind:href="getSubscriptionURL(record.PackageTypeId, record.Id, true)">{{ record.AddonCount }}</a></td>

                                        <td><DatePicker :id="record.Id.toString()" wrapperClass="col-xs-12 m-b-0" :defaultVal='record.StartDate' :is-Disabled='true' :displayAsLabel='true'></DatePicker>
                                            <div v-if="false" v-html="getShortDate(record.StartDate)" data-toggle="tooltip" data-placement="top" title="" :data-original-title="'Next Renewal: ' + record.NextRenewal" />
                                        </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>
`
}
