
//TODO: Paging on page level is remaining, ned to discuss as it is not handled in SP.

import { getLabelText } from '/components/common/utils.js?v=3.6'
import VueSelect from "/Components/Common/VueSelect.js?v=3.6"
import InputSearch from "/Components/Common/InputSearch.js?v=3.6"
import InputText from "/Components/Common/InputText.js?v=3.6"
import Pager from "/Components/Common/Pager.js?v=3.6"
import SearchPanel from "/Components/Common/SearchPanelWrapper.js?v=3.6"
import ModalPopUp from '/Components/Common/ModalPopUp.js?v=3.6'
import NoRecords from "/Components/Common/NoRecords.js?v=3.6"
import OperationsPanel from '/Components/Common/OperationsPanelWrapper.js?v=3.6'
import Loading from "/Components/Common/Loading.js?v=3.6"

export default {

    props: {
        //tabIndex: { type: String, required: true },
        readOnly: { type: Boolean, required: true },
        companyId: { type: String, required: true },
        customerId: { type: String, required: true },        
        sortPreference: { type: Object, required: true },
        packageTypeId: { type: String, required: true, default: '-1' },
        isResellerProd: { type: Boolean, required: true },
        showWHMCSColumn: { type: Boolean, required: true },
        packageTypeId: { type: String, required: true },
        addonParam: { type: String, required: true },

    },
    components: {
        OperationsPanel,
        VueSelect,
        InputSearch,
        InputText,
        Pager,
        getLabelText,
        SearchPanel,
        ModalPopUp,
        NoRecords,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            producttypes: {},
            totalRecords: 0,
            records: [],
            search: {
                selectedAddonType: this.packageTypeId,
                addonName: '',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'AddonTypeId',
                sortDir: 'Desc',
                updateSorting: false
            },
            showClearButton: false,
            useTranslation: true,


        }
    },
    methods: {
        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

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

        productTypeChangeHandler: function (obj) {
            this.search.selectedProductType = obj.selectedValue;

        },


        doSearch: function () {
            
            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        listProductTypes: async 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);

            await fetch("/webservices/machpanelservice.asmx/GetProductTypes", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.producttypes = JSON.parse(data.d);
                    if (vm.packageTypeId == '-1')
                        vm.producttypes.show = true;
                    else
                        vm.producttypes.show = false;
                });
            vm.producttypes.selectedProductType = vm.producttypes.initialValue; //vm.search.selectedProductType;

        },

        listRecords: async function () {

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

            await fetch("/RCC/Packages/ProductListingCopy.aspx/FillAddons", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.records = JSON.parse(data.d);
                    this.updateSorting = false;
                    
                    if (vm.records.length > 0)
                        vm.totalRecords = vm.records[0].TotalRecords;

                });
            vm.isLoading = false;

        },

        cloneAddon: function (addOnTypeId, addOnGroupName) {
            
            let postRequest = { ...fetchPost };
            var param = {

                'AddOnTypeId': addOnTypeId,
                'AddOnGroupName': addOnGroupName
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Packages/ProductListingCopy.aspx/CloneAddon", postRequest)
                .then(response => response.json()).then((data) => {
                    
                    if (data.d == true || data.d == 'true') {
                        this.doSearch();
                        displaySuccessMsg(this.getLabelText('EGN0000011')); //

                    }

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

        },
        confirmRemove: function (addOnTypeId, addOnGroupName) {

            if (confirm(this.getLabelText('GN000200')))
                this.removePackage(addOnTypeId, addOnGroupName);
        },
        removePackage: function (addOnTypeId, addOnGroupName) {

            let postRequest = { ...fetchPost };
            var param = {

                'AddOnTypeId': addOnTypeId,
                'AddOnGroupName': addOnGroupName
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Packages/ProductListingCopy.aspx/RemoveAddon", postRequest)
                .then(response => response.json()).then((data) => {
                    
                    if (data.d == true || data.d == 'true') {
                        this.doSearch();
                        displaySuccessMsg(this.getLabelText('EGN0000011')); //

                    }

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

        },

        addNewAddon: function () {
            var vm = this;

            window.open("/RCC/Packages/AddOn.aspx?" + vm.addonParam + "&ML=" + vm.ML, "_blank");

        },
        addBillingOnlyAddon: function () {
            var vm = this;
            var param = "";
            if (vm.packageTypeId > 0) {
                param = "?PType=" + vm.packageTypeId + "&ML";
            }
            else {
                param = "?ML" + vm.ML;
            }
            window.open("/RCC/Packages/AddBillingOnlyAddon.aspx" + param, "_blank");

        },
        UpdateIndex: function (isAddon, isTld) {
            

            let postRequest = { ...fetchPost };
            var param = {
                'PackageOrderIDs': this.records.map(item => item.AddOnTypeId + '|' + item.DisplayIndex).join(),
                'IsAddOn': isAddon,
                'IsTLD': isTld
            };

            postRequest.body = JSON.stringify(param);
           
            fetch("/RCC/Packages/ProductListingCopy.aspx/UpdateIndex", postRequest)
                .then(response => response.json()).then((data) => {
                    displaySuccessMsg(data.d);
                    if (data.d == 'true') {
                        this.doSearch();
                        displaySuccessMsg(this.getLabelText('EGN0000011'));
                    }

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

        },
        getLabelText,
        doClearSearch: async function () {

            // this.search.selectedOwner = this.owners.initialValue;

            //if (this.statuses.show) {
            //    await this.ListStatus();

            //}
            // Set them with initial value
            //this.search.selectedActionType = -1;
            //vm.producttypes.selectedProductType = vm.search.selectedProductType;

            this.search.selectedProductType = this.packageTypeId;
            this.search.selectedStatus = '-1';
            this.search.addonName = '';
            this.search.pageIndex = 1;
            //this.search.pageSize = 20;
            //this.search.sortExpression = 'TimeStampEntered';
            //this.search.sortDir = 'Desc';          
            clearAllMsgs();
            this.doSearch();
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        }


    },
    created: async function () {

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

        var vm = this;

        await this.listProductTypes().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>
                            <a v-if="packageTypeId != 25 && packageTypeId != 24 && packageTypeId != 21" @click="addNewAddon();" class="btn btn-primary waves-effect btnAction">{{ getLabelText('SMI706') }}</a>
                            <a @click="addBillingOnlyAddon();" class="btn btn-primary waves-effect btnAction">{{ getLabelText('SMI707') }}</a>
                            <a @click="UpdateIndex(true,false);" class="btn btn-primary waves-effect btnAction">{{ getLabelText('FAM0019') }}</a>                          
                        </OperationsPanel>

                        <SearchPanel id='products-list' :showClearButton="showClearButton" @onSearch='doSearch' @onClear='doClearSearch'>
                             
                                           
                            <InputSearch :searchValue="search.addonName" fieldName="addonName"  :fieldLabel="getLabelText('String141')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" /> 
                                           
                            <div :class="searchContainerDivClass" v-if="producttypes.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="producttypes.items" :selectedValue="this.search.selectedProductType" @selectchange="productTypeChangeHandler" />
                                </div>
                            </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">{{getLabelText("GN0000941")}}</th>
                                        <th class="col-xs-1" >{{getLabelText("GN0000678")}}</th>
                                        <th class="col-xs-1" v-if="showWHMCSColumn">{{getLabelText("USM0159")}}</th>
                                        <th class="col-xs-2">{{getLabelText("GN000140")}}</th>                                        
                                        <th class="col-xs-3">{{getLabelText("String141")}}</th>                                         
                                        <th class="col-xs-1">{{getLabelText("String330")}}</th>                                        
                                        <th class="col-xs-1">{{getLabelText("SMI300")}}</a></th>                                        
                                        <th class="col-xs-1 align-center" v-if="!readOnly">{{getLabelText("GN0000360")}}</th>
                                    </tr>
                                    <tr v-for="record in records">                                      
                                      
                                       
                                        <td>  
                                            <InputText v-model:fieldValue="record.DisplayIndex"/>
                                        </td>
                                        <td>{{record.AddOnTypeId}}</td>
                                        <td v-if="showWHMCSColumn">{{record.WHMCS_ProdId}}</td>
                                         <td>{{getLabelText(record.Trans_Id)}}</td>
                                        <td>{{record.AddOnGroupName}}</td>
                                        <td>{{record.AddOnUsedCount}}</td>
                                        <td v-if="record.PlanAddon">{{getLabelText("GN0000004")}}</td>    
                                        <td v-else>{{getLabelText("GN0000005")}}</td>  
                                        <td class="align-center" v-if="!readOnly">
                                        <ul class="option-menu Div_OpsRow">
                                        <li class="dropdown">
                                            <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                                                <i class="material-icons">menu</i>
                                            </a>
                                                <ul class="dropdown-menu pull-right" id="UL_OptionMenu">
                                             <li>                                               
                                                <a v-bind:class="'btnAction waves-effect waves-block'"  v-on:click.prevent="cloneAddon(record.AddOnTypeId,record.addOnGroupName)">{{getLabelText("DGN1110198")}}</a>
                                            </li>
                                            <li>
                                                <a v-bind:class="'btnAction waves-effect waves-block'"  @click.prevent="">{{getLabelText("GN0000276")}}</a>
                                            </li> 
                                             <li>
                                                <a v-bind:class="'btnAction waves-effect waves-block'"  @click.prevent="">{{getLabelText("GN0000843")}}</a>
                                            </li> 
                                                                                           
                                              <li>                                       
                                                   <a v-bind:class="'btnAction waves-effect waves-block'"   v-on:click.prevent="confirmRemove(record.AddOnTypeId,record.addOnGroupName);">{{getLabelText("GN0000278")}}</a>
                                              </li>
                                           
                                            </ul>    
                                                </li>
                                            </ul>
                                    </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>
`

}