import Pager from '/Components/Common/Pager.js?v=3.4'
import NoRecords from '/Components/Common/NoRecords.js?v=3.4'
import OperationsPanel from '/Components/Common/OperationsPanelWrapper.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: {
        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: 'DepatmentName',
                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/DepartmentListing.aspx/GetDepartments", 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;
        },
        confirmRemove: 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,
                'DepatmentName': name
            };
            postRequest.body = JSON.stringify(params);

            fetch("/RCC/HelpDesk/DepartmentListing.aspx/RemoveDepartment", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        cloneRecord: function (e) {
            var vm = this;

            // 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;

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

            fetch("/RCC/HelpDesk/DepartmentListing.aspx/CloneDepartment", 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('DGN1110468') }}</h3></div>
                <div class="body">
                    <div class="row">

                        <OperationsPanel v-if="!readOnly">
                            <a v-bind:href="'/RCC/HelpDesk/AddDepartment.aspx'" class="btn btn-primary waves-effect btnAction">{{ getLabelText('SM400003') }}</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-3"><a href="#" @click.prevent="sortBy('DepatmentName')">{{getLabelText('GN0000507')}}</a></th>
                                        <th class="col-xs-5">{{ getLabelText('GN0000597') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('GN0000642') }}</th>
                                        <th class="col-xs-1">{{ getLabelText('GN0000366') }}</th>
                                        <th class="col-xs-1 align-center">{{ getLabelText('GN0000360') }}</th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td>{{ record.DepatmentName }}</td>
                                        <td>{{ record.Description }}</td>
                                        <td>{{ record.IsInternal }}</td>
                                        <td>{{ record.TotalTickets }}</td>

                                        <td>
                                            <ul class="option-menu">
                                                <li class="dropdown">
                                                    <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                                                        <i class="material-icons">menu</i>
                                                    </a>
                                                    <ul class="dropdown-menu pull-right">
                                                        <li>
                                                            <a v-bind:href="'/RCC/HelpDesk/EmailTemplates.aspx?DID=' + record.TicketDepartmentId" class="LinkButtonGoy">{{ getLabelText('SM400011') }}</a>
                                                        </li>
                                                        <li>
                                                            <a v-if="!readOnly" @click.prevent="cloneRecord" :data-id="record.TicketDepartmentId" :data-name="record.DepatmentName" class="LinkButtonClone1y btnAction">{{ getLabelText('DGN1110198') }}</a>
                                                        </li>
                                                        <li>
                                                            <a v-bind:href="'/RCC/HelpDesk/EditDept.aspx?DID=' + record.TicketDepartmentId" class="LinkButtonEdity">{{ getLabelText('GN0000276') }}</a>
                                                        </li>
                                                        <li>
                                                            <a v-if="!readOnly" @click.prevent="confirmRemove" :data-id="record.TicketDepartmentId" :data-name="record.DepatmentName" class="LinkButtonRemovey btnAction">{{ getLabelText('GN0000278') }}</a>
                                                        </li>
                                                    </ul>
                                                </li>
                                            </ul>
                                        </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>
`
}
