
let el = {
    tb: '#tb',
    tt: '#tt',
    tb1: '#tb222',
    moldCode: '#moldCode',
    moldName: '#moldName',
    productCode: '#productCode',
    productName: '#productName',
    mgTbCounter: 0,
    sgTbCounter: 0,
    useState: '#useState',
    startDate: '#startDate',
    startTime: '#startTime',
    endDate: '#endDate',
    endTime: '#endTime',
}

$(function () {
    initDictName('moldform_status')
    initPageQuery();
    loadGrid();
});

/**
 * 初始化查询条件
 */
function initPageQuery() {
    $(el.tt).tabs({
        border: false,
        onSelect: function(title, index){
            if(el.mgTbCounter === 0 && el.sgTbCounter === 0){
                return false;
            }
            if(el.mgTbCounter === 0 || el.sgTbCounter === 0){
                dataQuery(index);
            }
        }
    });
}
function loadGrid() {
    $('#tb').datagrid({
        url: g.ctx + "pc/sys/mold/moldSettings/rest/list",
        iconCls: 'icon-list',
        title: '',
        height: gridheight-70,
        width: gridwidth,
        singleSelect: true,
        pagination: true,
        idField: 'id',
        autoHeight: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        fitColumns: false,
        remoteSort: true,
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'deleteFlag',
                title: '是否删除',
                width: '120px',
                align: 'left',
                formatter: function (value) {
                    switch (value) {
                        case "0":
                            return '<span>否</span>';
                        case "1":
                            return '<span style="color: red;">是</span>';
                    }
                }
            },
            {
                field: 'moldCode',
                title: '智微编码',
                width: '15%',
                align: 'left'

            },
            {
                field: 'supplierMouldNo',
                title: '供应商模号',
                width: '15%',
                align: 'left'

            },
            {
                field: 'moldName',
                title: '名称',
                width: '15%',
                align: 'left'

            },
            {
                field: 'useState',
                title: '使用状态',
                width: '100',
                align: 'left',
                exportEnum:getDictList('moldform_status'),
                formatter: function (value) {
                    return getDicName('moldform_status',value);
                }
            },
            {
                field: 'supplierCode',
                title: '制造商编码',
                width: '15%',
                align: 'left'
            },
            {
                field: 'supplierName',
                title: '制造商名称',
                width: '15%',
                align: 'left'
            },
            {
                field: 'productCode',
                title: '产品料号',
                width: '15%',
                align: 'left'
            },
            {
                field: 'productName',
                title: '产品描述',
                width: '15%',
                align: 'left'
            },
            {
                field: 'purchaseAmount',
                title: '产品数量',
                width: '15%',
                align: 'left'
            },
            // {
            //     field: 'dosage',
            //     title: '单次产出数量',
            //     width: '15%',
            //     align: 'left'
            // },
            {
                field: 'note',
                title: '备注',
                width: '15%',
                align: 'left'
            },
            {
                field: 'attachment',
                title: '附件',
                width: '15%',
                align: 'left',
                // formatter: function (value, row ,rec) {
                //     var sty = "";
                //     if (!row.attachment) {
                //         sty = "color: #0C0C0C";
                //     }
                //     return '<a href="#" style="' + sty + '" onclick="uploadFilesDialog(\'' + row.attachment + '\')">上传/下载</a>';
                // }
                formatter: function (value, row ,rec) {
                    //var row = $("#tb").datagrid("getChecked");

                    var sty = "";
                    if (!row.attachment) {
                        sty = "color: #0C0C0C";
                    }
                    var fileIds = row.attachment
                    var id = row.id
                    return '<a href="#" style="' + sty + '" onclick="onSiteAuthenticationFilesLookupDialog(\'' + id + '\',\'' + fileIds + '\')">上传/下载</a>';
                }
            },
            {
                field: 'createrName',
                title: '创建人',
                width: '15%',
                align: 'left'
            },
            {
                field: 'createTime',
                title: '创建日期',
                width: '15%',
                align: 'left',
                formatter: function (value, row, index) {
                    return DateFormatMs(value);
                }

            }
        ]],
        toolbar: ["-", {
            text: '新增',
            id: 'add',
            iconCls: 'icon-add',
            hidden: true,
            handler: function () {
                addOrEdit(0);
            }
        }, "-", {
            text: '编辑',
            id: 'edit',
            iconCls: 'icon-edit',
            handler: function () {
                addOrEdit(1);
                setOperationLog("编辑按钮", "摸具与产品关联");
            }
        }, "-", {
            text: '删除',
            id: 'delete',
            hide: true,
            iconCls: 'icon-remove',
            handler: function () {
                delFactory();
            }
        },"-", {
            text: '查看',
            id: 'look',
            hide: true,
            iconCls: 'icon-ok',
            handler: function () {
                look();
                setOperationLog("查看按钮", "摸具与产品关联");
            }
        },"-", {
            text: '导出',
            id: 'export',
            hide: true,
            iconCls: 'icon-reload',
            handler: function () {
                var params = searchParams();
                openExportDialog('pc/sys/mold/moldSettings/rest/export','tb',params);
                setOperationLog("导出按钮", "摸具与产品关联");
            }
        }
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole("Mold Settings");
            autoMergeCells();
            loadGrid2();
            $(el.tb).datagrid('clearSelections');
        },
    });
}


