//TODO: 1-Save form functionality remaing

import { getLabelText } from '/components/common/utils.js?v=3.9'
import VueSelect from "/Components/Common/VueSelect.js?v=3.9"
import InputSearch from "/Components/Common/InputSearch.js?v=3.9"
import Pager from "/Components/Common/Pager.js?v=3.9"
import SearchPanel from "/Components/Common/SearchPanelWrapper.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 Loading from "/Components/Common/Loading.js?v=3.9"

export default {

    props: {      
        readOnly: { type: Boolean, required: true },
        DBName: { type: String, required: true },
        ServerGroupId: { type: String, required: true },
    },
    components: {
        OperationsPanel,
        VueSelect,
        InputSearch,
        Pager,
        SearchPanel,
        NoRecords,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            search: {
                serverGroupId: this.ServerGroupId,
                dbName: this.DBName,
                selectedOwner: '',
                clientId: '',
                customerName: '',
                organization: '',                
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'MailboxId',
                sortDir: 'Asc',
                updateSorting: false
            },
            globalSettings: {},
            showClearButton: false,

        }
    },
    methods: {
        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

            if (obj.submit == true)
                this.doSearch();
        },
        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();
        },
        serverGroupChangeHandler: async function (obj) {

            this.search.selectedServerGroup = obj.selectedValue;


        },
        checkAll: function (checked) {
            this.records.map(obj => obj.IsItemSelected = checked);
        },
        checkAllChecked: function () {
            return !this.records.find(obj => !obj.IsItemSelected);
        },
        listOwners: async function () {

            var vm = this;

            await fetch("/webservices/machpanelservice.asmx/GetOwners", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.owners = JSON.parse(data.d);
                    vm.search.selectedOwner = vm.owners.initialValue;

                })
                .catch(function (e) {
                    displayErrorMsg(e);
                });

        },
        listRecords: async function () {

            var vm = this;    
            vm.isLoading = true;
            let postRequest = { ...fetchPost };
            postRequest.body = JSON.stringify(vm.search);

            await fetch("/PCC/Exchange/ExchDatabasesCopy.aspx/FillArchive", 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;
        },
        getLabelText,
        doClearSearch: async function () {            
            this.search.customerName = '';
            this.search.organization = '';
            this.search.displayName = '';
             
            this.search.pageIndex = 1;         
            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.settings = [];
                if (vm.settings.length > 0)
                    vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });

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

    },
    created: async function () {       
        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">

                    <SearchPanel id='record-list' :showClearButton="showClearButton" @onSearch='doSearch' @onClear='doClearSearch'>
                        
                        <div :class="searchContainerDivClass" v-if="false" >
                            <div class="form-group form-float">
                                <VueSelect :options="owners.items" :selectedValue="this.search.selectedOwner" @selectchange="ownerChangeHandler" />
                            </div>
                        </div>
                        
                        <InputSearch :searchValue="search.clientId" fieldName="clientId" fieldDataType="Number" v-if="!isLoggedInAsCustomer"  :fieldLabel="getLabelText('GN0000715')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                        <InputSearch :searchValue="search.customerName" fieldName="customerName" v-if="!isLoggedInAsCustomer"  :fieldLabel="getLabelText('GN0000268')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" /> 
                        <InputSearch :searchValue="search.organization" fieldName="organization"  :fieldLabel="getLabelText('DGN1110608')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" /> 
                          
                    </SearchPanel>

                    <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-1 align-center" v-if="!readOnly">
                                        <input type="checkbox" id="CheckAll" :checked="checkAllChecked()" @change="checkAll($event.target.checked);" />                                             
                                    </th>
                                    <th class="col-xs-4">{{getLabelText("GN00001113")}}</th>
                                    <th class="col-xs-4">{{getLabelText("GN0000652")}}</th>
                                </tr>
                                <tr v-for="record in records">
                                    <td class="align-center" v-if="!readOnly">
                                          <input type="checkbox" v-bind:id="record.MailboxId" v-model="record.IsItemSelected" />
                                    </td>
                                    <td>{{record.MailBoxDisplayName}}</td>
                                    <td>{{record.EmailAddress}}</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>
`

}