/**
 * 列表批处理操作扩展，跨页全选参数封装
 * @author zongwen_liu
 */
var that;
var crossPageSelectAllEventButtonList =[];
shr.defineClass("shr.dormitorysystem.commonBatchListNew", shr.framework.List, {
    maxRecords: 1000,
    theMaxRecords: 3000,   // 最大处理条数
    submitRecordsStep: 200, // 每次处理条数
    virtualQueryMode: "1", //默认走虚模式查询
    /**
     * dealWithOriginalPostData设置为true后，上面三个条件都会失效，CommonBatchListHandler.java将不会分批调用业务方法，只会将当前跨页全选所需参数传到后端，
     * 业务方法在handler方法中通过this.getGridRequestData(request, response, modelMap); 自行查询获取跨页全选的所有数据进行处理
     */
    dealWithOriginalPostData: false,
    isOverTheMaxRecordsRefuseDeal: false, // 超过最大处理条数是否拒绝处理前theMaxRecords条
    _crossPage: {
        YES: "1", // 跨页全选
        NO: "0"
    },
    //theMaxRecordsMessage: jsBizMultLan.perfweb_commonBatchList_i18n_3,
    instructionTpl: [
        '<div class="tipsboxwrap">',
        //'<div class="tipsbox">',
        //jsBizMultLan.perfweb_commonBatchList_i18n_6,
        //'</div>',
        '</div>',
    ].join(''),

    initalizeDOM: function () {
        shr.dormitorysystem.commonBatchListNew.superClass.initalizeDOM.call(this);
        that = this;
        // 在跨页全选按钮后边加tips
        /*$(".singleradioallselectwrap").after("<span class='selectAllTips'></span>");
        $(".selectAllTips").css({
            "width": "16px",
            "height": "16px",
            "border-radius": "100%",
            "background": 'url("addon/perfweb/web/images/btn-questionmark.png") center no-repeat #abb1bc',
            "cursor": "pointer",
            "display": "inline-block",
            "vertical-align": "middle",
            "margin-left": "8px",
        });
        var instructionHtml = shr.formatMsg(this.instructionTpl, [this.theMaxRecords]);
        $(".selectAllTips").append(instructionHtml);
        $('.tipsboxwrap').css({
            "background": "#ffffff",
            "box-shadow": "0 4px 20px 0 rgba(0,0,0,0.2), 0 -2px 10px 0 rgba(0,0,0,0.2)",
            "position": "relative",
            "width": "220px",
            "z-index": 2,
            "padding": "5px",
            "display": "none",
            "margin-left": "-25px",
            "margin-top": "20px"
        });*/
        this.crossPageSelectAllEvent();

        //考核结果显示控制
        if(typeof initResultShow == 'function') {
            initResultShow(this.gridId);
        }
    },

    /**
     * 获取快速过滤字段值-考核周期
     */
    getPeriodId: function () {
        //经常获取不到f7的值
        var period = $('#f7-period').shrPromptBox('getValue');
        if (typeof period != "undefined") {
            period = period['id'];
        } else {
            period = this.getFastFilterItemValueByItemName("bizDate");
        }
        if (period == "undefined" || period == null || period == "") {
            period = shr.getUrlRequestParam("period", window.parent.location.href);
        }
        return period;
    },

    /**
     * 跨页全选点击事件
     */
    crossPageSelectAllEvent: function () {
        //跨页全选点击事件
        $('.singleradioallselectwrap').live('click', function () {
            var radio = $(this).find('.singleradioallselect');
            if (radio.hasClass('singleradio_select')) {
                radio.removeClass('singleradio_select');
                $('.doneinspection').hide();
                //取消跨页全选，放开所有按钮
                for(var i=0,len=crossPageSelectAllEventButtonList.length; i<len; i++) {
                    $('#'+crossPageSelectAllEventButtonList[i]).show();
                }
            } else {
                radio.addClass('singleradio_select');
                $('.doneinspection').show();
                //点击跨页全选，隐藏不能跨页全选按钮
                for(var i=0,len=crossPageSelectAllEventButtonList.length; i<len; i++) {
                    $('#'+crossPageSelectAllEventButtonList[i]).hide();
                }
            }
        });
        //跨页全选tips点击事件
        // $(".selectAllTips").live('click', function () {
        //     var box = $('.tipsboxwrap');
        //     if (box.is(':hidden')) {
        //         box.fadeIn();
        //     } else {
        //         box.fadeOut();
        //     }
        //     event.stopPropagation();
        // });
        $(".selectAllTips").live('mouseover', function () {
            var box = $('.tipsboxwrap');
            box.fadeIn();
        });
        $(".selectAllTips").live('mouseout', function () {
            var box = $('.tipsboxwrap');
            box.fadeOut();
        });
        $(document).click(function (e) {
            if (!$(e.target).hasClass('selectAllTips') && !$(e.target).hasClass('tipsboxwrap')) {
                $(".tipsboxwrap").fadeOut();
            }
        });
    },

    /**
     * 按钮操作前校验是否有表格中数据
     * @returns {boolean}
     */
    checkSelectIds: function () {
        var rowDatas = $(this.gridId).jqGrid("getRowData");
        if (!rowDatas || rowDatas.length == 0) {
            shr.showWarning({message: "没有数据！"});
            return false;
        }
        var billIds = this.getSelectedFields();
        if (("" == billIds || null == billIds || !billIds || billIds.length === 0) ) {
            billIds = this.getSelectedRealIds();
            if (("" == billIds || null == billIds || !billIds || billIds.length === 0)) {
                shr.showWarning({
                    message: "请选择数据行",
                    hideAfter: 3
                });
                return false;
            }
        }
        return true;
    },

    /**
     * 获取通用批处理所需参数，包含跨页全选所需的各种过滤条件参数
     */
    getCommonParamsForBatchAction: function (option) {
        var $grid = $(this.gridId);
        var postData = $grid.jqGrid("getGridParam", "postData");
        $grid._pingPostData(postData);
        var param = $.extend({}, postData, option);
        param.method = "commonBatch";
        if (!option.billId) {
            param.billId = this.getSelectedIds();
        }
        param.isAll = true; //获取全部数据，不需要进行分页查询
        if (option.selectAll) {
            param.isCrossPageSelectAll = this._crossPage.YES;
        } else {
            param.isCrossPageSelectAll = this.isCrossPageSelectAll();   //是否跨页全选
        }
        return param;
    },

    /*getSelectedIds: function() {
        var billIds = shr.perfweb.commonBatchList.superClass.getSelectedIds.call(this);
        if ("" == billIds || null == billIds || !billIds || billIds.length === 0) {
            return this.getSelectedRealIds();
        }
    },*/

    /**
     * 是否有选择跨页全选
     */
    isCrossPageSelectAll: function () {
        if ($('.singleradioallselect').hasClass('singleradio_select')) {
            return that._crossPage.YES;
        }
        return that._crossPage.NO;
    },

    /**
     * 取消跨页全选选中
     */
    cancelCrossPageSelected: function (isCancelCrossPageSelected) {
        if (isCancelCrossPageSelected) {
            $('.singleradioallselect').removeClass('singleradio_select')
            //显示被隐藏的按钮
            //取消跨页全选，放开所有按钮
            for(var i=0,len=crossPageSelectAllEventButtonList.length; i<len; i++) {
                $('#'+crossPageSelectAllEventButtonList[i]).show();
            }
            //BT-01722227 目标填报下达，还未填报下达前，点击“直接下达”或“待确认”，会出现“目标下达人”按钮，不应显示出来
            if(this.targetTransmitBillWay == '1'){
                $("#distributeGroupBtn").hide();
            }
        }
    },

    /**
     * 查询表格
     */
    queryGrid: function() {
        var _self = this;
        _self.initData.custom_params.virtualQueryMode = _self.virtualQueryMode;
        shr.dormitorysystem.commonBatchListNew.superClass.queryGrid.call(this);
    },

    /**
     * 扩展批处理方法
     */
    doRemoteWithBatchExtendAction: function (option) {
        var $grid = $(this.gridId),
            totalRecords = $grid.jqGrid('getGridParam', 'records');
        option.rows = totalRecords;
        option.realMethod = option.method;
        delete option.method;
        var params = that.getCommonParamsForBatchAction(option);
        params.theMaxRecords = this.theMaxRecords;
        params.submitRecordsStep = this.submitRecordsStep;
        params.dealWithOriginalPostData = this.dealWithOriginalPostData;
        params.virtualQueryMode =  this.virtualQueryMode;
        params.isCancelCrossPageSelected = option.isCancelCrossPageSelected;
        params.isShowCustomerMessage = option.isShowCustomerMessage;
        if (option.isCancelCrossPageSelected == undefined) {
            params.isCancelCrossPageSelected = true;
        }
        if (option.gridFrame != undefined && option.gridFrame != "") {
            this.gridFrame = option.gridFrame;
        }
        var messageFun;
        if($.isFunction(top.Messenger)){
            messageFun = top.Messenger();
        }else{
            messageFun = Messenger();
        }
        messageFun.hideAll();

        that.doRemoteWithBatchAction(params);
        that.cancelCrossPageSelected(params.isCancelCrossPageSelected);

    },

    doRemoteWithBatchAction: function (param) {
        var _self = this;
        var data = param;
        var func = data.func;
        var success = param.success;
        delete data.func;
        data = $.extend(_self.prepareParam(), data);
        data = $.extend({permItemId: shr.getCurrentPagePermItemId()}, data);
        //增加异步处理不弹框
        var showDialog = param.showDialog;
        if(showDialog == undefined ||showDialog == 'undefined' || showDialog == null ){
            showDialog = true;
        }
        var async = param.async;
        if(async == undefined ||async == 'undefined' || async == null ){
            async = false;
        }
        var showBlock = param.showBlock;
        if(showBlock == undefined ||showBlock == 'undefined' || showBlock == null ){
            showBlock = true;
        }
        shr.doWithBatchAction({
            url: _self.dynamicPage_url,
            type: 'post',
            data: data,
            async:async,
            showBlock:showBlock,
            success: function (response) {
                if (response) {
                    if (func && typeof func === "function") {
                        func(response);
                    }

                    if (success && typeof success === "function") {
                        return success(response);
                    }
                    _self.reloadGrid();
                    setTimeout(()=>{
                        data.billId=response.billId;
                        var batchTipsData = _self.batchTipsDataHandler(response, data);
                        if(showDialog) {
                            $(_self).shrMessageTips({
                                isSuccess: batchTipsData.isSuccess,
                                successCount: batchTipsData.successCount,
                                failureCount: batchTipsData.failureCount,
                                confirmCallback: function () {
                                    $(_self).shrDetailTips({
                                        tableData: batchTipsData.tmp,
                                        successCount: batchTipsData.successCount,
                                        failureCount: batchTipsData.failureCount,
                                        colNamesData: batchTipsData.tableModel,
                                        isSortable: _self.batchHandlerWhetherSortable(),
                                        modalWidth: param.modalWidth || ''
                                    }).shrDetailTips("open");
                                },

                                closeCallback: function () {
                                    _self.reloadGrid();
                                }
                            }).shrMessageTips("open");
                        }
                    }, 300);

                } else {
                    $(_self).shrMessageTips("_setDetailDisable");
                }
            },
            error: function (response) {
                if (param.billId && param.billId.split(',').length > 1) {
                    _self.reloadGrid();
                }
            }
        });
    },

    /**
     * 跨页全选批处理方法
     */
    _doRemoteWithCrossPageSelectAllAction: function (param) {
        var _self = this;
        var data = param;
        data = $.extend(_self.prepareParam(), data);
        data = $.extend({permItemId: shr.getCurrentPagePermItemId()}, data);
        var isShowCustomerMessage = false;
        if (param.isShowCustomerMessage != 'undefined') {
            isShowCustomerMessage = param.isShowCustomerMessage;
        }
        var success = param.success;
        //增加异步处理不弹框
        var showDialog = param.showDialog;
        if(showDialog == undefined ||showDialog == 'undefined' || showDialog == null ){
            showDialog = true;
        }
        var async = param.async;
        if(async == undefined ||async == 'undefined' || async == null ){
            async = false;
        }
        var showBlock = param.showBlock;
        if(showBlock == undefined ||showBlock == 'undefined' || showBlock == null ){
            showBlock = true;
        }
        if (showBlock && parent) {
            parent.$.block.show();
        }
        shr.doWithBatchAction({
            url: _self.dynamicPage_url,
            type: 'post',
            data: data,
            async:async,
            showBlock: parent ? !showBlock : showBlock,
            success: function (response) {
                if (response) {
                    //var batchTipsData = _self.batchTipsDataHandler(response, data);
                    if (success && typeof success === "function") {
                        return success(response);
                    }
                    var tmp = response.result;
                    var errorMessage = "";
                    if (isShowCustomerMessage) {
                        errorMessage = response.result[0].muitTipsMessage;
                    } else {
                        var details = [];
                        // 合并错误信息
                        for (var i = 0; i < tmp.length; i++) {
                            if (!tmp[i].muitTipsState) {
                                var muitTipsMessage = tmp[i].muitTipsMessage;
                                var exists = false;
                                for (var j = 0; j < details.length; j++) {
                                    if (details[j].muitTipsMessage == muitTipsMessage) {
                                        details[j].failureCount += 1;
                                        exists = true;
                                        break;
                                    }
                                }
                                if (!exists) {
                                    details.push({muitTipsMessage: muitTipsMessage, failureCount: 1});
                                }
                            }
                        }
                        var errorMessage = shr.formatMsg(jsBizMultLan.perfweb_commonBatchList_i18n_1,
                            [response.successCount, response.failureCount]);
                        for (var k = 0; k < details.length; k++) {
                            errorMessage += shr.formatMsg(jsBizMultLan.perfweb_commonBatchList_i18n_0,
                                [details[k].failureCount, details[k].muitTipsMessage]);
                        }
                        errorMessage = juicer(errorMessage, {
                            successCount: response.successCount,
                            failureCount: response.failureCount
                        });
                    }
                    if(showDialog) {
                        $(_self).shrMessageTips({
                            isSuccess: response.failureCount == 0,
                            successCount: response.successCount,
                            failureCount: response.failureCount,
                            confirmCallback: function () {
                                shr.showWarning({message: errorMessage})
                            },

                            closeCallback: function () {
                                _self.reloadGrid();
                            }
                        }).shrMessageTips("open");
                    }
                } else {
                    $(_self).shrMessageTips("_setDetailDisable");
                }
                parent.$.block.hide();
            },
            error: function (response) {
                if (param.billId && param.billId.split(',').length > 1) {
                    _self.reloadGrid();
                }
            }
        });
    },

    /**
     * 获取合并单元格后的选中id
     */
    getRowspanSelectedIds: function () {
        return $("#grid").jqGrid('getGridParam', 'selarrrow');
    },

    /**
     * 判断是否组织考核
     */
    judgeIsOrg:function () {
        return top.shr.getUrlRequestParam("uipk").includes('4Org');
    },

    /**
     * 批量提示行数据，方便子类覆写
     */
    getBatchTipsRowDatas: function (ids, options) {
        var _self = this;
        var $table;
        if (_self.gridFrame != undefined && _self.gridFrame != "") {
            $table = $("#" + _self.gridFrame).contents().find("#grid");
        }
        if ($table == undefined || $table.length == 0) {
            $table = $(_self.gridId);
        }

        var rowDatas = []; //获取选中的表格数据,这种方法只能获取到当前页数据   bug编号：BT1155539
        for (var i = 0, l = ids.length; i < l; i++) {
            rowDatas.push($table.jqGrid('getOriginalRowData', ids[i]));
        }
        // rowDatas = _self.selectedRowData;
        return rowDatas;
    },



    /**
     * 统一封装绩效套打功能
     */
    perfTemplateName: '/s-HR/PF/PerfEvaluTarget',   //绩效套打模板名称 /s-HR/PF/PerfEvaluTarget
    perfTemplateProvider: 'com.kingdee.shr.perfweb.evaluplan.handler.PerfEvaluResultPrintDataProvider', //绩效套打后台业务处理类
    perfTemplateIdKey: 'id',   //绩效套打主键id key，没有则取billId
    perfTemplateIdSplitChar: '$', //绩效套打针对复合主键的情况，主键分隔符
    templatePrintAction: function(event) {
        // wenyi.zhou 增加参数读取，在视图中即可完成配置，不需要继承js实现getTemplateName()与getTemplateQueryPK()方法，如下
        // <button name="templatePrint" visible="true" caption="套打" functionData="{'queryPK':'com.kingdee.eas.hr.affair.app.EmpEnrollBizBillPrintQuery','templateName':'/s-HR/AffairBiz/empProve'}" />
        var customData;
        try{
            customData = eval("("+$(event.target).data('functionData')+")") || {};
        }catch (e){
            customData={};
        }
        //保存套打的自定义配置信息
        if(!$.isEmptyObject(customData.templateName)) {
            this.perfTemplateName = customData.templateName;
        }

        if(!$.isEmptyObject(customData.templateProvider)) {
            this.perfTemplateProvider = customData.templateProvider;
        }

        if(!$.isEmptyObject(customData.templateIdKey)) {
            this.perfTemplateIdKey = customData.templateIdKey;
        }

        if(!$.isEmptyObject(customData.templateIdSplitChar)) {
            this.perfTemplateIdSplitChar = customData.templateIdSplitChar;
        }

        shr.dormitorysystem.commonBatchListNew.superClass.templatePrintAction.call(this, event);

    },
    /**
     * 套打模板名称 重写此方法
     */
    getTemplateName : function() {
        return this.perfTemplateName;
    },

    /**
     * 套打dataProvider 重写此方法
     */
    getTemplateDataProvider : function() {
        return this.perfTemplateProvider;
    },

    /**
     * 套打query查询传入的id
     */
    getTemplatePrintId: function () {
        var billIds = this.getSelectedFields(this.perfTemplateIdKey);
        if (billIds && billIds.length > 0) {
            let splitChar = this.perfTemplateIdSplitChar;
            for(var i=0,len=billIds.length; i<len; i++) {
                //兼容下考核计划执行，列表id为 evaObjId$workflowId 拼接的方式
                billIds[i] = billIds[i].split(splitChar)[0];
            }
            return billIds.toString();
        }

        shr.showWarning({
            // message: jsBizMultLan.perfweb_evaluationTaskUnsendList_1586345713712_i18n_25
            message: $.shrI18n.common.tips.chooseTableDataFirst
        });
    },
});