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 { VueMultiSelectableSelected } from "/Components/Common/VueMultiSelectableSelected.js?v=3.4"
import DatePicker from '/Components/Common/DatePicker.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 },
        currentDate: { type: String, required: true },
        isSubReseller: { type: Boolean, required: true },
        companyId: { type: String, required: true },
        customerId: { type: String, required: true },
        isLoggedInAsCustomer: { type: Boolean, required: true },
        isLoggedInAsReseller: { type: Boolean, required: true },
        sortPreference: { type: Object, required: true },
        syncFromBackendAllowed: { type: Boolean, required: true },
        exchLitigationHold: { type: Boolean, required: true },
    },
    components: {
        OperationsPanel,
        VueSelect,
        InputSearch,
        InputText,
        Pager,
        getLabelText,
        SearchPanel,
        ModalPopUp,
        NoRecords,
        VueMultiSelectableSelected,
        DatePicker,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            owners: {},
            statuses: accountStatusList,
            totalRecords: 0,
            records: [],
            search: {
                selectedOwner: '',
                srchId: '',
                srchDomainName: '',
                clientId: (this.customerId != '0' ? this.customerId : ''),
                customerName: '',
                companyName: '',
                labelSrch: '',
                orgName: '',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'ExchHostingID',
                sortDir: 'Asc',
                updateSorting: false,
                selectedStatus: '-1',
            },
            showClearButton: false,
            useTranslation: true,
            ucOrgs: [],
            selectedOrgs: [],
            cbEnableLH4AllMBox: false,
            tbLHDurationUnlimited: true,
            tbLHDuration: '',
            lhDate: this.currentDate,

            //***** START: Modal Popup *******
            showModal: false,
            modalTitle: this.getLabelText('Exch0901'),
            modalBody: '',
            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();
        },
        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();
        },
        ownerChangeHandler: async function (obj) {

            this.search.selectedOwner = obj.selectedValue;
            setOwnerCookie(obj.selectedValue);

        },
        statusChangeHandler: function (obj) {
            this.search.selectedStatus = obj.selectedValue;
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listAccounts().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        listAccounts: async function () {

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

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

                    vm.search.updateSorting = false;
                    vm.records = JSON.parse(data.d);                    
                    if (vm.records.length > 0)
                        this.totalRecords = this.records[0].Counter;
                });
            vm.isLoading = false;
        },
        fixSecurityGroup: function (labelsearch, Orgname) {

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

                'LabelSrch': labelsearch,
                'OrgName': Orgname
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Exchange/ExAccounts.aspx/FixSecurityGroup", postRequest)
                .then(response => response.json()).then((data) => {
                    //  alert(data.d);
                    if (data.d == true || data.d == 'true') {
                        //    alert('inside if '+data.d);
                        displaySuccessMsg(this.getLabelText('MP00989')); //

                    }

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

        },
        syncData: function (labelsearch, Orgname) {

            if (confirm(this.getLabelText('MP00909'))) {
                let postRequest = { ...fetchPost };
                var param = {

                    'LabelSrch': labelsearch,
                    'OrgName': Orgname
                };

                postRequest.body = JSON.stringify(param);

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

                        //if (data.d == this.getLabelText('MP0035')) {
                        //    displaySuccessMsg(this.getLabelText('MP0035'));
                        //}
                        //else {
                        displaySuccessMsg(data.d);
                        //  }

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

        },
        getLabelText,
        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 = this.owners.initialValue;

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

        },
        doClearSearch: async function () {
           
            this.search.selectedStatus = this.statuses.initialValue;
            this.search.srchId = '';
            this.search.srchDomainName = '';
            this.search.clientId = '';
            this.search.customerName = '';
            this.search.companyName = '';
            this.search.labelSrch = '';
            this.search.orgName = '';
            this.search.pageIndex = 1;
            this.search.pageSize = 20;
            this.search.sortExpression = 'ExchHostingId';
            this.search.sortDir = 'Asc';
            clearAllMsgs();
            this.doSearch();

        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        fillUCOrgs: async function () {
            var vm = this;

            await fetch("/RCC/Exchange/ExAccounts.aspx/FillOrganizations?allOrgs=0", 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));
        },
        lhDateSelectHandler: function (d) {
            this.lhDate = d.selectedDateStr;
        },
        mpModelEventHandler: function (obj) {
            if (obj.submit == true) {
                this.enableLHOnOrgs();
            }
            else {
                this.clearPopUpControls();
                this.showModal = false;
            }
        },
        clearPopUpControls: function () {
            this.selectedOrgs = [];
            this.cbEnableLH4AllMBox = false;
            this.tbLHDurationUnlimited = true;
            this.tbLHDuration = '';
            this.lhDate = this.currentDate;
        },
        enableLHOnOrgs: function () {

            if (this.selectedOrgs == null || this.selectedOrgs == undefined || this.selectedOrgs.length <= 0) {
                alert(this.getLabelText('strPleaseSelectOrganization'));
                this.showModal = true;
                $('#lhenabled').modal('show');
                return;
            }

            var vm = this;
            let postRequest = { ...fetchPost };
            let params = {
                "selectedOrgs": this.selectedOrgs,
                "cbEnableLH4AllMBox": this.cbEnableLH4AllMBox,
                "tbLHDurationUnlimited": this.tbLHDurationUnlimited,
                "tbLHDuration": this.tbLHDuration,
                "lhDate": this.lhDate
            };
            postRequest.body = JSON.stringify(params);

            fetch("/RCC/Exchange/ExAccounts.aspx/EnableLitigationHold", 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);
                });

            this.clearPopUpControls();
            this.showModal = false;
        },
        showPopUp: function () {
            this.clearPopUpControls();
            this.showModal = true;
        },
    },
    created: async function () {
        this.search.sortDir = this.sortPreference.SortDirection;
        this.search.sortExpression = this.sortPreference.SortExpression;
        this.search.selectedStatus = this.statuses.initialValue;

        var vm = this;
        await this.listOwners().then(this.fillUCOrgs).then(this.listAccounts).catch(function (e) {
            vm.records = [];
            vm.ucOrgs = [];
            vm.totalRecords = 0;
            vm.isLoading = false;
            displayErrorMsg(e);
        });


    },
    template: '#exaccounts-template'

}