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 },
        companyId: { type: String, required: true },
        employeeId: { 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,
            owners: {},
            records: [],
            search: {
                selectedOwner: '',
                templateName: '',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: '',
                sortDir: '',
            },
            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.doSearch();
        },
        ownerChangeHandler: async function (obj) {

            this.search.selectedOwner = obj.selectedValue;
            setOwnerCookie(obj.selectedValue);

        },
        listOwners: async function () {

            var vm = this;

            await fetch("/webservices/machpanelservice.asmx/FillOwnersWithoutComissionBasedResellers", 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("/RCC/Exchange/MailBoxTemplates.aspx/FillTemplates", postRequest)
                .then(response => response.json()).then((data) => {
                    
                    vm.records = JSON.parse(data.d);
                    if (vm.records.length > 0) {
                        // vm.totalRecords = vm.records.length;                        
                        vm.totalRecords = vm.records[0].itemscount;

                    }

                });
            vm.isLoading = false;
        },
        getLabelText,
        cloneTemplate: function (templateId) {

            let postRequest = { ...fetchPost };
            var param = {

                'MailBoxTemplateId': templateId
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Exchange/MailBoxTemplates.aspx/CloneTemplate", postRequest)
                .then(response => response.json()).then((data) => {
                    this.doSearch();
                    displaySuccessMsg(data.d); //


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

        },
        confirmRemove: function (templateId) {

            if (confirm(this.getLabelText('GN000200')))
                this.removeTemplate(templateId);
        },
        removeTemplate: function (templateId) {

            let postRequest = { ...fetchPost };
            var param = {

                'MailBoxTemplateId': templateId
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Exchange/MailBoxTemplates.aspx/RemoveTemplate", postRequest)
                .then(response => response.json()).then((data) => {

                    this.doSearch();
                    displaySuccessMsg(data.d); //


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

        },
        doClearSearch: async function () {

            this.search.templateName = '';
            this.search.pageIndex = 1;
            this.search.pageSize = 20;
            this.search.sortExpression = 'MailBoxTemplateId';
            this.search.sortDir = 'Asc';

            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.listOwners().then(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">

                    <OperationsPanel v-if="!readOnly">
                        <a v-bind:href="'/RCC/Exchange/AddEditMailboxTemplate.aspx'" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000659') }}</a>
                    </OperationsPanel>

                    <SearchPanel id='record-list' :showClearButton="showClearButton" @onSearch='doSearch' @onClear='doClearSearch'>                        
                        <div :class="searchContainerDivClass" v-if="owners.show">
                            <div class="form-group form-float">
                                <VueSelect :options="owners.items" :selectedValue="this.search.selectedOwner" @selectchange="ownerChangeHandler" />
                            </div>
                        </div>

                        <InputSearch :searchValue="search.templateName" fieldName="templateName" :fieldLabel="getLabelText('String273')" :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-3"> {{getLabelText("String273")}}</th>
                                    <th class="col-xs-2" v-if="companyId == 1 && employeeId != 0">{{getLabelText("SPT002811")}}</th>
                                    <th class="col-xs-2">{{getLabelText("String510")}}</th>
                                    <th class="col-xs-1">{{getLabelText("DB005")}}</th>                                   
                                    <th class="col-xs-1"> {{getLabelText("DGN1110402")}}</th>
                                    <th class="col-xs-3"> {{getLabelText("GN0000360")}}</th>
                                </tr>
                                <tr v-for="record in records">
                                    <td>{{record.TemplateName}}</td>
                                    <td v-if="companyId == 1 && employeeId != 0"><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?CID='+record.CustomerId+'&RD=1'">{{record.CompanyName}}[{{record.OwnerName}}]</a></td>
                                    <td v-if="record.ProhibitSendAndReceiveAtMB=='-1'">{{getLabelText("GN0000908")}}</td>
                                    <td v-else>{{record.ProhibitSendAndReceiveAtMB}}</td>
                                    <td><img id="Img1" :src="'/Images/icons/' + (record.OutlooklicenseEnabled ? 'yes' : 'error') + '.png'" /></td>
                                    <td><img id="Img1" :src="'/Images/icons/' + (record.ExchangeActiveSyncAccessAllowed ? 'yes' : 'error') + '.png'" /></td>
                                    <td>
                                        <button class="btn btn-primary" v-if="!readOnly" v-on:click.prevent="cloneTemplate(record.MailBoxTemplateId)">{{getLabelText("DGN1110198")}}</button>
                                        <a class="btn btn-primary" v-bind:href="'/RCC/Exchange/AddEditMailboxTemplate.aspx?TId=' + record.MailBoxTemplateId">{{getLabelText("GN0000276")}}</a>
                                        <button v-if="!readOnly" v-bind:class="[{'disabled':(record.TemplateName.toLowerCase().trim()=='basic' || record.TemplateName.toLowerCase().trim()=='standard' || record.TemplateName.toLowerCase().trim()=='standard plus' || record.TemplateName.toLowerCase().trim()=='enterprise' || record.TemplateName.toLowerCase().trim()=='enterprise plus')}, 'btn btn-primary']"  v-on:click.prevent="confirmRemove(record.MailBoxTemplateId)">{{getLabelText("GN0000278")}}</button>
                                    </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>
`

}