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

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

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

            isAddEditMode: false,
            headerText: this.getLabelText('GN0000361'),
            recordIdToEdit: '0',
            statusTitle: '',
            isSticky: false,
            isShownInOpenTickets: 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/ManageStatuses.aspx/GetManageStatuses", 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.isAddEditMode = true;
            this.recordIdToEdit = editId == '' ? '0' : editId;

            if (this.recordIdToEdit != '0') {
                //await this.getRecordToEdit();
            }
        },
        clearAddEditForm: function () {
            clearAllMsgs();

            this.isAddEditMode = false;
            this.recordIdToEdit = '0';
            this.statusTitle = '';
            this.isSticky = false;
            this.isShownInOpenTickets = false;
        },
        cancelRecord: function () {
            this.clearAddEditForm();

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

            if (this.statusTitle == '') {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                return false;
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'statusTitle': this.statusTitle,
                'isSticky': this.isSticky,
                'isShownInOpenTickets': this.isShownInOpenTickets
            };
            postRequest.body = JSON.stringify(params);

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

                    vm.cancelRecord();
                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        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);
        },
        removeRecord: function (Id) {
            var vm = this;

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

            fetch("/RCC/HelpDesk/ManageStatuses.aspx/RemoveStatus", 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="header"><h3>{{ getLabelText('DGN1110472') }}</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('GN0000361') }}</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-5"><a href="#" @click.prevent="sortBy('StatusTitle')">{{getLabelText('GN0000557')}}</a></th>
                                        <th class="col-xs-4">{{ getLabelText('GN0000358') }}</th>
                                        <th class="col-xs-3 align-center">{{ getLabelText('GN0000360') }}</th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td>{{ record.StatusTitle }}&nbsp;<img v-if="record.IsSticky" :src="'/Images/Icons/sticky.png'" /></td>
                                        <td><img :src="'/Images/Icons/' + (record.IsShownInOpenTickets ? 'yes' : 'error') + '.png'" /></td>

                                        <td>
                                            <a v-bind:href="'/RCC/HelpDesk/EditStatuses.aspx?StatusId=' + record.StatusId" class="btn btn-primary waves-effect">{{ getLabelText('GN0000276') }}</a>
                                            <a v-if="!readOnly && record.IsDeleteAble" @click="confrimRemove" :data-id="record.StatusId" :data-name="record.StatusTitle" class="btn btn-primary waves-effect 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 class="row" v-show="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('GN0000557') }}:</div>

                                        <div class="col-sm-4 col-xs-12">
                                            <InputText v-model:fieldValue="statusTitle"/>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-2 col-xs-12 row-label"></div>

                                        <div class="col-sm-4 col-xs-12">
                                            <div class="form-group">
                                                <label for="isSticky" class="checkbox-inline">
                                                    <input type="checkbox" id="isSticky" v-model="isSticky" />{{getLabelText('GN0000363')}}
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-2 col-xs-12 row-label"></div>

                                        <div class="col-sm-4 col-xs-12">
                                            <div class="form-group">
                                                <label for="isShownInOpenTickets" class="checkbox-inline">
                                                    <input type="checkbox" id="isShownInOpenTickets" v-model="isShownInOpenTickets" />{{getLabelText('GN0000358')}}
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-12">
                                            <a @click.prevent="saveRecord" class="btn btn-primary 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>
`
}