function loadGrid2() {
    $(el.tb1).datagrid({
        url: g.ctx + "pc/sys/mold/moldSettings/rest/list",
        iconCls: 'icon-list',
        title: '',
        height: gridheight-70,
        width: gridwidth,
        singleSelect: true,
        pagination: true,
        idField: 'id',
        autoHeight: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        fitColumns: false,
        remoteSort: true,
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'deleteFlag',
                title: '是否删除',
                width: '120px',
                align: 'left',
                formatter: function (value) {
                    switch (value) {
                        case "0":
                            return '<span>否</span>';
                        case "1":
                            return '<span style="color: red;">是</span>';
                    }
                }
            },
            {
                field: 'productCode',
                title: '产品料号',
                width: '15%',
                align: 'left'
            },
            {
                field: 'productName',
                title: '产品描述',
                width: '15%',
                align: 'left'
            },
            {
                field: 'moldCode',
                title: '模具编码',
                width: '15%',
                align: 'left'

            },
            {
                field: 'moldName',
                title: '名称',
                width: '15%',
                align: 'left'

            },
            {
                field: 'useState',
                title: '使用状态',
                width: '100',
                align: 'left',
                exportEnum:getDictList('moldform_status'),
                formatter: function (value) {
                    return getDicName('moldform_status',value);
                }
            },
            {
                field: 'supplierCode',
                title: '制造商编码',
                width: '15%',
                align: 'left'
            },
            {
                field: 'supplierName',
                title: '制造商名称',
                width: '15%',
                align: 'left'
            },
            {
                field: 'purchaseAmount',
                title: '产品数量',
                width: '15%',
                align: 'left'
            },
            // {
            //     field: 'dosage',
            //     title: '单次产出数量',
            //     width: '15%',
            //     align: 'left'
            // },
            {
                field: 'note',
                title: '备注',
                width: '15%',
                align: 'left'
            },
            {
                field: 'attachment',
                title: '附件',
                width: '15%',
                align: 'left',
                // formatter: function (value, row ,rec) {
                //     var sty = "";
                //     if (!row.attachment) {
                //         sty = "color: #0C0C0C";
                //     }
                //     return '<a href="#" style="' + sty + '" onclick="uploadFilesDialog(\'' + row.attachment + '\')">上传/下载</a>';
                // }
                formatter: function (value, row ,rec) {
                    //var row = $("#tb").datagrid("getChecked");

                    var sty = "";
                    if (!row.attachment) {
                        sty = "color: #0C0C0C";
                    }
                    var fileIds = row.attachment
                    var id = row.id
                    return '<a href="#" style="' + sty + '" onclick="onSiteAuthenticationFilesLookupDialog(\'' + id + '\',\'' + fileIds + '\')">上传/下载</a>';
                }
            },
            {
                field: 'createrName',
                title: '创建人',
                width: '15%',
                align: 'left'
            },
            {
                field: 'createTime',
                title: '创建日期',
                width: '15%',
                align: 'left',
                formatter: function (value, row, index) {
                    return DateFormatMs(value);
                }

            }
        ]],
        toolbar: ["-", {
            text: '新增',
            id: 'add',
            iconCls: 'icon-add',
            hidden: true,
            handler: function () {
                addOrEdit(0);
            }
        }, "-", {
            text: '编辑',
            id: 'edit',
            iconCls: 'icon-edit',
            handler: function () {
                addOrEdit(1);
            }
        }, "-", {
            text: '删除',
            id: 'delete',
            hide: true,
            iconCls: 'icon-remove',
            handler: function () {
                delFactory();
            }
        },"-", {
            text: '查看',
            id: 'look',
            hide: true,
            iconCls: 'icon-ok',
            handler: function () {
                look();
            }
        },"-", {
            text: '导出',
            id: 'export',
            hide: true,
            iconCls: 'icon-reload',
            handler: function () {
                var params = searchParams();
                openExportDialog('pc/sys/mold/moldSettings/rest/export','tb',params);
            }
        }
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole("Mold Settings");
            autoMergeCells1();
            $(el.tb1).datagrid('clearSelections');
        },
    });
}

