import Pager from '/Components/Common/Pager.js?v=3.6'
import OperationsPanel from '/Components/Common/OperationsPanelWrapper.js?v=3.6'
import NoRecords from '/Components/Common/NoRecords.js?v=3.6'
import { getLabelText } from '/Components/Common/utils.js?v=3.6';
import Loading from "/Components/Common/Loading.js?v=3.6"


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

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'RuleName',
                sortDir: 'Desc',
                updateSorting: false
            },
            showClearButton: false,
        }
    },
    methods: {
        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.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/TicketRules.aspx/GetTicketRules", 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;
        },
        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('CBE001').replace("%operand%", name)))
                this.removeRecord(Id, name);
        },
        removeRecord: function (Id, name) {
            var vm = this;

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

            fetch("/RCC/HelpDesk/TicketRules.aspx/RemoveTicketRules", 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.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);
        });

    },
    template: `

        <div class="col-xs-12">
            <div class="card">
                
                <div class="body">
                    <div class="row">

                        <OperationsPanel>
                            <a v-bind:href="'/RCC/HelpDesk/AddNewRule.aspx?T=TR'" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN00001234') }}</a>
                        </OperationsPanel>

                        <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"><a href="#" @click.prevent="sortBy('RuleName')">{{getLabelText('DGN1110008')}}</a></th>
                                        <th class="col-xs-6">{{ getLabelText('GN0000597') }}</th>
                                        <th class="col-xs-2 align-center">{{ getLabelText('GN0000360') }}</th>
                                    </tr>
                                    <tr v-for="record in records">
                                        <td><a v-bind:href="'/RCC/HelpDesk/AddNewRule.aspx?R=' + record.RuleID">{{ record.RuleName }}</a></td>
                                        <td v-if="record.whereClause == 1" v-html="getLabelText('GN0000540') + '<b> ' + getLabelText('GN0000371') + '</b> is &quot;<b>' + record.whereClauseValue + '</b>&quot; ...'"></td>
                                        <td v-else-if="record.whereClause == 2" v-html="getLabelText('GN0000540') + '<b> ' + getLabelText('GN0000541') + '</b> is &quot;<b>' + record.whereClauseValue + '</b>&quot; ...'"></td>
                                        <td v-else-if="record.whereClause == 3" v-html="getLabelText('GN0000540') + '<b> ' + getLabelText('GN0000542') + '</b> is &quot;<b>' + record.whereClauseValue + '</b>&quot; ...'"></td>
                                        <td v-else-if="record.whereClause == 4" v-html="getLabelText('GN0000540') + '<b> ' + getLabelText('GN0000543') + '</b> is &quot;<b>' + record.whereClauseValue + '</b>&quot; ...'"></td>
                                        
                                        <td>
                                            <a v-bind:href="'/RCC/HelpDesk/AddNewRule.aspx?R=' + record.RuleID" class="btn btn-primary">{{ getLabelText('GN0000276') }}</a>
                                            <a v-if="!readOnly && !record.RuleType" @click.prevent="confrimRemove" :data-id="record.RuleID" :data-name="record.RuleName" class="btn btn-primary btnAction">{{ getLabelText('GN0000377') }}</a>
                                        </td>                                        
                                    </tr>

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