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 Pager from "/Components/Common/Pager.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 NoRecords from "/Components/Common/NoRecords.js?v=3.4";
import { VueMultiSelectableSelected } from "/Components/Common/VueMultiSelectableSelected.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 },
        isLoggedInAsReseller: { type: Boolean, required: true },
        isSubReseller: { type: Boolean, required: true },
        sortPreference: { type: Object, required: true }
    },
    components: {
        VueSelect,
        InputSearch,
        Pager,
        SearchPanel,
        OperationsPanel,
        NoRecords,
        VueMultiSelectableSelected,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            orgs: {},
            settings: [],
            search: {
                selectedorg: '0',
                primaryDomainName: '',
                customerName: '',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: '',
                sortDir: '',
                updateSorting: false
            },
            globalSettings: {
                DLRequireAuth: false,
                DLRequireAuthUpdateEnabled: false,
                DLRequireAuthResellerUpdateEnabled: false,
                AllowLinkedMailbox: false,
                FirstNameLastNameRequired: false,
                HideExternalForwardingEmail: false,
                LoadTemplatesBasedOnAddons: false,
                AllowToUpdateSignature: true,
                AutoDisableEnableMailboxwithADUser: false
            },
            showClearButton: false,
            ucOrgs: [],
            selectedOrgs: [],
            isUpdateOrgSettingsMode: false,
            orgsEnableRequiredAuthDL: false,
            orgFirstLastNameRequired: false,
            orgAllowLinkedMailbox: false,
            orgsAllowAdminToChangeReqAuthDL: false,
            orgAllowToUpdaeSignature: true,
            autoDisableEnableMailboxwithADUser: false
        }
    },
    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.search.updateSorting = true;
            this.doSearch();
        },
        checkAll: function (checked) {
            this.settings.map(obj => obj.IsItemSelected = checked);
        },
        showActionButton: function () {
            return this.settings.find(obj => obj.IsItemSelected);
        },
        checkAllChecked: function () {
            return !this.settings.find(obj => !obj.IsItemSelected);
        },
        orgChangeHandler: async function (obj) {
            this.search.selectedorg = obj.selectedValue;
        },
        listSettings: async function () {

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

            await fetch("/RCC/Exchange/ExAccounts.aspx/FillOrgsSettings", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.search.updateSorting = false;
                    vm.settings = JSON.parse(data.d);
                    vm.settings.map(obj => ({ ...obj, IsItemSelected: false }));

                    if (vm.settings.length > 0) {
                        vm.totalRecords = vm.settings[0].TotalRecords;
                    }

                });
            vm.isLoading = false;
        },
        getLabelText,
        ListOrgs: async function () {

            var vm = this;

            await fetch("/RCC/Exchange/ExAccounts.aspx/GetOrgs?AllOrgs=1", fetchGet)
                .then(response => response.json()).then((data) => {
                    let result = JSON.parse(data.d);
                    vm.orgs = result;
                    vm.search.selectedorg = result.initialValue.toString();
                });
        },
        getGlobalOrgSettings: async function () {

            var vm = this;

            await fetch("/RCC/Exchange/ExAccounts.aspx/GetGlobalSettings", fetchGet)
                .then(response => response.json()).then((data) => {

                    let result = JSON.parse(data.d);
                    if (result.length > 0)
                        vm.globalSettings = result[0];
                });

        },
        SaveGlobalOrgSettings: function () {

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

                'enableRequiredAuthDL': vm.globalSettings.DLRequireAuth,
                'allowAdminToChangeReqAuthDL': vm.globalSettings.DLRequireAuthUpdateEnabled,
                'allowResellerToChangeReAuthDL': vm.globalSettings.DLRequireAuthResellerUpdateEnabled,
                'allowToAddLinkedMailbox': vm.globalSettings.AllowLinkedMailbox,
                'strFirstLastNameRequired': vm.globalSettings.FirstNameLastNameRequired,
                'strHideExternalForwardingEmailInput': vm.globalSettings.HideExternalForwardingEmail,
                'strLoadTemplatesBasedOnAddons': vm.globalSettings.LoadTemplatesBasedOnAddons,
                'allowToUpdateSignature': vm.globalSettings.AllowToUpdateSignature,
                'autoDisableEnableMailboxwithADUser': vm.globalSettings.AutoDisableEnableMailboxwithADUser
            };

            postRequest.body = JSON.stringify(param);


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

            fetch("/RCC/Exchange/ExAccounts.aspx/SaveGlobalOrgSettings", postRequest)
                .then(response => response.json()).then((data) => {
                    displaySuccessMsg(this.getLabelText('EGN0000011')); //

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

        },
        DeleteSelectedSettings: function () {
            let selectedRecords = this.settings.filter(a => a.IsItemSelected);

            if (selectedRecords == null || selectedRecords == undefined || selectedRecords.length <= 0) {
                alert(this.getLabelText('Please select settings to delete.'));
            }
            else {
                var vm = this;

                let postRequest = { ...fetchPost };

                let params = {
                    data: {
                        selectedItems: selectedRecords.map(it => ({ "recordId": it.RecordId, "orgId": it.OrganizationId })),
                    },
                }

                postRequest.body = JSON.stringify(params);

                fetch("/RCC/Exchange/ExAccounts.aspx/RemoveSelectedSettings", postRequest)
                    .then(response => response.json()).then((data) => {

                        vm.doSearch();
                        displaySuccessMsg(this.getLabelText('EGN0000011'));
                    });
            }
        },
        doClearSearch: async function () {

            this.search.selectedorg = this.orgs.initialValue;
            this.search.primaryDomainName = '';
            this.search.customerName = '';
            this.search.pageIndex = 1;
            this.search.pageSize = 20;
            this.search.sortExpression = 'OrganizationId';
            this.search.sortDir = 'Asc';

            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listSettings().catch(function (e) {
                vm.settings = [];
                if (vm.settings.length > 0)
                    vm.totalRecords = 0;
                vm.isLoading = true;
                displayErrorMsg(e);
            });

        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        resetOrgsSettings: function () {
            //this.ucOrgs = [];
            this.selectedOrgs = [];
            this.isUpdateOrgSettingsMode = false;
            this.orgsEnableRequiredAuthDL = false;
            this.orgFirstLastNameRequired = false;
            this.orgAllowLinkedMailbox = false;
            this.orgsAllowAdminToChangeReqAuthDL = false;
            this.orgAllowToUpdaeSignature = true;
            this.autoDisableEnableMailboxwithADUser = false;
        },
        updateOrgsSettings: async function () {
            this.resetOrgsSettings();
            this.isUpdateOrgSettingsMode = true;
            //await this.fillUCOrgs();
        },
        fillUCOrgs: async function () {
            var vm = this;

            await fetch("/RCC/Exchange/ExAccounts.aspx/FillOrganizations?allOrgs=1", fetchGet)
                .then(response => response.json()).then((data) => {

                    if (data.d != null) {
                        vm.ucOrgs = data.d;
                    }
                });
        },
        OrgsSelectionInfoHandler: function (selectableItems, selectedItems, id) {
            this.selectedOrgs = selectedItems.map(x => x.value);
            //console.log("Selectable: " + JSON.stringify(selectableItems));
            //console.log("Selected: " + JSON.stringify(selectedItems));
        },
        saveOrgsSettings: async function () {
            clearAllMsgs();
            if (this.selectedOrgs.length <= 0) {
                displayErrorMsg(Error(this.getLabelText('PleaseSelectOrgForGroupAction')));
                return false;
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'orgsEnableRequiredAuthDL': this.orgsEnableRequiredAuthDL,
                'orgFirstLastNameRequired': this.orgFirstLastNameRequired,
                'orgAllowLinkedMailbox': this.orgAllowLinkedMailbox,
                'orgsAllowAdminToChangeReqAuthDL': this.orgsAllowAdminToChangeReqAuthDL,
                'selectedOrgs': this.selectedOrgs,
                'orgAllowToUpdateSignature': this.orgAllowToUpdaeSignature,
                'autoDisableEnableMailboxwithADUser': this.autoDisableEnableMailboxwithADUser
            };
            postRequest.body = JSON.stringify(params);

            await fetch("/RCC/Exchange/ExAccounts.aspx/SaveOrgsSettings", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.resetOrgsSettings();
                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
    },
    created: async function () {
        this.search.sortDir = this.sortPreference.SortDirection;
        this.search.sortExpression = this.sortPreference.SortExpression;

        var vm = this;

        await this.ListOrgs().then(this.listSettings).then(this.getGlobalOrgSettings).then(this.fillUCOrgs).catch(function (e) {
            vm.settings = [];
            vm.ucOrgs = [];
            vm.totalRecords = 0;
            vm.isLoading = false;
            displayErrorMsg(e);
        });

    },
    template: '#exsettings-template'

}