/**
 * created by bijun_wang 2017.10.18
 */

(function ($) {
    $.widget("ui.cusDetailTips", {
        options: {
            tableData: [],
            successCount: "",
            failureCount: 0,
            isSortable: true,
            colNamesData: [],
            modalWidth: '700px',
            callback: null, //回调函数
            title: null,
            piece: null,
            colModels: []
        },

        $table: null,
        tableData: [],
        /**
         * 创建
         */
        _create: function () {
            this.element.attr("ctrlrole", this.widgetName);
        },
        /**
         * 打开
         */
        open: function () {
            var _self = this;
            shr.startMask(0.16);
            // 组装要显示的列
            var colNames = [];
            var colModel = [];
            var colModelTemp = this.options.colModels;
            for (var j = 0; j < colModelTemp.length; j++) {
                colModelTemp[j].sortable = _self.options.isSortable;
                if (colModelTemp[j].formatterForShowlink == 'showlink') {
                    colModelTemp[j].formatterForShowlink = '';
                }
                if (colModelTemp[j].editable) {
                    colModelTemp[j].editable = false;
                }
                colModelTemp[j].classes = '';
                colNames.push(colModelTemp[j].label);
                colModel.push(colModelTemp[j]);
            }
            this._initDOM();
            //var isOpen = this._initTable(_self._addStateAndRusultToGrid(colNames, colModel));
            var isOpen = this._initTable(colNames, colModel);
            if (!isOpen) { return; }
            shr.msgHideAll();
            var outZindex = $('#detailTipsCode:last').zIndex();
            if (window.jQuery && window.jQuery.ui.dialog) {
                $(document).unbind("focusin.dialog");
            }
            var innerZindex = $('#detailTipsCode:last').zIndex();
            var zindex = Math.max(outZindex, innerZindex);
            $('#detailTipsCode:last').css('z-index', ++zindex);
            $('#detailTipsCode').fadeIn().css('z-index', ++zindex);
            window.initDrag($('#detailTipsCode .modal-header').get(0), $('#detailTipsCode').get(0));
            setTimeout(function () {
                _self.setGridHeight(_self.$table);
            }, 0);
        },
        /**
         * 初始化元素
         */
        _initDOM: function () {
            var _self = this;
            var html = ['<div id="detailTipsCode" class="modal" style="width:${modalWidth}">',
                '<div class="self-dialog" style="width:auto">',
                '<div class="modal-content">',
                '<div class="modal-header">',
                '<button type="button" class="close" aria-hidden="true">×</button>',
                '<h4 class="modal-title">温馨提示&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
                '${title}',
                '<font class="failureCount"> ${failureCount} </font>${piece}',
                '，请确认后再提交</h4>',
                '</div>',
                '<div class="modal-body">',
                '<p></p>',
                '</div>',
                '<div class="modal-footer">',
                '<button id="confirm" type="button" class="shrbtn shrbtn-primary">确认</button>',
                '<button id="cancel" type="button" class="shrbtn">取消</button>',
                '</div>',
                '</div>',
                '</div>',
                '</div>'];
            html = html.join('');
            html = juicer(html, {
                //successCount: _self.options.successCount,
                title: _self.options.title,
                piece: _self.options.piece,
                failureCount: _self.options.failureCount,
                modalWidth: _self.options.modalWidth || '700px'
            });
            $("body").append(html);
            $("#detailTipsCode").attr('ctrlrole', _self.widgetName);
            this._addListener();//添加所有监听
        },

        /**
         * @method 在获取到的表格需要显示列的基础上增加状态和提示结果列
         * @param colNames:获取视图配置上需要显示列名称        colModel:列属性
         */
        _addStateAndRusultToGrid: function (colNames, colModel) {
            var _self = this;
            var colOptions;
            colNames.push($.shrI18n.widget.shrDetailTips.colNames.status);
            colNames.push($.shrI18n.widget.shrDetailTips.colNames.description);
            var stateObj = {
                name: 'muitTipsState',
                index: 'muitTipsState',
                label: $.shrI18n.widget.shrDetailTips.title.status,
                width: 50,
                align: "left",
                editable: false,
                sortable: _self.options.isSortable,
                formatter: _self.indexUnFormat
            };

            var messageObj = {
                name: 'muitTipsMessage',
                index: 'muitTipsMessage',
                label: $.shrI18n.widget.shrDetailTips.title.description,
                width: 450,
                align: "left",
                editable: false,
                sortable: _self.options.isSortable,
            };
            colModel.push(stateObj);
            colModel.push(messageObj);
            colOptions = {
                colNames: colNames,
                colModel: colModel,
            };

            return colOptions;
        },

        _initTable: function (colNames, colModel) {
            if (!this.options.tableData) {
                return false;
            }
            var _self = this;
            var $modal_body_p = $("div#detailTipsCode div.modal-body p");
            var pagerHtml = '<div class="shrPage span3" style="margin-left:30px;z-index:1;float:right;width:auto;position:relative;text-align:right;max-width:50% !important;">' +
                '<div id="gridPager2" class="gridPager" style="display:inline-block;"></div>' +
                '</div>';
            $modal_body_p.empty().append(pagerHtml);
            $modal_body_p.append('<table id="detailTipsCode-table"></table>');
            var $table = $modal_body_p.find('table#detailTipsCode-table');
            var dataGrid_option = {
                datatype: "local",
                height: 300,
                multiselect: false,
                caption: "",
                hasPager: true,
                autoWidth: true,
                viewrecords: true,
                rownumbers: true,
                rowNum: 50,
                customPager: '#gridPager2',
                rowList: [50, 100, 200],
                recordtext: '({0}-{1})/{2}',
                gridview: true,
                shrinkToFit: false,
                pginput: true,
                pagerpos: 'center',
                recordpos: 'left',
                pginputpos: 'right',
                colNames: colNames,
                colModel: colModel,
                gridComplete: function () {
                    var ids = $(this).jqGrid('getDataIDs');
                    for (var i = 0; i < ids.length; i++) {
                        $(this).editRow(ids[i]);
                    }
                },
            };
            dataGrid_option.loadComplete = function (ret) {
                _self.gridLoadComplete($table);
            };
            dataGrid_option.data = this.options.tableData;
            $table.jqGrid(dataGrid_option);

            this.$table = $table;
            return true;
        },

        gridLoadComplete: function ($grid) {
            var _self = this;
            if ($("#gridPager2").html() == "") {
                $grid.setCustomPager("#gridPager2");
            }
            shr.setIframeHeight();

            $('#gridPager2_left').click(function () {
                $('#gridPager2').find('.ui-pg-selbox').show();
                $(this).children('.ui-paging-info').hide();
            });
            setTimeout(function () {
                _self.setGridHeadWidth($grid);
            }, 100);
        },

        //如果有滚动条，设置表头的宽度要减去滚动条的宽度
        setGridHeadWidth: function ($grid) {
            if ($grid.length > 0) {
                var dom = $grid[0];
                var scrollHeight = dom.scrollHeight;
                var clientHeight = $('div#detailTipsCode div.modal-body p div.ui-jqgrid div.ui-jqgrid-view div.ui-jqgrid-bdiv').height();
                if (scrollHeight > clientHeight) {
                    var width = $grid.css('width');
                    $('div#detailTipsCode div.modal-body p div.ui-jqgrid div.ui-jqgrid-view div.ui-state-default div.ui-jqgrid-hbox table.ui-jqgrid-htable').css("cssText", "width:" + width + "!important;");
                }
            }
        },

        /**
         * 设置表格高度一直在可视高度
         * 
         */
        setGridHeight: function ($grid) {
            var gridBottom = 40;//表格下面留10px的空格
            var newGridHeight = $('#detailTipsCode').height() - $grid.offset().top - gridBottom;
            var gridHeight = $grid.height();
            if (gridHeight > newGridHeight) {
                if (newGridHeight > 340) {
                    $grid.jqGrid("setGridHeight", newGridHeight);
                } else {
                    $grid.jqGrid("setGridHeight", 340);
                }
                $grid.jqGrid("resizeGrid", { base: $grid, offset: 0 });
            }
        },

        indexUnFormat: function (cellValue, options, rowObject) {
            if (cellValue == $.shrI18n.widget.shrDetailTips.title.failure) {
                return '<font color="red">' + $.shrI18n.widget.shrDetailTips.title.failure + '</font>';
            } else {
                return '<font>' + $.shrI18n.widget.shrDetailTips.title.success + '</font>';
            }
        },

        _doAjax: function (options) {
            if (!options || !$.isPlainObject(options) || $.isEmptyObject(options)) {
                return;
            }
            $.ajax({
                "url": shr.getContextPath() + "/dynamic.do?method=" + options.whichAction,
                "type": "post",
                "async": true,
                "dataType": "JSON",
                "data": {
                    "uipk": shr.getUrlRequestParam('uipk'),
                    "data": JSON.stringify(options.data)
                },
                "success": function (data) {
                    if ($.isFunction(options.successCallback)) {
                        options.successCallback(data);
                    }
                },
                "error": function (data) {
                    if ($.isFunction(options.successCallback)) {
                        options.errorCallback(data);
                    }
                }
            });
        },

        _addListener: function () {
            var _self = this;
            $('div#detailTipsCode').on('click', 'button#confirm, button#cancel, button.close', function (event) {
                var id = $(this).attr('id');
                var className = $(this).attr('class');
                switch (id || className) {
                    case 'confirm':
                        _self.confirm();
                        break;
                    case 'cancel':
                        _self.close();
                        break;
                    case 'close':
                        _self.close();
                        break;
                    default:
                        break;
                }
            });
        },
        /**
         * 确认
         */
        confirm: function () {
            var _self = this;
            var callback = _self.options.callback;
            if (callback) {
                callback.call();
                _self.close();
            } else {
                _self.close();
            }
        },

        exportToExcel: function () {
            var _self = this;
            $('button#exportToExcel').blur();
            var datas = _self.options.tableData;
            var colModels = _self.$table.getGridParam('colModel');
            var excelDatas = [];
            var headerArr = [];
            $.each(colModels, function (index, colModel) {
                var headerObj = new Object();
                if (!colModel.label) {
                    headerObj['text'] = $.shrI18n.widget.shrDetailTips.title.number;
                } else {
                    headerObj['text'] = colModel.label;
                }
                headerArr.push(headerObj);
            });
            excelDatas.push(headerArr);
            $.each(datas, function (index, data) {
                var excelDataArr = [];
                $.each(colModels, function (i, colModel) {
                    var excelDataObj = new Object();
                    var property = colModel.name;
                    var value;
                    if (data.hasOwnProperty(property)) {
                        value = data[property];
                    } else {
                        if (property && property.indexOf('.') > -1) {
                            var propertyArr = property.split('.');
                            var realValue;
                            $.each(propertyArr, function (j, p) {
                                if (!realValue) {
                                    realValue = data[p];
                                } else {
                                    realValue = realValue[p];
                                }
                            });
                            value = realValue;
                        } else {
                            value = index + 1;
                        }
                    }
                    //添加空格的原因是为了防止导出结果，存在CSV注入漏洞，关联bug BT-00995665
                    if ($.isPlainObject(value)) {
                        if (value.isenum) {
                            excelDataObj['text'] = " " + value.alias;
                        }
                    } else {
                        excelDataObj['text'] = " " + value;
                    }
                    excelDataArr.push(excelDataObj);
                });
                excelDatas.push(excelDataArr);
            });
            var options = {
                "fileName": $.shrI18n.widget.shrDetailTips.title.fileName
            };
            var dataObject = [{
                "sheetName": $.shrI18n.widget.shrDetailTips.title.fileName,
                "data": excelDatas
            }];
            Jhxlsx.export(dataObject, options);
        },

        close: function () {
            shr.stopMask();
            $("#detailTipsCode").remove();
            this.options.tableData = [];
        },

        widget: function () {
            return this.element;
        },

        _setOption: function (key, value) {
            this._super(key, value);
            return this;
        },

        _setOptions: function (options) {
            var key;
            for (key in options) {
                this._setOption(key, options[key]);
            }
            return this;
        },

        destory: function () {
            $.Widget.prototype.destroy.call(this);
        }
    });
})(jQuery);