/**
 * 数据查询
 *
 * @param tabIndex tab索引
 */
function dataQuery(tabIndex) {
    var queryParams = {};
    queryParams.moldCode = $(el.moldCode).textbox('getValue');
    queryParams.moldName = $(el.moldName).textbox('getValue');
    queryParams.productCode = $(el.productCode).textbox('getValue');
    queryParams.productName = $(el.productName).textbox('getValue');
    // queryParams.startDate = $(el.startDate).datebox('getValue');
    // queryParams.endDate = $(el.endDate).datebox('getValue');
    // queryParams.startDate = $.trim($(el.startDate).val());
    // queryParams.endDate = $.trim($(el.endDate).val());
    queryParams.startTime = $(el.startTime).datebox('getValue');
    queryParams.endTime = $(el.endTime).datebox('getValue');
    // queryParams.expireDate = moment(expireDate).format('YYYY-MM-DD');

    if(tabIndex === -1){
        $(el.tt).tabs('getSelected');
        var choseTab = $(el.tt).tabs('getSelected');
        tabIndex = $(el.tt).tabs('getTabIndex', choseTab);
    }
    if(tabIndex === 0){
        $("#tb").datagrid('options').queryParams = queryParams;
        $("#tb").datagrid('load');
        el.mgTbCounter = 1;
    }else {
        $("#tb222").datagrid('options').queryParams = queryParams;
        $("#tb222").datagrid('load');
        el.sgTbCounter = 1;
    }
}
/**
 * 重置查询条件
 */
