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 SearchPanel from "/Components/Common/SearchPanelWrapper.js?v=3.6"
import NoRecords from '/Components/Common/NoRecords.js?v=3.6'
import { getLabelText } from '/Components/Common/utils.js?v=3.6'
import Loading from "/Components/Common/Loading.js?v=3.6"

export default {
    components: {
        getLabelText,
        NoRecords,
        VueSelect,
        InputSearch,
        InputText,
        SearchPanel,
        Loading
    },
    props: {
        //tabIndex: { type: String, required: true },
        readOnly: { type: Boolean, required: true },
        customerIdFromOwner: { type: Number, required: true, default: 0 },
        companyIdOfOwner: { type: Number, required: true, default: 1 },
        resellerSubscription: { type: Boolean, required: true }
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            records: [],
            categories: [],
            languages: {},

            totalRecords: 0,
            search: {
                categoryName: '',
                subscriptionName: '',
                selectedLanguage: '-1',
                rs: this.resellerSubscription,
                cId: this.customerIdFromOwner,
            },
            showClearButton: false,
            globalRecipientEmailsCSV: ''
        }
    },
    methods: {
        getLabelText,
        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.doSearch();
        },
        listLanguages: async function () {

            var vm = this;
            vm.isLoading = true;
            let cId = this.resellerSubscription ? 1 : this.companyIdOfOwner;

            await fetch("/RCC/Clients/NotificationSubscriptions.aspx/FillLanguages?CompanyId=" + cId + "&customerId=" + this.customerIdFromOwner, fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.languages = JSON.parse(data.d);
                    vm.search.selectedLanguage = vm.languages.initialValue;
                    
                });
            vm.isLoading = false;
        },
        languageChangeHandler: function (obj) {
            this.search.selectedLanguage = obj.selectedValue;
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            vm.isLoading = true;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.categories = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        doClearSearch: async function () {

            this.search.selectedLanguage = this.languages.initialValue;
            this.search.categoryName = '';
            this.search.subscriptionName = '';

            updateSelectInterface();    //Required to update SOL control in case of html select.
            clearAllMsgs();
            this.doSearch();

        },
        listRecords: async function () {

            var vm = this;

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

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

                    vm.records = JSON.parse(data.d);
                    vm.records = vm.records.map(obj => ({ ...obj, IsItemSelected: (!obj.SubscribersOnly || obj.RecipientEmailsCSV != '') }));

                    vm.categories = vm.records.filter((obj, index, self) =>
                        index === self.findIndex((t) => t.CategoryName === obj.CategoryName)
                    );

                    if (vm.records.length > 0)
                        vm.totalRecords = vm.records.length;
                });

        },
        checkAll: function (checked) {
            //this.records.map(obj => obj.IsItemSelected = checked);

            this.records.map(record => { if (record.SubscribersOnly) { record.IsItemSelected = checked; } });
        },
        showActionButton: function () {
            return this.records.find(obj => obj.IsItemSelected);
        },
        checkAllChecked: function () {
            return !this.records.find(obj => !obj.IsItemSelected);
        },
        saveSubscribed: async function (isGlobal) {
            clearAllMsgs();

            let selectedRecords = this.records; //.filter(a => a.IsItemSelected);

            if (isGlobal && this.globalRecipientEmailsCSV.trim() == '') {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                return false;
            }

            //if (isGlobal && !ValidateCommaSeparatedEmails(this.globalRecipientEmailsCSV.trim())) {
            //    displayErrorMsg(Error(this.getLabelText('SMI00940')));
            //    return false;
            //}

            let selectedEmptyEmailAddRcds = this.records.filter(a => a.IsItemSelected && a.RecipientEmailsCSV.trim() == '');
            
            if (selectedEmptyEmailAddRcds != null && selectedEmptyEmailAddRcds != undefined && selectedEmptyEmailAddRcds.length > 0) {
                displayErrorMsg(Error(this.getLabelText('strEmailisRequiredForAllCheckedSubs')));
                return false;
            }

            //let selectedInvalidEmailAddRcds = this.records.filter(a => a.IsItemSelected && !ValidateCommaSeparatedEmails(a.RecipientEmailsCSV.trim()));
             
            //if (selectedInvalidEmailAddRcds != null && selectedInvalidEmailAddRcds != undefined && selectedInvalidEmailAddRcds.length > 0) {
            //    displayErrorMsg(Error(this.getLabelText('SMI00940')));
            //    return false;
            //}
            
            if (selectedRecords == null || selectedRecords == undefined || selectedRecords.length <= 0) {
                alert(this.getLabelText('PlzSelectSubscription'));
                return false;
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                data: {
                    //selectedItems: selectedRecords,
                    selectedItems: selectedRecords.map(it => ({
                        "SubscriptionId": it.SubscriptionId,
                        "SubscriptionName": it.SubscriptionName,
                        "RecipientEmailsCSV": it.RecipientEmailsCSV.trim(),
                        "SubscribersOnly": it.SubscribersOnly,
                        "CompanyId": it.CompanyId,
                        "IsItemSelected": it.IsItemSelected
                    })),
                },
                'globalRecipientEmailsCSV': this.globalRecipientEmailsCSV.trim(),
                'resellerSubscription': this.resellerSubscription,
            };
            postRequest.body = JSON.stringify(params);

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

                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
    },
    created: async function () {
        var vm = this;
        vm.isLoading = true;
        await this.listLanguages().then(this.listRecords).catch(function (e) {
            vm.records = [];
            vm.categories = [];
            vm.totalRecords = 0;
            vm.isLoading = false;
            displayErrorMsg(e);
        });

        //setTimeout(function () { AdminBSBThemeChanges(); }, 5000);
    },
    template: `

        <div class="col-xs-12">
            <div class="card">
                <div class="header"><h3>{{ getLabelText('NotificationSubscriptions') }}</h3></div>

                <div class="body">
                    <div class="row">

                        <SearchPanel id='subs-list' :showClearButton="showClearButton" @onSearch='doSearch' @onClear='doClearSearch'>

                            <InputSearch :searchValue="search.categoryName" fieldName="categoryName" :fieldLabel="getLabelText('GN0001286')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.subscriptionName" fieldName="subscriptionName" :fieldLabel="getLabelText('strSubscription')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

                            <div :class="searchContainerDivClass" v-if="languages.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="languages.items" :selectedValue="this.search.selectedLanguage" @selectchange="languageChangeHandler" />
                                </div>
                            </div>

                        </SearchPanel>

                        <div class="col-xs-12" v-if="isLoading">
                            <Loading/>
                        </div>
                    <div class="col-xs-12" v-else>
                        <div v-if="categories.length > 0">

                            <div class="col-xs-12" v-if="!readOnly && customerIdFromOwner <= 0">
                                <div class="card">
                                    <div class="header"><h3>{{ getLabelText('UpdateAlternateEmailAll') }}</h3>
                                    </div>
                                    <div class="body">
                                        <div class="row">
				                            <div class="col-xs-12 col-sm-3" v-html="'* ' + getLabelText('AlternateEmailAddresses') + ': '"></div>
				                            <div class="col-xs-12 col-sm-5">
                                                <InputText v-model:fieldValue="globalRecipientEmailsCSV" />
                                            </div>
				                            <div class="col-xs-12 col-sm-4">
                                                <a @click.prevent="saveSubscribed(true)" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000281')}} </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

				            <div class="col-xs-12" v-html="'<strong>Note: </strong>' + getLabelText('FAM00254')" v-if="!readOnly && customerIdFromOwner <= 0"></div>

                            <div class="col-xs-12" v-if="!readOnly && customerIdFromOwner <= 0">
                                <label for="CheckAll" class="checkbox-inline">
                                    <input type="checkbox" id="CheckAll" :checked="checkAllChecked()" @change="checkAll($event.target.checked);" />{{ getLabelText('GN0000180') }}
                                </label>
                            </div>

                            <div class="panel-group" id="accordion_1" role="tablist" aria-multiselectable="true">
                                <div class="col-xs-12">
                                    <div :id="'AccordionPane1' + record.CategoryId" class="panel panel-primary" v-for="record in categories">
	                                    <div :id="'PanelHeading' + record.CategoryId" class="panel panel-heading collapsed" role="tab">
		                                    <h2 class="panel-title">
			                                    <a :href="'#collapseOne' + record.CategoryId" :id="'A_Head' + record.CategoryId" role="button" data-toggle="collapse"
 				                                    data-parent="#accordion_1" aria-expanded="false" :aria-controls="'collapseOne' + record.CategoryId"
 				                                    class="" data-show-progress="no">
				                                    {{ record.CategoryName }}
                                                    <!-- <label :for="'CheckAll-' + record.CategoryId" class="checkbox-inline">
                                                        <input type="checkbox" :id="'CheckAll-' + record.CategoryId" :checked="checkAllChecked()" @change="checkAll($event.target.checked);" />{{ record.CategoryName }}
                                                    </label> -->

			                                    </a>
		                                    </h2>
	                                    </div>
	                                    <div :id="'collapseOne' + record.CategoryId" class="panel-collapse collapse in" role="tabpanel" :aria-labelledby="'PanelHeading' + record.CategoryId">
		                                    <div class="panel-body">
			                                    <div class="row" v-for="sub in records.filter(x => x.CategoryId == record.CategoryId)">
				                                    <div class="col-xs-12">
                                                        <label v-bind:for="'cb' + sub.SubscriptionId" class="checkbox-inline">
                                                            <input type="checkbox" v-bind:id="'cb' + sub.SubscriptionId" v-model="sub.IsItemSelected" :disabled="(!sub.SubscribersOnly || customerIdFromOwner > 0 ? true : false)" />{{ sub.SubscriptionName }}
                                                        </label>

                                                    </div>

				                                    <div class="col-xs-12 col-sm-3" v-html="'* ' + getLabelText('AlternateEmailAddresses') + ': '"></div>
				                                    <div class="col-xs-12 col-sm-7">
                                                        <InputText v-model:fieldValue="sub.RecipientEmailsCSV" :disabled="(customerIdFromOwner > 0 ? true : false)"/>
                                                    </div>
				                                    <div class="col-xs-12 col-sm-2"> {{ getLabelText('GN00003000') + ': ' + sub.LanguageName }}</div>

				                                    <div class="col-xs-12"><hr/></div>
			                                    </div>
		                                    </div>
	                                    </div>
                                    </div>
                                </div>
                            </div>

				            <div class="col-xs-12" v-html="'<strong>Note: </strong>' + getLabelText('FAM00254')" v-if="!readOnly && customerIdFromOwner <= 0"></div>

				            <div class="col-xs-12" v-if="!readOnly && customerIdFromOwner <= 0">
                                <a @click.prevent="saveSubscribed(false)" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000654')}} </a>
                            </div>

                        </div>
                        <div class="col-xs-12" v-else>
                            <NoRecords />
                        </div>

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