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, getFileContentsFromInput } 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: 'PriorityId',
                sortDir: 'Asc',
                updateSorting: false
            },
            showClearButton: false,

            headerText: this.getLabelText('GN0000279'),
            isAddEditMode: false,
            recordIdToEdit: '0',
            title: '',
            imageName: '',
            imgPath: '',
            oldImagePath:'',
            imgfile:null
        }
    },
    methods: {
        getLabelText,
        getFileContentsFromInput,
        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/ManagePriorities.aspx/GetManagePriorities", 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;
        },
        getRecordToEdit: function () {
            var vm = this;

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

            fetch("/RCC/HelpDesk/ManagePriorities.aspx/GetPriorityToEdit", postRequest)
                .then(response => response.json()).then((data) => {

                    if (data.d != null) {
                        vm.title = data.d.title;
                        vm.imageName = data.d.imageName;
                        vm.headerText = this.getLabelText('GN0000279');
                        vm.oldImagePath = data.d.oldImagePath;
                        vm.isAddEditMode = true;
                    }
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        cancelRecordSave: function () {
            var vm = this;
            vm.isAddEditMode = false;
            doSearch();
        },
        saveRecord: async function () {
            var vm = this;
           // alert(vm.imgfile);
            var fileName='';
            var fileContent='';
            if (vm.title == '') {
                alert(this.getLabelText("GN00001243"));
                return;
            }
            else if ((vm.imgfile == null) && vm.recordIdToEdit == '0') {
                alert(this.getLabelText("FAM0038"));
                return;
            }
            else if ((vm.imgfile == null) && vm.recordIdToEdit != '0') {
                fileName = this.imageName;
                fileContent = '';                
            }
            else {
                fileName = vm.imgfile.name;
                fileContent = await this.getFileContentsFromInput(vm.imgfile);
            }
           
            let postRequest = { ...fetchPost };
            let params = {
                'PriorityId': vm.recordIdToEdit,
                'Title': vm.title,
                'ImageName': fileName,
                'ImageContent': fileContent
            };
            
            postRequest.body = JSON.stringify(params);

            fetch("/RCC/HelpDesk/ManagePriorities.aspx/SavePriority", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.isAddEditMode = false;
                    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/ManagePriorities.aspx/RemovePriorities", 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);
            });
        },
        setAddEditUI: async function (editId) {
            this.clearAddEditForm();
            this.recordIdToEdit = editId == '' ? '0' : editId;
           // alert(editId);
            if (this.recordIdToEdit != '0')
                await this.getRecordToEdit();
            else {

                this.isAddEditMode = true;
           //     alert(this.isAddEditMode);
            }
        },
        onFileChange: function (event) {
            this.imgfile = event.target.files[0];
        },
        clearAddEditForm: function () {
            clearAllMsgs();

            this.isAddEditMode = false;
            this.recordIdToEdit = '0';
            this.title = '';
            this.imageName = '';
            this.imgPath = '';
            this.imgfile = null;
        },
    },
    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('DGN1110471') }}</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('GN0000279') }}</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">{{getLabelText('GN0000557')}}</th>
                                        <th class="col-xs-3">{{ getLabelText('GN0000270') }}</th>
                                        <th class="col-xs-3">{{ getLabelText('GN0000282') }}</th>
                                        <th class="col-xs-3 align-center">{{ getLabelText('GN0000275') }}</th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td><img :src="'/Images/' + record.PriorityImage" /></td>
                                        <td>{{ record.PriorityTitle }}</td>
                                        <td>{{ record.PriorityImage }}</td>

                                        <td>
                                            <a @click.prevent="setAddEditUI(record.PriorityId)" class="btn btn-primary waves-effect">{{ getLabelText('GN0000276') }}</a>
                                            <a v-if="!readOnly && record.IsDeleteAble" @click="confrimRemove" :data-id="record.PriorityId" :data-name="record.PriorityTitle" 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-3 col-xs-12 row-label">* {{ getLabelText('GN0000280') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <InputText v-model:fieldValue="title" />
                                        </div>
                                    </div>      
                                    <div class="row" v-if="recordIdToEdit!=0 && false">
                                        <div class="col-sm-3 col-xs-12 row-label"> {{ getLabelText('OldImagePath') }}: </div>
                                        <div class="col-sm-4 col-xs-12">{{oldImagePath}}</div>
                                    </div>      
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">
                                            <label>{{ '* ' + getLabelText('GN0000282') }}: </label>
                                        </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <div class="form-group">
                                                <div class="fileupload fileupload-new" data-provides="fileupload">
                                                    <span class="btn btn-primary btn-file"><span class="fileupload-new">{{ getLabelText('strSelectFile') }}</span></span>
                                                    <span class="fileupload-exists">{{ getLabelText('GN0000385') }}</span>
                                                    <input type="file" @change="onFileChange" />
                                        
                                                    <span class="fileupload-preview"></span>
                                                    <a href="#" class="close fileupload-exists" data-dismiss="fileupload" style="float: none">×</a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>                                     
                                    <div class="row" v-if="!readOnly">
                                        <div class="col-xs-12">
                                            <a @click.prevent="saveRecord" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000281')}} </a>
                                            <a @click.prevent="cancelRecordSave" class="btn btn-primary waves-effect">{{ getLabelText('GN0000572')}} </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

               
`
}