function resetQuery(tabIndex) {
    $(el.moldCode).textbox('setValue', '');
    $(el.moldName).textbox('setValue', '');
    $(el.productCode).textbox('setValue', '');
    $(el.productName).textbox('setValue', '');
    $(el.startTime).datebox('setValue', '');
    $(el.endTime).datebox('setValue', '');
    // $(el.expireDate).datebox('setValue', moment().format('YYYY-MM-DD'));

    var queryParams = {};
    queryParams.moldCode = $(el.moldCode).textbox('getValue');
    queryParams.moldName = $(el.moldName).textbox('getValue');
    queryParams.productCode = $(el.productCode).textbox('getValue');
    queryParams.productName = $(el.productName).textbox('getValue');
    queryParams.startTime = $(el.startTime).datebox('getValue');
    queryParams.endTime = $(el.endTime).datebox('getValue');
    // queryParams.expireDate = moment().format('YYYY-MM-DD');

    if(tabIndex === -1){
        $(el.tt).tabs('getSelected');
        var choseTab = $(el.tt).tabs('getSelected');
        tabIndex = $(el.tt).tabs('getTabIndex', choseTab);
    }
    if(tabIndex === 0){
        $("#tb").datagrid('options').queryParams = queryParams;
        $("#tb").datagrid('load');
        el.mgTbCounter = 1;
    }else {
        $("#tb222").datagrid('options').queryParams = queryParams;
        $("#tb222").datagrid('load');
        el.sgTbCounter = 1;
    }
}

function onSiteAuthenticationFilesLookupDialog (id, fileIds) {
    const uploadOptions = {
        title: '模具产品关联附件上传',
        fileIds: fileIds
    }
    if (id != undefined) {
        uploadOptions.callBack = function (fileIds) {
            $.ajax({
                url: g.ctx + 'pc/sys/mold/moldSettings/rest/saveOnFile',
                method: "POST",
                data: {fileIds: fileIds.join(','), id: id},
                success: function (data) {
                    topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                        $("#tb").datagrid("reload")
                        topWin.layer.close(idx);
                    });
                },
                error: function (data) {
                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                }
            });
        }
    }
    openFileUploadDialog("模具产品关联附件上传", uploadOptions)
}

/**
 * 单元格合并
 **/
function autoMergeCells() {
    // tableDom 表格HTML中DOM; judge 判断条件
    var judge = 'moldCode';
    // field_arr 需要合并的列
    var field_arr = ['moldCode', 'moldName','supplierCode','supplierName','supplierMouldNo'];
    var rows = $(el.tb).datagrid('getRows');
    if (NULL(field_arr) || NULL(rows)) {
        return;
    }
    for (var i = 1; i < rows.length; i++) {
        for (var k = 0; k < field_arr.length; k++) {
            // 要排序的字段
            var field = field_arr[k];
            // 相邻的上下两行
            if (rows[i][field] === rows[i - 1][field]) {
                if (NOTNULL(judge)) {
                    if (rows[i][judge] !== rows[i - 1][judge]) {
                        continue;
                    }
                }
                var rowSpan = 2;
                // 判断上下多行内容一样
                for (var j = 2; i - j >= 0; j++) {
                    if (rows[i][field] !== rows[i - j][field]) {
                        break;
                    } else {
                        if (NOTNULL(judge)) {
                            if (rows[i][judge] !== rows[i - j][judge]) {
                                break;
                            }
                        }
                        rowSpan = j + 1;
                    }
                }
                // 合并
                $(el.tb).datagrid('mergeCells', {
                    index: i - rowSpan + 1,
                    field: field,
                    rowspan: rowSpan
                });
            }
        }
    }
}
/**
 * 单元格合并
 **/
function autoMergeCells1() {
    // tableDom 表格HTML中DOM; judge 判断条件
    var judge = 'productCode';
    // field_arr 需要合并的列
    var field_arr = ['productCode', 'productName'];
    var rows = $(el.tb).datagrid('getRows');
    if (NULL(field_arr) || NULL(rows)) {
        return;
    }
    for (var i = 1; i < rows.length; i++) {
        for (var k = 0; k < field_arr.length; k++) {
            // 要排序的字段
            var field = field_arr[k];
            // 相邻的上下两行
            if (rows[i][field] === rows[i - 1][field]) {
                if (NOTNULL(judge)) {
                    if (rows[i][judge] !== rows[i - 1][judge]) {
                        continue;
                    }
                }
                var rowSpan = 2;
                // 判断上下多行内容一样
                for (var j = 2; i - j >= 0; j++) {
                    if (rows[i][field] !== rows[i - j][field]) {
                        break;
                    } else {
                        if (NOTNULL(judge)) {
                            if (rows[i][judge] !== rows[i - j][judge]) {
                                break;
                            }
                        }
                        rowSpan = j + 1;
                    }
                }
                // 合并
                $(el.tb).datagrid('mergeCells', {
                    index: i - rowSpan + 1,
                    field: field,
                    rowspan: rowSpan
                });
            }
        }
    }
}
/**
 * 附件上传
 **/
