
//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.4'
import VueSelect from "/Components/Common/VueSelect.js?v=3.4"
import InputSearch from "/Components/Common/InputSearch.js?v=3.4"
import InputText from "/Components/Common/InputText.js?v=3.4"
import Pager from "/Components/Common/Pager.js?v=3.4"
import SearchPanel from "/Components/Common/SearchPanelWrapper.js?v=3.4"
import ModalPopUp from '/Components/Common/ModalPopUp.js?v=3.4'
import NoRecords from "/Components/Common/NoRecords.js?v=3.4"
import OperationsPanel from '/Components/Common/OperationsPanelWrapper.js?v=3.4'
import Loading from "/Components/Common/Loading.js?v=3.4"

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: Number, required: true, default: '-1' },
        isResellerProd: { type: Boolean, required: true },
        isCommissionReseller: { type: Boolean, required: true },
        showWHMCSColumn: { type: Boolean, required: true },
        ML: { type: Number, required: true },
        addPageURL: { 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: {},
            partnerProfiles: {},
            countries: {},
            locales: {},
            voiceProviders: {},
            voiceCountries: {},
            totalRecords: 0,
            records: [],
            search: {
                selectedProductType: this.packageTypeId,
                resellerProduct: this.isResellerProd,
                selectedPartnerProfile: '',
                selectedCountry: '',
                selectedLocale: '',
                selectedVProvider: '',
                selectedVCountry: '0',
                productName: '',
                selectedStatus: '-1',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'PackageID',
                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 () {
            //this.ListAccounts();
            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;

        },
        listPartnerProfile: async function () {

            var vm = this;

            let postRequest = { ...fetchPost };
            var params = {
            }
            postRequest.body = JSON.stringify(params);

            await fetch("/RCC/Packages/ProductListingCopy.aspx/FillPartnerProfiles", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.partnerProfiles = JSON.parse(data.d);
                    if (vm.packageTypeId == '21')
                        vm.partnerProfiles.show = true;
                    else
                        vm.partnerProfiles.show = false;
                });
            vm.search.selectedPartnerProfile = vm.partnerProfiles.initialValue;

        },
        listCountries: async function () {

            var vm = this;

            let postRequest = { ...fetchPost };
            var params = {
                'selectedProfile': vm.search.selectedPartnerProfile
            }
            postRequest.body = JSON.stringify(params);

            await fetch("/RCC/Packages/ProductListingCopy.aspx/FillCountries", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.countries = JSON.parse(data.d);
                    //console.log(vm.countries);
                    if (vm.packageTypeId == '21')
                        vm.countries.show = true;
                    else
                        vm.countries.show = false;
                });
            vm.search.selectedCountry = vm.countries.initialValue;

        },
        listLocales: async function () {

            var vm = this;

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

            }
            postRequest.body = JSON.stringify(params);

            await fetch("/RCC/Packages/ProductListingCopy.aspx/FillLocale", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.locales = JSON.parse(data.d);
                    if (vm.packageTypeId == '21')
                        vm.locales.show = true;
                    else
                        vm.locales.show = false;
                });
            vm.search.selectedLocale = vm.locales.initialValue;

        },
        listVoiceProviders: async function () {

            var vm = this;
            //alert(vm.packageTypeId);
            let postRequest = { ...fetchPost };
            var params = {

            }
            postRequest.body = JSON.stringify(params);

            await fetch("/RCC/Packages/ProductListingCopy.aspx/FillVoiceProvider", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.voiceProviders = JSON.parse(data.d);
                    if (vm.packageTypeId == '24')
                        vm.voiceProviders.show = true;
                    else
                        vm.voiceProviders.show = false;
                });
            vm.search.selectedVProvider = vm.voiceProviders.initialValue;

        },
        listVoiceCountries: async function () {

            var vm = this;
            //alert(vm.packageTypeId);
            let postRequest = { ...fetchPost };
            var params = {

            }
            postRequest.body = JSON.stringify(params);

            await fetch("/RCC/Packages/ProductListingCopy.aspx/FillVoiceCountry", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.voiceCountries = JSON.parse(data.d);
                    if (vm.packageTypeId == '24')
                        vm.voiceCountries.show = true;
                    else
                        vm.voiceCountries.show = false;
                });
            vm.search.selectedVCountry = vm.voiceCountries.initialValue;

        },
        listRecords: async function () {

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

            await fetch("/RCC/Packages/ProductListingCopy.aspx/FillProducts", 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;

        },
        clonePackage: function (packageID, PackageName, packageTypeName, isActive) {

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

                'PackageID': packageID,
                'PackageName': PackageName,
                'PackageTypeName': packageTypeName,
                'IsActive': isActive
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Packages/ProductListingCopy.aspx/ClonePackage", 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 (packageID, PackageName, packageTypeName, isActive) {

            if (confirm(this.getLabelText('GN000200')))
                this.removePackage(packageID, PackageName, packageTypeName, isActive);
        },
        removePackage: function (packageID, PackageName, packageTypeName, isActive) {

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

                'PackageID': packageID,
                'PackageName': PackageName,
                'PackageTypeName': packageTypeName,
                'IsActive': isActive
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Packages/ProductListingCopy.aspx/RemovePackage", 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);
                });

        },
        editPackage: function (packageID) {
            if (this.isCommissionReseller) {
                window.location.replace("/RCC/Packages/EditDetailCommResellerPackage.aspx?Mode=1&PId=" + packageID + "&PType=" + this.packageTypeId, "");
            }
            else {
                var TI = 1;
                if (this.isResellerProd == true) {
                    TI = 0;
                }
                //alert(this.packageTypeId);
                if (this.packageTypeId == 16) {
                    //  alert(packageID);
                    //alert(vm.ML);
                    window.location.replace("/RCC/Packages/EditExPackage.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 19) {
                    window.location.replace("/RCC/Packages/VPS/EditPackage.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 17) {
                    window.location.replace("/RCC/Packages/EditSPPackage.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 18) {
                    window.location.replace("/RCC/Packages/EditOCSPackage.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 14) {
                    window.location.replace("/RCC/Packages/EditCRMPackage.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 2) {
                    window.location.replace("/RCC/Packages/EditNHPackage.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 3) {
                    window.location.replace("/RCC/Packages/ADPackage.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 8) {
                    window.location.replace("/RCC/Packages/EditSSLPlan.aspx?PROID=" + packageID + "&TI=" + TI + "&p=1&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 21) {
                    window.location.replace("/RCC/O365/CSPPlan.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 22) {
                    window.location.replace("/RCC/RDS/EditPackage.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 23) {
                    window.location.replace("/RCC/Packages/WorkfolderPackage.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 24) {
                    window.location.replace("/RCC/Voice/Plan.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }
                else if (this.packageTypeId == 25) {
                    window.location.replace("/RCC/HostedVoice/Plan.aspx?PROID=" + packageID + "&TI=" + TI + "&ML=" + this.ML, "");
                }

            }
        },
        packageDetail: function (packageID) {
            if (this.isCommissionReseller) {
                window.location.replace("/RCC/Packages/EditDetailCommResellerPackage.aspx?Mode=2&PId=" + packageID + "&PType=" + this.packageTypeId, "_blank");
            }
            else {
            }
        },
        activateDeActivatePackage: function (packageID, isActive) {
            alert(isActive);
            let postRequest = { ...fetchPost };
            var param = {

                'PackageID': packageID,
                'IsActive': isActive
            };

            postRequest.body = JSON.stringify(param);

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

                    }

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

        },
        addPackage: function () {
            var vm = this;
            var resellerPro = "TI=1";

            if (vm.isResellerProd == true) {

                resellerPro = "IR=1&TI=0";
            }

            window.open("/RCC/Packages/" + vm.addPageURL + "?" + resellerPro + "&ML=" + vm.ML, "_blank");

        },
        UpdateIndex: function (isAddon, isTld) {

            let postRequest = { ...fetchPost };
            var param = {
                'PackageOrderIDs': this.records.map(item => item.PackageId + '|' + 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.selectedProductType = this.packageTypeId;
            this.search.selectedStatus = '-1';
            this.search.productName = '';
            this.search.pageIndex = 1;
           
            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;
        if (vm.packageTypeId == '21') {
            await this.listPartnerProfile().then(this.listCountries).then(this.listLocales).catch(function (e) {

                displayErrorMsg(e);
            });
        }
        if (vm.packageTypeId == '24') {
            await this.listVoiceProviders().then(this.listVoiceCountries()).catch(function (e) {
                displayErrorMsg(e);
            });
        }
        await this.listProductTypes().then(this.listRecords).catch(function (e) {
            vm.records = [];
            vm.totalRecords = 0;
            vm.isLoading = false;
            displayErrorMsg(e);
        });
        updateSelectInterface();

    },
    template: ` 
        <div class="col-xs-12">
            <div class="card">
                <div class="body">
                    <div class="row">

                        <OperationsPanel>
                            <a @click="addPackage();" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN00001462') }}</a>
                            <a @click="UpdateIndex(false,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.productName" fieldName="productName"  :fieldLabel="getLabelText('GN0000103')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" /> 
                                           
                            <div :class="searchContainerDivClass">
                                <div class="form-group form-float">
                                    <VueSelect :options="producttypes.items" :selectedValue="this.search.selectedProductType" :disabled=!producttypes.show @selectchange="productTypeChangeHandler" />
                                </div>
                            </div>
 

                            <div :class="searchContainerDivClass">
                                <div class="form-group form-float">
                                    <select v-model="search.selectedStatus" class="vue-select">
                                        <option value="-1">{{ getLabelText('SelectStatus') }}</option>
                                        <option value="1">{{ getLabelText('GN0000935') }}</option>
                                        <option value="0">{{ getLabelText('GN0000936') }}</option>
                                    </select>
                                </div>
                            </div>

                       


                            <div :class="searchContainerDivClass" v-if="packageTypeId == 21 && partnerProfiles.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="partnerProfiles.items" :selectedValue="this.search.selectedPartnerProfile" @selectchange="" />
                                </div>
                            </div>

                            <div :class="searchContainerDivClass" v-if="packageTypeId == 21 && countries.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="countries.items" :selectedValue="this.search.selectedCountry" @selectchange="" />
                                </div>
                            </div>
                            <div :class="searchContainerDivClass" v-if="packageTypeId == 21 && locales.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="locales.items" :selectedValue="this.search.selectedLocale" @selectchange="" />
                                </div>
                            </div>             

                             <div :class="searchContainerDivClass" v-if="packageTypeId == 24 && voiceProviders.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="voiceProviders.items" :selectedValue="this.search.selectedVProvider" @selectchange="" />
                                </div>
                            </div>             

                            <div :class="searchContainerDivClass" v-if="packageTypeId == 24 && voiceCountries.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="voiceCountries.items" :selectedValue="this.search.selectedVCountry" @selectchange="" />
                                </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("String385")}}</th>
                                        <th class="col-xs-1" >{{getLabelText("GN0000941")}}</th>
                                        <th class="col-xs-1"><a href="#" @click.prevent="sortBy('PackageID')">{{getLabelText("GN0000678")}}</a></th>
                                        <th class="col-xs-1" v-if="showWHMCSColumn">{{getLabelText("USM0159")}}</th>
                                        <th class="col-xs-3"><a href="#" @click.prevent="sortBy('PackageName')">{{getLabelText("GN0000937")}}</a></th>                                         
                                        <th class="col-xs-1">{{getLabelText("String330")}}</th>                                        
                                        <th class="col-xs-2">{{getLabelText("GN00001496")}}</th>
                                        <th class="col-xs-1 "><a href="#" @click.prevent="sortBy('PackageTypeName')">{{getLabelText("PT0030002")}}</a></th>
                                        <th class="col-xs-1 align-center" v-if="!readOnly">{{getLabelText("GN0000360")}}</th>
                                    </tr>
                                    <tr v-for="record in records">                                      
                                      
                                        <td v-if="record.IsActive">{{getLabelText("GN000195")}}</td>    
                                        <td v-else>{{getLabelText("GN0000860")}}</td>    
                                        <td>  
                                            <InputText v-model:fieldValue="record.DisplayIndex"/>
                                        </td>
                                        <td>{{record.PackageId}}</td>
                                        <td v-if="showWHMCSColumn">{{record.WHMCS_ProdId}}</td>
                                         <td>{{record.PackageName}}</td>
                                        <td>{{record.TotalSold}}</td>
                                        <td>{{record.DateCreated}}</td>
                                        <td>{{record.PackageTypeName}}</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-if="!isCommissionReseller"  v-on:click.prevent="clonePackage(record.PackageId,record.PackageName,record.PackageTypeName,record.IsActive)">{{getLabelText("DGN1110198")}}</a>
                                            </li>
                                            <li>
                                                <a v-bind:class="'btnAction waves-effect waves-block'"  @click.prevent="editPackage(record.PackageId)">{{getLabelText("GN0000276")}}</a>
                                            </li> 
                                             <li>
                                                <a v-bind:class="'btnAction waves-effect waves-block'" v-if="isCommissionReseller"  @click.prevent="packageDetail(record.PackageId)">{{getLabelText("GN0000843")}}</a>
                                            </li> 
                                            <li>
                                              <a v-if="record.IsActive && !isCommissionReseller" v-bind:class="'btnAction waves-effect waves-block'"  @click.prevent="activateDeActivatePackage(record.PackageId,record.IsActive)">{{getLabelText("String542")}}</a>
                                              <a v-else-if="!record.IsActive && !isCommissionReseller" v-bind:class="'btnAction waves-effect waves-block'"  @click.prevent="activateDeActivatePackage(record.PackageId,record.IsActive)">{{getLabelText("GN0000807")}}</a>
                                            </li>
                                            
                                              <li>                                           
                                                    <a v-if="packageTypeId == 21" v-bind:class="'btnAction waves-effect waves-block'"  @click.prevent="">{{getLabelText("ShowOffers")}}</a>
                                               </li>
                                               <li>                                        
                                                    <a v-if="packageTypeId == 21" class="btn btn-primary"  @click.prevent="">{{getLabelText("Str3rdPartyProds")}}</a>
                                               </li>
                                              <li>                                       
                                                   <a v-bind:class="'btnAction waves-effect waves-block'" v-if="!isCommissionReseller"   v-on:click.prevent="confirmRemove(record.PackageId,record.PackageName,record.PackageTypeName,record.IsActive);">{{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>
`

}