import Pager from '/Components/Common/Pager.js?v=3.4'
import NoRecords from '/Components/Common/NoRecords.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 InputSearch from "/Components/Common/InputSearch.js?v=3.4"
import InputText from "/Components/Common/InputText.js?v=3.4"
import InputTextArea from "/Components/Common/InputTextArea.js?v=3.4"
import { getLabelText } from '/Components/Common/utils.js?v=3.4'
import Loading from "/Components/Common/Loading.js?v=3.4"

export default {
    props: {
        readOnly: { type: Boolean, required: true },
        sortPreference: { type: Object, required: true }
    },
    components: {
        InputSearch,
        InputText,
        InputTextArea,
        SearchPanel,
        OperationsPanel,
        NoRecords,
        Pager,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            search: {
                selectedType: '-1',
                searchString: '',

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

            headerText: this.getLabelText('GN0000655'),
            isAddEditMode: false,
            recordIdToEdit: '0',
            blockingValue: '',
            selectedBlockingType: '0',
            blockingReason: ''
        }
    },
    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.search.updateSorting = true;
            this.doSearch();
        },
        listRecords: async function () {

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

            await fetch("/RCC/HelpDesk/BlockingSettings.aspx/GetBlockingSettings", 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;
        },
        setAddEditUI: async function (editId) {
            this.clearAddEditForm();
            this.recordIdToEdit = editId == '' ? '0' : editId;
            this.isAddEditMode = true;
        },
        saveRecord: async function () {
            clearAllMsgs();
            if (this.blockingValue == '' || this.blockingReason == '') {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                return false;
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'blockingValue': this.blockingValue,
                'selectedBlockingType': this.selectedBlockingType,
                'blockingReason': this.blockingReason
            };
            postRequest.body = JSON.stringify(params);

            await fetch("/RCC/HelpDesk/BlockingSettings.aspx/SaveSettings", postRequest)
                .then(response => response.json()).then((data) => {

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

            this.isAddEditMode = false;
            this.recordIdToEdit = '0';
        },
        clearAddEditForm: function () {
            clearAllMsgs();

            this.isAddEditMode = false;
            this.recordIdToEdit = '0';
            this.blockingValue = '';
            this.selectedBlockingType = '0';
            this.blockingReason = '';
        },
        confrimRemove: function (e) {
            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

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

            //CustomerId, OwnerId, Name, SubsCount, UserCount
            let Id = e.target.dataset.id;
            let name = e.target.dataset.name;

            if (confirm(this.getLabelText('GN000200')))
                this.removeRecord(Id, name);
        },
        removeRecord: function (Id, name) {
            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'Id': Id,
                'BlockingValue': name
            };
            postRequest.body = JSON.stringify(params);

            fetch("/RCC/HelpDesk/BlockingSettings.aspx/RemoveBlockingSettings", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {
            this.search.selectedType = '-1';
            this.search.searchString = '';
            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);
            });
        },
    },
    created: async function () {

        this.search.sortDir = this.sortPreference.SortDirection;
        this.search.sortExpression = this.sortPreference.SortExpression;

        var vm = this;

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

    },
    updated: function () {
        updateSelectInterface();
        AdminBSBThemeChanges();
    },
    template: `

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

                    <div class="row" v-show="!isAddEditMode">

                        <OperationsPanel v-if="!readOnly">
                            <a @click="setAddEditUI('')" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000655') }}</a>
                        </OperationsPanel>

                        <SearchPanel id='blocking-settings' :showClearButton="showClearButton" @onSearch='doSearch' @onClear='doClearSearch'>

                            <div :class="searchContainerDivClass">
                                <div class="form-group form-float">
                                    <select v-model="search.selectedType" class="vue-select">
                                        <option value="-1">{{ getLabelText('SearchAllType') }}</option>
                                        <option value="0">{{ getLabelText('GN000174') }}</option>
                                        <option value="1">{{ getLabelText('GN0000652') }}</option>
                                        <option value="2">{{ getLabelText('GN0000653') }}</option>
                                    </select>
                                </div>
                            </div>

                            <InputSearch :searchValue="search.searchString" fieldName="searchString" :fieldLabel="getLabelText('SearchValue')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

                        </SearchPanel>

                        <div class="col-xs-12" v-if="isLoading">
                            <Loading/>
                        </div>
                    <div class="col-xs-12" v-else>
                            <table class="table table-bordered table-striped table-hover" v-if="records.length > 0">
                                <tbody>
                                    <tr>
                                        <th class="col-xs-4">{{getLabelText('GN0000649')}}</th>
                                        <th class="col-xs-5">{{ getLabelText('GN0000651') }}</th>
                                        <th class="col-xs-3 align-center" v-if="!readOnly">{{ getLabelText('GN0000360') }}</th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td>{{ record.BlockingValue }}</td>
                                        <td>{{ (record.BlockingTypeId == 0 ? getLabelText('GN000174') : (record.BlockingTypeId == 1 ? getLabelText('GN0000652') : getLabelText('GN0000653'))) }}</td>
                                        
                                        <td v-if="!readOnly">
                                            <a @click="confrimRemove" :data-id="record.BlockId" :data-name="record.BlockingValue" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000278') }}</a>
                                        </td>
                                        
                                    </tr>

                                    <Pager :totalRecords="totalRecords" :pageSize="this.search.pageSize" :currentPage="this.search.pageIndex" @pagerChange="pagerChangeHandler" />
                                </tbody>
                            </table>
                            <NoRecords v-else />
                        </div>
                    </div>

                    <div class="row" v-if="isAddEditMode">
                        <div class="col-xs-12">
                            <div class="card">
                                <div class="header">
                                    <h3 v-html="headerText"></h3>
                                </div>

                                <div class="body">

                                    <div class="row">
                                        <div class="col-sm-2 col-xs-12 row-label">{{ '* ' + getLabelText('GN0000649') }}: </div>

                                        <div class="col-sm-4 col-xs-12">
                                             <InputText v-model:fieldValue="blockingValue" />                                               
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-2 col-xs-12 row-label">{{ getLabelText('GN0000651') }}: </div>

                                        <div class="col-sm-4 col-xs-12">
                                            <div class="form-group">
                                                <select v-model="selectedBlockingType" class="vue-select" id="blockingType">
                                                    <option value="0">{{ getLabelText('GN000174') }}</option>
                                                    <option value="1">{{ getLabelText('GN0000652') }}</option>
                                                    <option value="2">{{ getLabelText('GN0000653') }}</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-2 col-xs-12 row-label">{{'* ' + getLabelText('BlockingReason') }}: </div>
                                        <div class="col-sm-10 col-xs-12">
                                             <InputTextArea v-model:fieldValue="blockingReason" fieldRows="5" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-12">
                                            <a @click.prevent="saveRecord" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000281')}} </a>
                                            <a @click.prevent="cancelRecord" class="btn btn-primary waves-effect">{{ getLabelText('GN0000572')}} </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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