var mdmMetaDataGridManager = null, folderId = null, fullId, flag, refreshFlag = false, dictFolderName = null;
var dictFolderIds = '';
$(document).ready(function () {
        initUI();
        getUserDictFolderIds();
       // initializeTree();
        initMdmMetaDataListGrid();
    }
);


function initUI() {
    UICtrl.initDefaultLayout();
}

function initMdmMetaDataListGrid() {
    var toolbarOptions = [];
    toolbarOptions = UICtrl.getDefaultToolbarOptions({
            addHandler: addHandler,
            updateHandler: updateHandler,
            deleteHandler: deleteHandler,
            enableHandler: enableHandler,
            disableHandler: disableHandler,
            replicaMetaData: {
                id: 'replicaMetaData', img: 'fa-files-o', text: '复制', click: function () {
                    replicaMetaData();
                }
            },
        }
    );
    mdmMetaDataGridManager = UICtrl.grid('#mdmMetaDataGrid', {
            columns: [{
                display: "字段名称", name: "fieldName", width: "12%", minWidth: "60",align: "center",type: "string"}
            
                , {display: "字段CODE", name: "fieldCode", width: "10%", minWidth: "60", align: "center", type: "string"}
                //, {display: "字段显示名称", name: "fieldEngname", width: "10%", minWidth: "60", align: "center", type: "string"}
                , {display: "字段类型", name: "fieldDataTypeTextView",width: "12%",  minWidth: "60",  align: "center",type: "string"
                }
                , {display: "字段长度", name: "fieldLength", width: "10%", minWidth: "60", align: "center", type: "int"}
                , {display: "字段精度", name: "fieldDecimal", width: "10%", minWidth: "60", align: "center", type: "money"}
                , {display: '启用状态', name: 'status', width: "8%", minWidth: 60, align: "left",
                    render: function (item) {
                        return UICtrl.getStatusInfo(item.status);
                    }
                }
                , {display: "关联字典", name: "dictName", width: "10%", minWidth: "60", align: "center", type: "string"}
               // , {display: "字段注释", name: "fieldNotes", width: "14.0%", minWidth: "60", align: "center", type: "string"}
                , {display: "是否为空", name: "isNullTextView", width: "10%", minWidth: "60", align: "center", type: "string"}
            ],
            dataAction: 'server',
            url: web_app.name + '/metaData/slicedQueryMdmMetaData.ajax',
            toolbar: toolbarOptions,
            width: '99.8%',
            height: '100%',
            heightDiff: -4,
            sortName: 'id',
            sortOrder: 'asc',
            checkbox: true,
            usePager: true,
            rownumbers: false,
            enabledEdit: false,
            fixedCellHeight: true,
            selectRowButtonOnly: true,
            onDblClickRow: function (data, rowindex, rowobj) {
                doShowUpdateDialog(data.id);
            }
        }
    );
    UICtrl.setSearchAreaToggle(mdmMetaDataGridManager);
}

//刷新Gird方法;
function reloadMdmMetaDataGrid() {
    var params = $("#queryMainForm").formToJSON();
    UICtrl.gridSearch(mdmMetaDataGridManager, params);
}

function getId() {
    return $("#id").val() || "";
}

//增加方法
function addHandler() {

    UICtrl.showAjaxDialog({
            title: "添加元数据",
            param: {id: folderId},
            url: web_app.name + '/metaData/loadMdmMetaDataDetail.load',
            width: 800, height: 460,
            init: function () {
                initAddMdmMetaData(folderId);
            },
            ok: doSaveMdmMetaData,
            close: onDialogCloseHandler
        }
    );
}

function initAddMdmMetaData(folderId) {
    $('#codeRuleId').searchbox({
        type: 'saf',
        name: 'selectMetaCodeNames',
        getParam: function () {
            return {
                folderId: folderId
            };
        },
        back: {
            // metaName : '#codeRuleId',
            metaCode: '#codeRuleId',
        },
        onChange: function () {
        }
    });
    $('#dictName').searchbox({
        type: 'saf',
        name: 'selectDictNames',
        getParam: function () {
            return {
                folderId: dictFolderIds
            };
        },
        back: {
            // metaName : '#codeRuleId',
            dictCode: '#dictCode',
            dictName: '#dictName'
        },
        onChange: function () {
        }
    });

   

    var newBusinessName = $('#newBusinessName').val();
    $('#newBusinessDataName').searchbox({
        type: 'mdm',
        name: 'selectBusinessDataName',
        getParam: function () {
            return {
                folderId: folderId,
                newBusinessName: $('#newBusinessName').val(),
                oldBusinessId: $('#id').val(),
                newBusinessFullId: $('#newBusinessFullId').val(),
            };
        },
        back: {
            name: '#newBusinessDataName',
            id: '#newBusinessDataId'

        },
        onChange: function (value, data) {
            $('#newBusinessDataName').val(data.fullName + "/" + data.name)
            var newBusinessName = $('#newBusinessName').val();
            var newBusinessDataId = $('#newBusinessDataId').val
            if (Public.isNotBlank(data.id)) {
                UICtrl.gridSearch(existdataNewPlusGridManager, {"id": data.id, "newBusinessDataName": data.name})
            }
        }
    });
}

