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

export default {
    props: {
        readOnly: { type: Boolean, required: true }
    },
    components: {
        OperationsPanel,
        NoRecords,
        Pager,
        VueSelect,
        VueMultiSelectableSelected,
        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: 'ISOId',
                sortDir: 'Asc',
                updateSorting: false
            },

            headerText: this.getLabelText('ISODetails'),
            isAddEditMode: false,
            recordIdToEdit: '0',
            isoImageName: '',
            isoPath: '',
            customers: [],
            selectedCustomersIds: [],
            isActive: 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("/PCC/VPS/Setup.aspx/GetISOs", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.search.updateSorting = false;
                    vm.records = JSON.parse(data.d);
                    if (vm.records.length > 0) {
                        vm.totalRecords = vm.records[0].TotalRecords;
                    }
                });
            vm.isLoading = false;
        },
        fillCustomers: async function () {
            var vm = this;

            await fetch("/PCC/VPS/Setup.aspx/FillCustomers", fetchGet)
                .then(response => response.json()).then((data) => {

                    if (data.d != null) {
                        vm.customers = data.d;
                    }
                });
        },
        setAddEditUI: async function (editId) {
            this.clearAddEditForm();            
            this.recordIdToEdit = editId == '' ? '0' : editId;
            this.customers.clearSelection();

            if (this.recordIdToEdit != '0')
                await this.getRecordToEdit();
            else {
                //await this.fillCustomers().catch(function (e) {
                //    vm.customers = [];
                //    displayErrorMsg(e);
                //});
                
                this.isAddEditMode = true;
            }
        },
        getRecordToEdit: async function () {
            var vm = this;

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

            await fetch("/PCC/VPS/Setup.aspx/GetISOToEdit", postRequest)
                .then(response => response.json()).then((data) => {

                    if (data.d != null) {
                        vm.isActive = data.d.isActive;
                        vm.isoImageName = data.d.isoImageName;
                        vm.isoPath = data.d.isoPath;
                        //vm.customers = data.d.customers;
                        //vm.customers = vm.customers.map(i => { return { text: i.text, value: i.value, selected: data.d.customers.find(x => x.value == i.value && x.selected) ? true : false } });
                        //vm.customers.setPropertyFromListOfObjects('selected', true, 'value', data.d.customers.filter(i => i.selected).map(i => i),false);
                        //vm.customers.setPropertyFromListOfVals('selected', true, 'value', data.d.customers.filter(i => i.selected).map(i => i.value),false);
                        //vm.customers.setSelectedListByListOfObjects(data.d.customers);
                        vm.customers.setSelectedListByListOfVals(data.d.customers);
                                                
                        vm.isAddEditMode = true;
                    }
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        saveRecord: async function () {
            clearAllMsgs();
            if (this.isoImageName == '' || this.isoPath == '') {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                return false;
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'ISOId': this.recordIdToEdit,
                'isActive': this.isActive,
                'isoImageName': this.isoImageName,
                'isoPath': this.isoPath,
                'selectedCustomersIds': this.selectedCustomersIds
            };
            postRequest.body = JSON.stringify(params);

            await fetch("/PCC/VPS/Setup.aspx/SaveISO", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.cancelRecord();
                    vm.search.pageIndex = 1;
                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        cancelRecord: function () {
            this.clearAddEditForm();
            this.search.pageIndex = 1;
            this.doSearch();
            this.isAddEditMode = false;
            this.recordIdToEdit = '0';
        },
        clearAddEditForm: function () {
            clearAllMsgs();

            this.isAddEditMode = false;
            this.recordIdToEdit = '0';
            this.isoImageName = '';
            //this.customers = [];
            this.isoPath = '';
            this.isActive = false;
        },
        confirmRemoveRecord: function (e) {
            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

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

            let imageId = e.target.dataset.id;

            if (confirm(this.getLabelText('String1040')))
                this.removeRecord(imageId);
        },
        removeRecord: function (Id) {
            var vm = this;
            let postRequest = { ...fetchPost };
            var param = {
                'Id': Id
            };

            postRequest.body = JSON.stringify(param);

            fetch("/PCC/VPS/Setup.aspx/RemoveISO", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.search.pageIndex = 1;
                    vm.doSearch();
                    displaySuccessMsg(this.getLabelText('EGN0000011'));

                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doSearch: function () {

            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        selectionInfoHandler: function (selectableItems, selectedItems, id) {
            this.selectedCustomersIds = selectedItems.map(x => x.value);
            //console.log("Selectable: " + JSON.stringify(selectableItems));
            //console.log("Selected: " + JSON.stringify(selectedItems));
        },
    },
    created: async function () {

        var vm = this;

        await this.listRecords().then(this.fillCustomers).catch(function (e) {
            vm.records = [];
            vm.customers = [];
            vm.totalRecords = 0;
            vm.isLoading = false;
            displayErrorMsg(e);
        });
    },
    updated: function () {
        updateSelectInterface();
        AdminBSBThemeChanges();
    },
    template: `

        <div class="col-xs-12">
            <div class="card">
                <div class="body">
                    <div class="row" v-show="!isAddEditMode">

                        <OperationsPanel v-if="!readOnly">
                            <a @click="setAddEditUI('')" class="btn btn-primary waves-effect btnAction">{{ getLabelText('AddISO') }}</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" cellspacing="0" rules="all" border="1" v-if="records.length > 0">

                                <tbody>
                                    <tr>
                                        <th class="col-xs-4">{{ getLabelText('GN0001267') }}</th>
                                        <th class="col-xs-4">{{ getLabelText('ISOPath') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strActive') }}</th>
                                        <th class="col-xs-2 align-center" v-if="!readOnly">{{ getLabelText('GN0000360') }}</th>
                                    </tr>
                                    <tr v-for="record in records">
                                        <td><a @click.prevent="setAddEditUI(record.ISOId)">{{ record.ISOName }}</a></td>
                                        <td>{{ record.ISOPath }}</td>
                                        <td>{{ (record.IsActive ? getLabelText('Yes') : getLabelText('No')) }}</td>
                                        <td v-if="!readOnly">
                                            <a @click.prevent="setAddEditUI(record.ISOId)" class="btn btn-primary waves-effect">{{ getLabelText('GN0000276') }}</a>
                                            <a @click.prevent="confirmRemoveRecord" :data-id="record.ISOId" :disabled="(record.CanRemove != 0 ? true : null)" 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('GN0001267') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <inputText v-model:fieldValue="isoImageName" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('ISOPath') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <inputText v-model:fieldValue="isoPath" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('GN000195') }}: </div>
                                        <div class="col-sm-4 col-xs-12">                                      
                                           <input type="checkbox" v-model="isActive" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-12 row-label">* {{ getLabelText('SMI0369') }}: </div>
                                        <div class="col-xs-12">
                                            <VueMultiSelectableSelected :useTranslation="false" :items="customers" id="customers" @selectionInfo="selectionInfoHandler" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-12">
                                            <a v-if="!readOnly" @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>
`
}
