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 ModalPopUp from '/Components/Common/ModalPopUp.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: {
        isSubReseller: { type: Boolean, required: true },
        readOnly: { type: Boolean, required: true },
        isLoggedInAsCustomer: { type: Boolean, required: true },
        isLoggedInAsReseller: { type: Boolean, required: true },
        sortPreference: { type: Object, required: true },
        packageTypeId: { type: String, required: true, default: '21' },
        runGroupJob: { type: Boolean, required: true },
        tenantId: { type: Number, required: false, default: 0 },
        allowToManageO365GroupJobs: { type: Boolean, required: true },
        allowToRunO365GroupJob: { type: Boolean, required: true },
        allowToCancelO365GroupJob: { type: Boolean, required: true },
    },
    components: {
        OperationsPanel,
        VueSelect,
        InputSearch,
        Pager,
        getLabelText,
        SearchPanel,
        ModalPopUp,
        NoRecords,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            owners: {},
            actionTypes: {},
            totalRecords: 0,
            records: [],
            recordDetails: [],
            jobDetails: '',
            search: {
                selectedProductType: 21,
                selectedOwner: '',
                clientId: '',
                parameters: '',
                selectedActionType: '-1',
                selectedStatus: '-1',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'TimeStampEntered',
                sortDir: 'Desc',
                updateSorting: false,
                tId: this.tenantId
            },
            showClearButton: false,
            useTranslation: true,

            //***** START: Modal Popup *******
            showModal: false,
            modalTitle: '',
            yesText: '',
            noText: '',
            parentContext: {},  //params to execute callback method related to current operation

            showDetailModal: 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.updateSorting = true;
            this.doSearch();
        },
        checkAll: function (checked) {
            this.records.map(obj => {
                if (!(obj.job.Status != 0 && obj.job.Status != 1))
                    obj.IsItemSelected = checked;
            });


        },
        showActionButton: function () {
            return this.records.find(obj => obj.IsItemSelected);
        },
        checkAllChecked: function () {
            return !this.records.find(obj => !obj.IsItemSelected);
        },
        ownerChangeHandler: async function (obj) {

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

        },
        mpModelEventHandler: function (obj) {
            this.recordDetails = [];
            this.showModal = false;
            this.showDetailModal = false;
            this.showPassModal = false;
        },
        actionTypeChangeHandler: async function (obj) {

            this.search.selectedActionType = obj.selectedValue;

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

            var vm = this;

            let postRequest = { ...fetchPost };
            var params = {
                packageType: vm.search.selectedProductType
            };

            postRequest.body = JSON.stringify(params);

            await fetch("/webservices/machpanelservice.asmx/GetActionTypes", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.actionTypes = JSON.parse(data.d);
                    // vm.producttypes.show = true;
                    this.search.selectedActionType = vm.actionTypes.initialValue; //-1;
                });

        },
        listGroupActions: async function () {

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

            await fetch("/RCC/Network/ServiceDirector/GroupActions.aspx/FillO365Data", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.records = JSON.parse(data.d);
                    this.updateSorting = false;                    
                    if (vm.records.length > 0) {
                        vm.totalRecords = vm.records[0].TotalViews;
                        vm.records.map(obj => ({ ...obj, IsItemSelected: false }));
                    }
                });
            vm.isLoading = false;

        },
        showLogDetails: async function (jobId, packagetypeId) {

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                "JobID": jobId,
                "PackageTypeID": packagetypeId
            }
            postRequest.body = JSON.stringify(params);

            await fetch("/RCC/Network/ServiceDirector/GroupActions.aspx/FillQLogs", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.recordDetails = JSON.parse(data.d);
                    vm.showModal = true;
                    vm.parentContext = { op: "convert" };
                    vm.modalTitle = 'Job Log Detail';
                    vm.noText = getLabelText('GN000150');

                }).catch(function (e) {
                    vm.recordDetails = [];
                    //vm.totalRecords = 0;
                    displayErrorMsg(e);
                });


        },
        getLabelText,
        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);
                });

        },
        doClearSearch: async function () {

            this.search.selectedOwner = this.owners.initialValue;

            this.search.selectedProductType = 21;
            this.search.selectedActionType = this.actionTypes.initialValue;
            this.search.clientId = '';
            this.search.parameters = '';
            this.search.pageIndex = 1;
            this.search.selectedStatus = '-1';
            clearAllMsgs();
            this.doSearch();
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        resetTryCount: function (cId, selectedOwner, pTypeId) {
            // alert(cId);
            let postRequest = { ...fetchPost };
            var param = {

                'CId': cId,   //(cId === "" ? " 0 " : cId)
                'IsO365Job': true,
                'SelectedOwner': selectedOwner,
                'PackageTypeId': pTypeId
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Network/ServiceDirector/GroupActions.aspx/ResetTryCount", postRequest)
                .then(response => response.json()).then((data) => {
                    //  alert(data.d);
                    if (data.d == true || data.d == 'true') {
                        this.doSearch();
                        displaySuccessMsg(this.getLabelText('EGN0000011')); //

                    }

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

        },
        removeCompletedCancelledJobs: function (selectedOwner, orgid, pTypeId) {

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


                'SelectedOwner': selectedOwner,
                'OrganizationId': this.tenantId,
                'PackageTypeId': pTypeId
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Network/ServiceDirector/GroupActions.aspx/RemoveCompletedCancelledJobs", postRequest)
                .then(response => response.json()).then((data) => {
                    //  alert(data.d);
                    if (data.d == true || data.d == 'true') {
                        this.doSearch();
                        displaySuccessMsg(this.getLabelText('EGN0000011')); //

                    }

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

        },
        runJob: function (jobId, packageTypeId) {

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

                'JobId': jobId,
                'PackageTypeID': packageTypeId,
                'TenantId': this.tenantId
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Network/ServiceDirector/GroupActions.aspx/RunJob", postRequest)
                .then(response => response.json()).then((data) => {
                    //  alert(data.d);
                    //if (data.d == true || data.d == 'true') {
                    this.doSearch();
                    displaySuccessMsg(data.d); //

                    //}

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

        },
        jobDetailsLog: function (jobId) {
            var vm = this;
            let postRequest = { ...fetchPost };
            var param = {

                'jid': jobId
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/Network/ServiceDirector/GroupActions.aspx/FillJobDetail", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.showDetailModal = true;
                    //alert(data.d);
                    vm.jobDetails = data.d;

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

        },
        closeJobDetailLog: function () {
            var vm = this;

            $('#jobDetail').modal('hide');
            vm.showDetailModal = false;
            vm.jobDetails = '';

        },
        confirmActionCancel: function (jId) {
            //alert(jId);
            if (confirm(this.getLabelText('FAM00185')))
                this.cancelJobs(jId);



        },
        cancelJobs: function (jId) {
            let selectedRecords = this.records;
            //alert(selectedRecords.length);
            let vm = this;
            if (jId != '')
                selectedRecords = this.records.filter(a => a.job.JobId.toLowerCase() == jId.toLowerCase());
            else
                selectedRecords = this.records.filter(a => a.IsItemSelected);

            //alert(selectedRecords.length);
            if (selectedRecords.length > 0) {
                let postRequest = { ...fetchPost };
                let params = {
                    data: {
                        //selectedItems: obj.parentContext.selectedRecords
                        selectedItems: selectedRecords.map(it => ({
                            "JobId": it.job.JobId,
                            "PackageTypeId": 21,
                            "StatusId": it.job.Status,
                            "Parameters": it.job.Parameters.split('|')[0],
                            "ActionType": it.job.ActionType,
                            "AccountId": '',
                            "tid": vm.tenantId
                        })),
                    },
                    
                   
                };
                 
                postRequest.body = JSON.stringify(params);
                //alert(postRequest.body);
                fetch("/RCC/Network/ServiceDirector/GroupActions.aspx/CancelJobs", postRequest)
                    .then(response => response.json()).then((data) => {
                        this.doSearch();
                        displaySuccessMsg(data.d);

                    }).catch(function (e) {
                        displayErrorMsg(e);
                    });
            }
            else {
                displaySuccessMsg(getLabelText('EGN0000011'));
            }
        },
        handleGlobalSearch: function () {
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

            for (var i = 0; i < hashes.length; i++) {
                var hash = hashes[i].split('=');
                if (hash[0].toLowerCase() == 'org') {
                    this.search.organization = hash[1];
                }
                else if (hash[0].toLowerCase() == 'cid') {
                    this.search.clientId = hash[1];
                }
            }
        },

    },
    created: async function () {

        this.search.sortDir = this.sortPreference.SortDirection;
        this.search.sortExpression = this.sortPreference.SortExpression;


        var vm = this;
        this.handleGlobalSearch();
        await this.listOwners().then(this.listActionTypes).then(this.listGroupActions).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">

                        <ModalPopUp v-if="showModal" :id="'groupActions'" :parentContext="parentContext" :modalTitle="modalTitle"
                            :yesButtonText="yesText" :noButtonText="noText" @onYes="mpModelEventHandler" @onNo="mpModelEventHandler">
                            <table class="table table-bordered table-striped table-hover table-layout-fixed" cellspacing="0" rules="all" border="1">
                                <tbody>
                                    <tr>
                                        <th class="col-xs-3">{{ getLabelText('Dev676') }}</th>
                                        <th class="col-xs-8">{{ getLabelText('Dev675') }}</th>                
                                    </tr>
                                    <tr v-for="record in recordDetails">
                                        <td>{{ record.LogEntryHeader }}</td>
                                        <td v-html="record.LogEntry"></td>
                                    </tr>
                                </tbody>
                            </table>
                        </ModalPopUp>
 
                        <ModalPopUp v-if="showDetailModal" :id="'jobDetail'" :parentContext="parentContext" :modalTitle="modalTitle"
                            :yesButtonText="yesText" :noButtonText="noText" @onYes="mpModelEventHandler" @onNo="mpModelEventHandler">                            
                               
                            <div class="row">
                                <div class="col-xs-2"><b>{{ getLabelText('JobDetails') }}:</b> </div>
                                <div class="col-xs-10"><pre>{{ this.jobDetails }}</pre></div>                
                            </div>  
                            </br>
                                                                                     
                        </ModalPopUp>

                        <OperationsPanel  v-if="!readOnly">
                            <a @click="resetTryCount(search.clientId,search.selectedOwner,search.selectedProductType);" class="btn btn-primary waves-effect btnAction">{{ getLabelText('ResetTriesCount') }}</a>
                            <a @click="removeCompletedCancelledJobs(search.selectedOwner,0,search.selectedProductType)" class="btn btn-primary waves-effect btnAction">{{ getLabelText('clearJobs') }}</a>
                             <a @click="confirmActionCancel('')" v-show="showActionButton()" class="btn btn-primary waves-effect btnAction">{{ getLabelText('AB0006') }}</a>  
                            <a v-bind:href="'/RCC/Network/ServiceDirector/GroupActionsSettings.aspx'" v-if="packageTypeId == -1 && !isLoggedInAsCustomer && !isLoggedInAsReseller && !isSubReseller" class="btn btn-primary waves-effect btnAction">{{ getLabelText('strGroupJobsSettings') }}</a>
                        </OperationsPanel>

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

                            <div :class="searchContainerDivClass" v-if="actionTypes.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="actionTypes.items" :selectedValue="this.search.selectedActionType" @selectchange="actionTypeChangeHandler" />
                                </div>
                            </div>
                                                                                                                                       
                           
                            <div :class="searchContainerDivClass">
                                <div class="form-group form-float">
                                    <select v-model="search.selectedStatus" class="vue-select">
                                        <option value="-1">{{ getLabelText('SelectStatus') }}</option>
                                        <option value="2">{{ getLabelText('GN0000347') }}</option>
                                        <option value="3">{{ getLabelText('GN0000343') }}</option>
                                        <option value="1">{{ getLabelText('DGN1110246') }}</option>
                                        <option value="0">{{ getLabelText('GN0000348') }}</option>
                                        <option value="4">{{ getLabelText('strInProcess') }}</option>
                                    </select>
                                </div>
                            </div>

                            <InputSearch :searchValue="search.clientId" fieldName="clientId" fieldDataType="Number" v-if="!isLoggedInAsCustomer"  :fieldLabel="getLabelText('GN0000715')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                                                                                                                                                
                            <InputSearch :searchValue="search.parameters" fieldName="parameters"  :fieldLabel="getLabelText('Parameters')" :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 || isSubReseller)">
                                            <input type="checkbox" id="CheckAll" :checked="checkAllChecked()" @change="checkAll($event.target.checked);" />
                                            <label for="CheckAll"></label>                                            
                                        </th>
                                        <th class="col-xs-1">{{getLabelText("String385")}}</th>
                                        <th class="col-xs-2" >{{getLabelText("DGN1110209")}}</th>
                                        <th class="col-xs-1"><a href="#" @click.prevent="sortBy('TimeStampEntered')">{{getLabelText("DGN1110210")}}</a></th>
                                        <th class="col-xs-1"><a href="#" @click.prevent="sortBy('TriesCount')">{{getLabelText("GN0000813")}}</a></th>
                                        <th class="col-xs-1"><a href="#" @click.prevent="sortBy('LastTryTimeStamp')">{{getLabelText("DGN1110212")}}</a></th>  
                                        <th class="col-xs-1"><a href="#" @click.prevent="sortBy('O365RecordType')">{{getLabelText("FAM00133")}}</a></th> 
                                        <th class="col-xs-1" v-if="!isLoggedInAsCustomer && (tenantId == '' || tenantId == '0')"><a href="#" @click.prevent="sortBy('CustomerId')">{{getLabelText("GN0000850")}}</a></th>
                                        <th class="col-xs-2" v-if="owners.show && !isLoggedInAsCustomer && !isLoggedInAsReseller && (tenantId == '' || tenantId == '0')"><a href="#" @click.prevent="sortBy('Owner')">{{getLabelText("Exh505")}}</a></th>
                                        <th class="col-xs-1 align-center" v-if="!isLoggedInAsCustomer && !isLoggedInAsReseller && (tenantId == '' || tenantId == '0')">{{getLabelText("GN0000839")}}</th>
                                        <th class="col-xs-1 align-center">{{getLabelText("GN0000360")}}</th>
                                    </tr>
                                    <tr v-for="record in records">
                                       <td class="align-center" v-if="!(readOnly || isSubReseller)" >
                                            <input type="checkbox" v-bind:id="record.job.JobId" :disabled="(record.job.Status!=0 && record.job.Status!=1)" v-model="record.IsItemSelected" />
                                            <label v-bind:for="record.job.JobId"></label>                                           
                                        </td>
                                        <td v-if="record.job.InProcess">{{getLabelText("strInProcess")}}</td>
                                        <td v-else-if="record.job.Status == 0">{{getLabelText("GN0000348")}}</td>
                                        <td v-else-if="record.job.Status == 1"><a @click.left.prevent="showLogDetails(record.job.JobId,21)">{{getLabelText("DGN1110246")}}</a></td>
                                        <td v-else-if="record.job.Status == 2"><a @click.left.prevent="showLogDetails(record.job.JobId,21)">{{getLabelText("GN0000347")}}</a></td>
                                        <td v-else-if="record.job.Status == 3"><a @click.left.prevent="showLogDetails(record.job.JobId,21)">{{getLabelText("GN0000343")}}</a></td>      

                                        <td v-html="record.job.Parameters.split('¤')[0]"></td>
                                        <td>{{record.job.Parameters.split('¤')[2]}}</td>
                                        <td>{{record.job.TriesCount}}</td>
                                        <td>{{record.job.Parameters.split('¤')[3]}}</td>
                                        <td>{{record.job.Parameters.split('¤')[1]}}</td>
                                        <td v-if="!isLoggedInAsCustomer && (tenantId == '' || tenantId == '0')"><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?CID='+record.CustomerId+'&Src=C'"># {{record.CustomerId}} {{record.CustomerName}} </a></td>
                                        <td v-else-if="!isLoggedInAsCustomer && record.CompanyName!='' && (tenantId == '' || tenantId == '0')"><a v-bind:href="'/RCC/Clients/ClientDetail.aspx?CID='+record.CustomerId+'&Src=C'"># {{record.CustomerId}} {{record.CustomerName}}[{{record.CompanyName}}] </a></td>
                                        
                                        <td v-if="owners.show && !isLoggedInAsCustomer && !isLoggedInAsReseller && (record.CompanyId=='' || record.CompanyId=='1') && (tenantId == '' || tenantId == '0')">{{ record.TenantOwner }}</td>
                                        <td v-else-if="owners.show && !isLoggedInAsCustomer && (tenantId == '' || tenantId == '0')">
                                            <a v-bind:href="'/RCC/Clients/ClientDetail.aspx?CID='+record.CustomerId+'&RD=1'">{{record.TenantOwner}}</a>
                                        </td>

                                        <td v-if="!isLoggedInAsCustomer && !isLoggedInAsReseller">{{record.job.AddedBy}}</td>
                                        <td class="align-center">
                                            <button v-if="!readOnly && !record.job.InProcess && allowToManageO365GroupJobs && allowToRunO365GroupJob && (runGroupJob || record.TriesCount >= 100)" v-bind:class="[{'disabled':(record.job.Status==2 || record.job.Status==3)}, 'btn btn-primary']"  v-on:click.prevent="runJob(record.job.JobId,21);">{{getLabelText("DGN1110045")}}</button>
                                            <button class="btn btn-primary" v-if="!readOnly && !record.job.InProcess && allowToManageO365GroupJobs && allowToCancelO365GroupJob" v-bind:class="[{'disabled':(record.job.Status==2 || record.job.Status==3)}, 'btn btn-primary']" @click.prevent="confirmActionCancel(record.job.JobId);">{{getLabelText("GN0000572")}}</button>
                                            <button class="btn btn-primary" v-on:click.prevent="jobDetailsLog(record.job.JobId)">{{getLabelText("Detail")}}</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>
`

}