function getUserDictFolderIds() {

    var url = web_app.name + '/metaData/getUserDictFolderIds.ajax';
    Public.ajax(url, {}, function (data) {
        dictFolderIds = data.dictFolderIds;
    });
    //return dictFolderIds;
}


/*function getUserDictFolderName() {
    //var dictFolderName='';
    var url = web_app.name+'/mdmModelAttribute/getUserDictFolderName.ajax';
    Public.ajax(url,{},function (data) {
        dictFolderName=data.dictFolderName;
    });
    //return dictFolderName;
}*/


//保存方法 ;
function doSaveMdmMetaData() {
    var _self = this;
    var id = getId();
    var url = '/metaData/saveMdmMetaData.ajax';
    if ($('#fieldLength').val() < 1) {
        Public.tip("元数据字段长度必须大于1")
        return;
    }

    var fieldCode = $('#fieldCode').val();
    var regex = /^[a-z]+[a-z0-9_]*$/;
    var result = regex.test(fieldCode);
    if (result == false) {
        Public.tip("字段编码只能是小写英文，数字或下划线组成");
        $('#fieldCode').focus();
        return;
    }

    $('#mdmMetaDataForm').ajaxSubmit({
            url: web_app.name + url, success: function (data) {
                reloadMdmMetaDataGrid();
                refreshFlag = true;
                _self.close();
            }
        }
    );
}

//编辑方法
function updateHandler() {
    var row = UICtrl.checkSelectedRows(mdmMetaDataGridManager);
    if (row) {
        doShowUpdateDialog(row.id);
    }
}

function doShowUpdateDialog(id) {
    UICtrl.showAjaxDialog({
            title: "修改",
            url: web_app.name + '/metaData/updateMdmMetaData.load',
            param: {id: id},
            width: 900,
            init: function () {
                initAddMdmMetaData(folderId);
            },
            ok: doSaveMdmMetaData,
            close: onDialogCloseHandler
        }
    );
}

//删除数据方法;
function deleteHandler() {
    var row = UICtrl.checkSelectedRows(mdmMetaDataGridManager);
    var action = "/metaData/deleteMdmMetaDatas.ajax";
    DataUtil.delSelectedRows({
            action: action,
            idFieldName: 'id',
            gridManager: mdmMetaDataGridManager,
            onSuccess: reloadMdmMetaDataGrid
        }
    );
}

//启用
function enableHandler() {
    enableStatus('确实要启用选中数据吗?', 1);
}

function enableStatus(message, status) {
    var action = "/metaData/changeMdmMetaDataStatus.ajax";
    DataUtil.updateById({
        action: action,
        gridManager: mdmMetaDataGridManager,
        param: {status: status},
        message: message,
        onSuccess: function () {
            reloadMdmMetaDataGrid();
        }
    });
}

//禁用
function disableHandler() {
    enableStatus('确实要禁用选中数据吗?', 0);
}

//复制元数据
function replicaMetaData() {

    if (folderId == null || !flag) {
        Public.tip('请选择业务分类节点。');
        return;
    }
    UICtrl.showAjaxDialog({
            title: "复制元数据",
            param: {id: folderId},
            url: web_app.name + '/metaData/loadMdmMetaDataCopy.load',
            width: 800, height: 460,
            init: function () {
                initAddMdmMetaData(folderId);
            },
            ok: doSaveCopyMdmMetaData,
            close: onDialogCloseHandler
        }
    );

}

//查询方法;
function query(obj) {
    var param = $(obj).formToJSON();
    UICtrl.gridSearch(mdmMetaDataGridManager, param);
}

//重置表单;
function resetForm(obj) {
    $(obj).formClean();
}

function onDialogCloseHandler() {
    if (refreshFlag) {
        reloadMdmMetaDataGrid();
        refreshFlag = false;
    }
}

//保存方法 ;
function doSaveCopyMdmMetaData() {
    var _self = this;
    var newBusinessDataId = $('#newBusinessDataId').val
    var detailData = DataUtil.getGridData({
        gridManager: existdataNewPlusGridManager,
        isAllData: true,
        onCheck: function () {
            return true;
        }
    });
    var param = {detailData: encodeURI($.toJSON(detailData))}
    var copyUrl = '/metaData/saveCopyMdmMetaData.ajax';
    $('#mdmMetaDataCopyForm').ajaxSubmit({
            url: web_app.name + copyUrl,
            param: param,
            success: function (data) {
                refreshFlag = true;
                _self.close();
            }
        }
    );
}