import VueSelect from '/Components/Common/VueSelect.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 InputText from "/Components/Common/InputText.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 },
        customerId: { type: String, required: true },
        isLoggedInAsCustomer: { type: Boolean, required: true },
        aliasTypesFilter: { type: Object, required: true },
    },
    components: {
        SearchPanel,
        OperationsPanel,
        VueSelect,
        InputSearch,
        InputText,
        NoRecords,
        Pager,
        Loading,
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            owners: {},
            typesFilter: this.aliasTypesFilter,
            search: {
                selectedOwner: '',
                selectedTypeFilter: 'all', 
                clientId: (this.customerId != '0' ? this.customerId : ''),
                customerName: '',
                clientCompanyName: '',
                aliasNameFilter: '',
                descriptionFilter: '',
                detailsFilter: '',

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'Name',
                sortDir: 'Asc'
            },
            showClearButton: false,
        }
    },
    methods: {
        ownerChangeHandler: async function (obj) {

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

        },
        typeChangeHandler: function (obj) {

            this.search.selectedTypeFilter = obj.selectedValue;

        },
        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

            if (obj.submit == true)
                this.doSearch();
        },
        getLabelText,
        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();
        },
        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 = vm.owners.initialValue;

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

        },
        listRecords: async function () {
            var vm = this;
            vm.isLoading = true;
            let postRequest = { ...fetchPost };
            postRequest.body = JSON.stringify(vm.search);
            //console.log(vm.search);
            await fetch("/PCC/VPS/SDN/SDN.aspx/GetAliases", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.records = JSON.parse(data.d);
                    if (vm.records.length > 0)
                        this.totalRecords = this.records[0].Counter;
                });
            vm.isLoading = false;
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {
            this.search.clientId = (this.customerId != '0' ? this.customerId : '');
            this.search.customerName = '';
            this.search.clientCompanyName = '';
            this.search.aliasNameFilter = '';
            this.search.selectedTypeFilter = 'all';
            this.search.descriptionFilter = '';
            this.search.detailsFilter = '';

            this.search.pageIndex = 1;

            updateSelectInterface();    //Required to update SOL control in case of html select.
            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        confirmRemove: function (e) {
            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

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

            let sId = e.target.dataset.id;
            let name = e.target.dataset.name;

            if (confirm(this.getLabelText('CBE001').replace('%operand%', name)))
                this.removeRecord(sId);
        },
        removeRecord: function (sId) {

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'AliasId': sId,
            };
            postRequest.body = JSON.stringify(params);

            fetch("/PCC/VPS/SDN/SDN.aspx/RemoveAlias", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },

    },
    created: async function () {

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

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