import VueSelect from '/Components/Common/VueSelect.js?v=3.9'
import { VueMultiSelectableSelected } from "/Components/Common/VueMultiSelectableSelected.js?v=3.9"
import InputSearch from '/Components/Common/InputSearch.js?v=3.9'
import SearchPanel from '/Components/Common/SearchPanelWrapper.js?v=3.9'
import OperationsPanel from '/Components/Common/OperationsPanelWrapper.js?v=3.9'
import Pager from '/Components/Common/Pager.js?v=3.9'
import NoRecords from '/Components/Common/NoRecords.js?v=3.9'
import { getLabelText } from '/Components/Common/utils.js?v=3.9'
import Loading from "/Components/Common/Loading.js?v=3.9"

export default {
    props: {
        readOnly: { type: Boolean, required: true },
        isCustomersMode: { type: Boolean, required: true },
        companyRolesFilter: { type: Object, required: true },
    },
    components: {
        OperationsPanel,
        SearchPanel,
        InputSearch,
        Pager,
        NoRecords,
        VueSelect,
        VueMultiSelectableSelected,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            rolesFilter: this.companyRolesFilter,
            records: [],
            search: {
                customersMode: this.isCustomersMode,
                customerNameFilter: '',
                roleFilter: '-1',

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'RecordID',
                sortDir: 'Asc',
            },
            showClearButton: false,

            headerText: this.getLabelText('AddRestriction'),
            isAddEditMode: false,
            accounts: {},
            roles: {},
            selectedAccountIds: [],
            selectedRoleIds: [],
            selectedAccountNames: [],
            selectedRoles: [],
        }
    },
    methods: {
        getLabelText,
        checkAll: function (checked) {
            this.records.map(obj => obj.IsItemSelected = checked);
        },
        checkAllChecked: function () {
            return !this.records.find(obj => !obj.IsItemSelected);
        },
        showActionButton: function () {
            return this.records.find(obj => obj.IsItemSelected);
        },
        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

            if (obj.submit == true)
                this.doSearch();
        },
        roleChangeHandler: function (obj) {

            this.search.roleFilter = obj.selectedValue;

        },
        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();
        },
        listRecords: async function () {

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

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

                    vm.records = JSON.parse(data.d);
                    if (vm.records.length > 0) {
                        vm.totalRecords = vm.records[0].TotalRecords;
                        vm.records.map(obj => ({ ...obj, IsItemSelected: false }));
                    }
                });
            vm.isLoading = false;
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doSearch: function () {

            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        doClearSearch: async function () {
            this.search.customersMode = this.isCustomersMode;
            this.search.customerNameFilter = '';
            this.search.roleFilter = '-1';

            this.search.pageIndex = 1;

            updateSelectInterface();    //Required to update SOL control in case of html select.
            this.doSearch();
        },
        accountsSelectionHandler: function (selectableItems, selectedItems, id) {
            this.selectedAccountIds = selectedItems.map(x => x.value);
            this.selectedAccountNames = selectedItems.map(x => x.text);
            //console.log("Selectable: " + JSON.stringify(selectableItems));
            //console.log("Selected: " + JSON.stringify(selectedItems));
        },
        rolesSelectionHandler: function (selectableItems, selectedItems, id) {
            this.selectedRoleIds = selectedItems.map(x => x.value);
            this.selectedRoles = selectedItems.map(x => x.text);
        },
        setAddEditUI: async function () {
            this.clearAddEditForm();

            this.accounts = {};
            this.roles = {};

            var vm = this;
            vm.isLoading = true;

            if (this.isCustomersMode) {
                await fetch("/RCC/Clients/ClientsList.aspx/GetRestrictAccessToCustomers", fetchGet)
                    .then(response => response.json()).then((data) => {

                        if (data.d != null) {
                            vm.accounts = data.d.accounts;
                            vm.roles = data.d.roles;
                            vm.isAddEditMode = true;
                        }
                    });
            }
            else {
                await fetch("/PCC/Reseller/List.aspx/GetRestrictAccessToResellers", fetchGet)
                    .then(response => response.json()).then((data) => {

                        if (data.d != null) {
                            vm.accounts = data.d.accounts;
                            vm.roles = data.d.roles;
                            vm.isAddEditMode = true;
                        }
                    });
            }

            vm.isLoading = false;
        },
        clearAddEditForm: function () {
            clearAllMsgs();

            this.isAddEditMode = false;
            this.accounts = {};
            this.roles = {};
            this.selectedAccountIds = [];
            this.selectedRoleIds = [];
        },
        confirmRemoveRecord: function (e) {

            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

            if (disabledValue === 'true' || disabledValue === true)
                return false;

            let Id = e.target.dataset.id;
            let aName = e.target.dataset.aname;
            let rName = e.target.dataset.rname;
            //console.log(e.target.dataset);

            if (confirm(this.getLabelText('String1040')))
                this.removeRecord(Id, aName, rName);
        },
        removeRecord: function (Id, aName, rName) {
            this.isLoading = true;

            var vm = this;
            let postRequest = { ...fetchPost };
            var param = {
                'Id': Id,
                'AccountName': aName,
                'RoleName': rName,
                'IsCustomersMode': vm.isCustomersMode
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Clients/ClientsList.aspx/RemoveAccessRestriction", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.search.pageIndex = 1;
                    vm.doSearch();
                    displaySuccessMsg(this.getLabelText('EGN0000011'));

                }).catch(function (e) {
                    vm.isLoading = false;
                    displayErrorMsg(e);
                });

            this.isLoading = false;
        },
        removeBulkRecords: function () {
            this.isLoading = true;
            let selectedRecords = this.records.filter(a => a.IsItemSelected);

            if (selectedRecords == null || selectedRecords == undefined || selectedRecords.length <= 0) {
                alert(this.getLabelText('GN0000889'));
            }
            else {

                var vm = this;

                let postRequest = { ...fetchPost };
                let params = {
                    data: {
                        selectedItems: selectedRecords.map(it => ({
                            "RecordID": it.RecordID,
                            "RoleId": it.RoleId,
                            "AccountName": it.AccountName,
                            "RoleName": it.RoleName,
                            "AccountId": it.AccountId
                        })),
                    },
                    IsCustomersMode: vm.isCustomersMode
                };
                postRequest.body = JSON.stringify(params);

                fetch("/RCC/Clients/ClientsList.aspx/BulkRemoveAccessRestrictions", postRequest)
                    .then(response => response.json()).then((data) => {

                        vm.doSearch();
                        displaySuccessMsg(data.d);

                    }).catch(function (e) {
                        vm.isLoading = false;
                        displayErrorMsg(e);
                    });
            }

            this.isLoading = false;
        },
        cancelRecord: function () {
            this.clearAddEditForm();

            this.search.pageIndex = 1;
            this.doSearch();
            this.isAddEditMode = false;
        },
        saveRecord: async function () {
            clearAllMsgs();
            if (this.selectedAccountIds.length <= 0 || this.selectedRoleIds.length <= 0) {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                return false;
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'isCustomersMode': this.isCustomersMode,
                'selectedRoleIds': this.selectedRoleIds,
                'selectedAccountIds': this.selectedAccountIds,
                'selectedRoles': this.selectedRoles,
                'selectedAccountNames': this.selectedAccountNames
            };
            postRequest.body = JSON.stringify(params);

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

                    vm.cancelRecord();
                    vm.search.pageIndex = 1;
                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
    },
    created: async function () {
        clearAllMsgs();
        var vm = this;

        await this.listRecords().catch(function (e) {
            vm.records = [];
            vm.totalRecords = 0;
            vm.isLoading = false;
            displayErrorMsg(e);
        });

    },
    updated: function () {
        updateSelectInterface();
        //AdminBSBThemeChanges();
    },
    template: '#restrictaccess-template',
}
