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 OperationsPanel from "/Components/Common/OperationsPanelWrapper.js?v=3.9"
import NoRecords from "/Components/Common/NoRecords.js?v=3.9"
import Loading from "/Components/Common/Loading.js?v=3.9"

export default {
    props: {
        readOnly: { type: Boolean, required: true },
        isProviderLogin: { type: Boolean, required: true },
        isLoggedInAsCustomer: { type: Boolean, required: true },
        isLoggedInAsReseller: { type: Boolean, required: true },
    },
    components: {
        OperationsPanel,
        VueSelect,
        InputSearch,
        NoRecords,
        Pager,
        SearchPanel,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            search: {
                templateName: '',
                orgName: '',
                domainName: '',
                ownerName: '',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExp: 'TemplateId',
                sortDir: 'Asc'

            },
            showClearButton: false,
            parentContext: {},  //params to execute callback method related to current operation
        };
    },
    methods: {
        getLabelText,
        newTemplate: function () {
            window.location.href = "/PCC/DC/AddEditLogOnHours.aspx";
        },
        cloneTemplate: function (obj, tName) {
            
            let postRequest = { ...fetchPost };
            let params = {
                templateId: obj,
                templateName: tName
            };

            postRequest.body = JSON.stringify(params);

            fetch("/PCC/DC/ListADOrgs.aspx/CloneTemplate", postRequest)
                .then(response => response.json()).then((data) => {

                    this.listTemplates();
                    displaySuccessMsg(data.d);

                }).catch(function (e) {

                    displayErrorMsg(e);
                });
        },
        confirmActionRemove: function (obj, tName) {

            this.parentContext = { templateId: obj, templateName: tName };

            if (confirm(this.getLabelText('CBE001').replace("%operand%", tName)))
                this.removeTemplate(this.parentContext);

        },
        removeTemplate: function (obj) {

            let postRequest = { ...fetchPost };
            let params = {
                templateId: obj.templateId,
                templateName: obj.templateName
            };

            postRequest.body = JSON.stringify(params);

            fetch("/PCC/DC/ListADOrgs.aspx/RemoveTemplate", postRequest)
                .then(response => response.json()).then((data) => {

                    this.listTemplates();
                    displaySuccessMsg(data.d);

                }).catch(function (e) {

                    displayErrorMsg(e);
                });

        },
        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.sortExp != exp) {
                this.search.sortExp = exp;
                this.search.sortDir = "Asc";
            }
            else
                this.search.sortDir = this.search.sortDir == "Asc" ? "Desc" : "Asc";

           
            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listTemplates().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        doClearSearch: async function () {

            this.search.templateName = '';
            this.search.orgName = '';
            this.search.domainName = '';
            this.search.ownerName = '';

            this.search.pageIndex = 1;
            this.search.sortExp = 'TemplateId';
            this.search.sortDir = 'ASC';

            this.doSearch();

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

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

            await fetch("/PCC/DC/ListADOrgs.aspx/GetLogonHoursTemplateList", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.records = JSON.parse(data.d)
                    if (vm.records.length > 0)
                        vm.totalRecords = vm.records[0].TotalRecords;
                });
            vm.isLoading = false;
        },
    },
    created: async function () {

        var vm = this;

        await this.listTemplates().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>
                        <button id="Btn_AddNewTemplate" class="btn btn-primary waves-effect btnAction" v-if="!readOnly" @click.prevent="newTemplate();">{{getLabelText("SMI704")}}</button>
                    </OperationsPanel>

                    <SearchPanel id="templates-list" :showClearButton="showClearButton" @onSearch="doSearch" @onClear="doClearSearch">
                        <InputSearch :searchValue="search.templateName" fieldName="templateName" :fieldLabel="getLabelText('String273')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                        <InputSearch :searchValue="search.orgName" fieldName="orgName" :fieldLabel="getLabelText('DGN1110608')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                        <InputSearch :searchValue="search.domainName" fieldName="domainName" :fieldLabel="getLabelText('GN000125')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                        <InputSearch :searchValue="search.ownerName" fieldName="ownerName" v-if="isProviderLogin" :fieldLabel="getLabelText('strOwnerEmailName')" :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">{{getLabelText("String234")}}</th>
                                    <th class="col-xs-3"><a href="#" @click.prevent="sortBy('TemplateName')">{{getLabelText("String273")}}</a></th>
                                    <th class="col-xs-2"><a href="#" @click.prevent="sortBy('TimeZone')">{{getLabelText("Lync179")}}</a></th>
                                    <th class="col-xs-3" v-if="isProviderLogin">{{getLabelText("Exh505")}}</th>
                                    <th class="col-xs-1">{{getLabelText("assignedToUsers")}}</th>
                                    <th class="col-xs-1 align-center" v-if="!readOnly">{{getLabelText("GN0000360")}}</th>
                                </tr>
                                <tr v-for="tmpl in records">
                                    <td>{{tmpl.TemplateId}}</td>
                                    <td>{{tmpl.TemplateName}} </td>
                                    <td>{{tmpl.TimeZone}} </td>

                                    <td v-if="tmpl.CustomerId != 0"><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?CID='+tmpl.CustomerId">{{tmpl.CustomerName}}</a></td>
                                    <td v-else-if="tmpl.CompanyId == 1 && isProviderLogin">{{tmpl.CompanyName}}</td>
                                    <td v-else-if="isProviderLogin"><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?RD=1&CID='+tmpl.CustomerId">{{tmpl.CompanyName}}</a></td>

                                    <td>{{tmpl.UserCount}}</td>
                                    <td class="align-center" v-if="!readOnly">
                                        <ul class="option-menu Div_OpsRow">
                                        <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="'/PCC/DC/AddEditLogOnHours.aspx?TId=' + tmpl.TemplateId" v-bind:class="[{'disabled':((isProviderLogin && (tmpl.CompanyId > 1 || tmpl.CustomerId > 0)) || (isLoggedInAsReseller && (tmpl.CompanyId == 1 || tmpl.CustomerId > 0)) || (isLoggedInAsCustomer && tmpl.CustomerId == 0))}, 'btnAction waves-effect waves-block']">{{ getLabelText('GN0000276') }}</a>
                                               </li>
                                                <li>
                                                    <a href="#" @click.prevent="cloneTemplate(tmpl.TemplateId, tmpl.TemplateName)" class="btnAction waves-effect waves-block">{{ getLabelText('DGN1110198') }}</a>
                                                </li>
                                                <li>
                                                    <a href="#" @click.prevent="confirmActionRemove(tmpl.TemplateId, tmpl.TemplateName)" v-bind:class="[{'disabled':(tmpl.UserCount > 0 || (isLoggedInAsReseller && tmpl.CompanyId == 1) || (isLoggedInAsCustomer && tmpl.CustomerId == 0))}, 'btnAction waves-effect waves-block']">{{ 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>
    `
}