function uploadFilesDialog(val){

    openFileUploadDialog('uploadFilesDialog',{
        title:'附件上传',
        fileIds : val,
        lookFlag: false,
        height: '75%',
        callBack : function (fileIds) {
            returnAddRequirefileUpload(fileIds.join(','))
        },
    });
}
function returnAddRequirefileUpload(ids) {

    var rows = $('#tb').datagrid('getSelected');
    var inx = $('#tb').datagrid('getRowIndex', rows);
    $('#tb').datagrid('endEdit', inx);
    $('#tb').datagrid('updateRow', {
        index: inx,
        row: {
            attachment: ids
        }
    })}
function addOrEdit(flag) {
    var id= '';
    if(flag===1){
        var cbox = $('#tb').datagrid('getSelected');
        if (cbox === null || cbox === undefined) {
            layer.msg("请选中一条记录");
            return;
        }
        if (cbox.deleteFlag != 0 ) {
            layer.msg("只有未删除状态数据才可编辑");
            return;
        }
        id = cbox.id;
    }
    var moldSettingsDialog = openDialog('moldSettings', g.ctx + 'pc/sys/mold/moldSettings/detail?id=' + id, {
        title: flag===0?'新增':'编辑',
        width: '700px',
        height: '520px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            moldSettingsDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.save,
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['moldSettings'].saveOrUpdate(function () {
                        topWin.layer.msg('数据保存成功', {icon: 1});
                        moldSettingsDialog.dialog('close');
                        $(el.tb).datagrid('reload');
                    });
                }
            },
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    moldSettingsDialog.dialog('close');
                }
            }
        ]
    });
}
function look(flag) {
    var id= '';
        var cbox = $('#tb').datagrid('getSelected');
        if (cbox === null || cbox === undefined) {
            layer.msg("请选中一条记录");
            return;
        }
        id = cbox.id;

    var moldSettingsDialog = openDialog('moldSettings', g.ctx + 'pc/sys/mold/moldSettings/look?id=' + id, {
        title: '查看',
        width: '700px',
        height: '520px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            moldSettingsDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.close,
                iconCls: 'icon-cancel',
                handler: function () {
                    moldSettingsDialog.dialog('close');
                }
            }
        ]
    });
}

function delFactory() {
    var cbox = $('#tb').datagrid('getSelected');
    if (cbox === null || cbox === undefined) {
        layer.msg("请选中一条记录");
        return;
    }
    if (cbox.deleteFlag != 0 ) {
        layer.msg("只有未删除状态数据才可删除");
        return;
    }
    var moldSettings = cbox.productCode;

    parent.layer.confirm('是否删除？', function (index) {
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        var url = g.ctx + 'pc/sys/mold/moldSettings/rest/remove';
        $.ajax({
            url: url,
            method: "post",
            data: {productCode: moldSettings},
            success: function (data) {
                parent.layer.close(index);
                $(el.tb).datagrid('reload');
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                layer.close(index);
                layer.alert(JSON.parse(data.responseText).message);
            }
        });
    });
}
/**
 * 判断字符串不为空
 *
 * @return {boolean}
 */
function NOTNULL(obj) {
    return !(typeof (obj) === 'undefined' || obj === '' || obj == null || obj === 'null');

}


/**
 * 判断字符串为空
 *
 * @return {boolean}
 */
function NULL(obj) {
    return typeof (obj) === 'undefined' || obj === '' || obj == null || obj === 'null';

}