var el = {
    form : '#form',
    attachment: '#attachment',
    qualityNotice: '#qualityNotice',
    emptyTd: '.empty-td',
    qualityNoticeData: '.quality_notice_data',
    qualityNoticeCode: '#qualityNoticeCode',
    suppllierName: '#suppllierName',
    badReason: '#badReason',
    problemSource: '#problemSource',
    defectiveBatches: '#defectiveBatches',
    refuseMerge: '#refuseMerge',
    userIdMap: {},
}


/**
 * 初始化页面特殊输入框
 */
$(function () {
    // 初始化不合格原因下拉框
    $(el.badReason).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=reasons_for_nonconformity',
        panelHeight: 260,
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
    // 初始化不良批次处理意向下拉框
    $("#defectiveBatches").combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=defective_batches',
        panelHeight: 'auto',
        method: 'GET',
        value: $(".defectiveBatches").val(),
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false,
        onSelect: function (record) {
            if (record.dicId == 2){
                $('.visiting_tr').show();
                $('.visiting_span').next().show();

            }else {
                $('.visiting_tr').hide();
                $('.visiting_span').next().hide();
            }
        }

    });
    $('.visiting_tr').hide();
    $('.visiting_span').next().hide();
    $('.handle_tr').hide();
    // 初始化问题类型下拉框
    $(el.problemSource).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=problem_source',
        panelHeight: 260,
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
    // 初始化公司下拉框
    $('#companyCode').combobox({
        valueField: 'companyCode',
        textField: 'dataPrimary',
        url: g.ctx + 'pc/sys/company/rest/listAll',
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 300,
        onSelect:function (data) {
            $('#companyName').textbox('setValue',data.companyName);
        }
    });
   // loadGrid();
    initDetailGrid()
});
//是否受理加载不良批次处理意向
$(".supAgreeRma").click(function () {
    var sup_agree_rma = $("input[name='supAgreeRma']:checked").val();
    if (sup_agree_rma == 1){
        $("#supDisagreeExplain").textbox({disabled:true})
        $('#agreeMerge').removeAttr('disabled');
        $(".sup_disagree_explain_tr").show();
    }else {
        $("#supDisagreeExplain").textbox({disabled:false});
        // $("#emergency_handling").combobox({disabled:'disabled'});
        $('#agreeMerge').attr('disabled','disabled');
        $('#agreeMerge').removeAttr('checked');
        $('#refuseMerge').prop("checked", "checked");
        $(".mergeList").hide();
        $(".sup_disagree_explain_tr").hide();
    }
});


/**
 * 加载明细表格
 */
function initDetailGrid() {
    var defaults = {
        // loadMsg: '数据远程载入中,请等待...',
        loadMsg: suplierModel.loadData,
        singleSelect: true,
        pagination: false,
        //url :  g.ctx + 'pc/spe/supQualityManage/qualityHandle/rest/findRectifiedByPage',
        checkbox: true,
        rownumbers: true,
        width: gridwidth,
        autoSave: true,
        queryParams: {
            page: 1,
            rows: 10,
            id: $("#id").val(),
            merge_flag: $("#merge_flag").val()
        }
    };
    defaults.toolbar = [
        {
            // text: '添加',
            text: buttonI18n.addTJ,
            iconCls: 'icon-add',
            handler: function () {
                addMeasures($("#id").val());
            }
        }, "-",
        {
            // text: '删除',
            text: buttonI18n.delete,
            iconCls: 'icon-remove',
            handler: function () {
                removeMeasures();
            }
        }
    ];
    columns = [
        {
            field: 'ck',
            checkbox: true
        },
        {
            field: 'id',
            hidden: true
        },
        {
            field: 'noticeOrderId',
            hidden: true
        },
        {
            field: 'measuresContent',
            // title: '<font color="red">*</font>处理措施',
            title: '<font color="red">*</font>'+suplierModel.measures_content,
            width: 290,
            editor: {
                type: 'textbox',
                options: {
                    // prompt: '请输入整改措施'
                    prompt: suplierModel.measures_content_placeholder
                }
            }
        },
        {
            field: 'personLiable',
            // title: '<font color="red">*</font>责任人',
            title: '<font color="red">*</font>'+suplierModel.person_liable,
            width: 130,
            editor: {
                type: 'textbox',
                options: {
                    // prompt: '请输入整改责任人'
                    prompt: suplierModel.person_liable_placeholder
                }
            }
        },
        {
            field: 'planCompleteTime',
            // title: '<font color="red">*</font>计划时间',
            title: '<font color="red">*</font>'+suplierModel.plan_complete_time,
            width: 130,
            formatter: function (value) {
                if (value) {
                    return moment(value).format('YYYY-MM-DD HH:mm:ss');
                }
                return '';
            },
            editor: {
                type: 'datetimebox', options: {
                    onSelect: function (d) {
                    },
                    panelWidth:'160',
                    panelHeight:'250',
                    editable: false
                }
            }
        },
        {
            field: 'attachments', title: suplierModel.attachments, width: 100, formatter: function (value, row ,rec) {
                return '<a href="#" onclick="uploadFilesDialog(\''+value+'\')">上传/下载</a>';
            }
        },
        {
            field: 'actualCompleteTime',
            // title: '完成时间',
            title: suplierModel.actual_complete_time,
            width: 130,
            formatter: function (value) {
                if (value) {
                    return moment(value).format('YYYY-MM-DD HH:mm:ss');
                }
                return '';
            }
        },
        {
            field: 'status',
            // title: '状态',
            title: materiaTable.status,
            width: 90,
            formatter: function (value) {
                if (value === 0) {
                    return 'open';
                }
                if (value === 1) {
                    return 'close';
                }
            }
        }
    ];
    defaults.columns = [columns];

    var settings = jQuery.extend(true, {}, defaults);
    $("#detail_table").edatagrid(settings);
}
/**
 * 添加整改措施
 */
function addMeasures(notice_order_id) {
    // 新增一个带默认值的行
    $("#detail_table").edatagrid('addRow', {
        id: '',
        noticeOrderId: notice_order_id,
        measuresContent: '',
        personLiable: '',
        attachments: '',
        planCompleteTime: '',
        actualCompleteTime: '',
        status: 0
    });
}
//确认提交
function improveRelease(callback) {
    var allRows = $('#detail_table').datagrid('getRows');
    for (var i = 0; i < allRows.length; i++) {
        $('#detail_table').datagrid('endEdit', i);
    }

    var id = $("#id").val();
    var attachmentRam = $('#attachmentRam').val();
    var merge_flag = $("#mergeFlag").val();
    var sup_flow_out_reason = $("#supFlowOutReason").val();
    if (!sup_flow_out_reason) {
        // layer.msg("请输入流出原因");
        layer.msg(suplierModel.enterReason1);
        return false;
    }
    var sup_deliver_reason = $("#supDeliverReason").val();
    if (!sup_deliver_reason) {
        // layer.msg("请输入发生原因");
        layer.msg(suplierModel.enterReason2);
        return false;
    }
    var source = $("#source").val();
    var rootCause_classify = "";
    if (source == 1) {
        rootCause_classify = $("#rootCause_classify").val()
    }
    var rows = $("#detail_table").edatagrid('getRows');
    if (rows.length == 0) {
        // layer.msg("请添加纠正与预防措施");
        layer.msg(suplierModel.msg25);
        return false;
    }
    for (var i = 0; i < rows.length; i++) {
        var flag = false;
        var msg = "";
        if (!rows[i].measuresContent) {
            // msg = "预防措施第" + (i + 1) + "行，" + "处理措施" + "不能为空";
            msg =  suplierModel.msg26+ (i + 1) + suplierModel.line +","+ suplierModel.measures_content + suplierModel.cannot_empty;
            layer.msg(msg, {time: 2000});
            flag = true;
            return false;
        }
        if (!rows[i].personLiable) {
            // msg = "预防措施第" + (i + 1) + "行，" + "责任人" + "不能为空";
            msg =suplierModel.msg26 + (i + 1) + suplierModel.line +","+ suplierModel.person_liable + suplierModel.cannot_empty;
            layer.msg(msg, {time: 2000});
            flag = true;
            return false;
        }
        if (!rows[i].planCompleteTime) {
            // msg = "预防措施第" + (i + 1) + "行，" + "计划时间" + "不能为空";
            msg = suplierModel.msg26 + (i + 1) + suplierModel.line +","+ suplierModel.plan_complete_time + suplierModel.cannot_empty;
            layer.msg(msg, {time: 2000});
            flag = true;
            return false;
        }
    }
    // if (!attachmentRam) {
    //     // layer.msg("请上传RMA或8D报告附件");
    //     layer.msg(suplierModel.uploadRAM);
    //     return false;
    // }
    var bad_num = "";
    var final_bad_rate = "";
    var final_bad_describe = "";
    //var url = "/supplierQuality/improve.do";
    var url = "/pc/spe/supQualityManage/qualityHandle/rest/improveSave";
    $.ajax({
        url: url,
        method: "post",
        contentType: 'application/json',
        data: JSON.stringify({
            id:id,
            mergeFlag:merge_flag,
            supFlowOutReason:sup_flow_out_reason,
            supDeliverReason:sup_deliver_reason,
            //rootCauseClassify:rootCause_classify,
            attachmentRam:attachmentRam,
            //rows:JSON.stringify(rows),
            rows:rows,
            //finalBadNumber:finalBadNumber,
            badNum:bad_num,
            finalBadRate:final_bad_rate,
            finalBadDescribe:final_bad_describe
        }),
        success: function (data) {
            if (data) {
                layer.alert(commonTxt.operateSuccess, function (index) {
                    layer.alert(commonTxt.review_success);
                    callback();
                    return false;
                });
            } else {
                layer.alert(claimModel.opt_fail_msg);
            }
        },
        error: function (data) {
            layer.alert(claimModel.opt_fail_msg);
        }
    });
}

/**
 * 删除整改措施
 */
function removeMeasures() {
    var rows = $("#detail_table").edatagrid('getSelections');
    if (rows.length === 0) {
        // topWin.layer.msg('请选中记录进行操作');
        topWin.layer.msg(suplierModel.selectone);
        return false;
    }
    var ids = [];
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].id){
            ids.push(rows[i].id);
        }
    }
    if (ids.length==0){
        for (var i = 0; i < rows.length; i++) {
            var rowIndex = $("#detail_table").datagrid('getRowIndex', rows[i]);
            $("#detail_table").datagrid('updateRow', {
                index: rowIndex,
                row: {noticeOrderId: -1}
            });
            $("#detail_table").datagrid('deleteRow', rowIndex);
        }
    }else {
        var url = "/pc/spe/supQualityManage/qualityHandle/rest/removeMeasures";
        $.ajax({
            url: url,
            method: "post",
            data: {ids:ids.join(',')},
            success: function (data) {
                if (data == 0) {
                    for (var i = 0; i < rows.length; i++) {
                        var rowIndex = $("#detail_table").datagrid('getRowIndex', rows[i]);
                        $("#detail_table").datagrid('updateRow', {
                            index: rowIndex,
                            row: {noticeOrderId: -1}
                        });
                        $("#detail_table").datagrid('deleteRow', rowIndex);
                    }
                } else {
                    layer.alert(claimModel.opt_fail_msg);
                }
            },
            error: function (data) {
                layer.alert(claimModel.opt_fail_msg);
            }
        });
    }

}

function searchSupplier(){
    var userOrgyDialog = openDialog('userOrgyDialog', g.ctx + 'pc/supplier/supplierSelect?single=1', {
        title: "选择供应商",
        width: '800px',
        height: '500px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userOrgyDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.confirm,
                handler: function () {
                    topWin.frames['userOrgyDialog'].chooseRow(function (cbox) {console.log(cbox)
                        $("#supplierId").val(cbox.id);
                        $('#supplierCode').textbox('setValue', cbox.supplierCode);
                        $('#supplierName').textbox('setValue', cbox.supplierName);
                        userOrgyDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                handler: function () {
                    userOrgyDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 选择物料页面
 */
function selectMaterial() {
    var selectMaterialElement = openDialog("selectMaterialDialog", g.ctx + 'pc/sys/product/select/dialog?single=1', {
        title: '选择物料',
        width: '80%',
        height: '75%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            selectMaterialElement.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.confirm,
                handler: function () {
                    topWin.frames['selectMaterialDialog'].chooseRows(function (cbox) {console.log(cbox)
                        //$("#supplierId").val(cbox.id);
                        $("#materialCode").textbox('setValue',cbox.materialCode);
                        $('#materialName').textbox('setValue',cbox.materialName);
                        selectMaterialElement.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                handler: function () {
                    selectMaterialElement.dialog('close');
                }
            }
        ]


    });
}

/**
 * 选择部门
 */
function doSearch() {
    var userOrgyDialog = openDialog('userOrgyDialog', g.ctx + 'pc/sys/org/orgTree', {
        title: "组织部门",
        width: '400px',
        height: '700px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userOrgyDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.save,
                handler: function () {
                    topWin.frames['userOrgyDialog'].confirm(function (cbox) {
                        $("#materialUseDeptCode").val(cbox.code);
                        $('#materialUseDeptName').textbox('setValue', cbox.name);
                        // setOrgValue(cbox.id, cbox.name, cbox.code);
                        userOrgyDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                handler: function () {
                    userOrgyDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 选择用户
 */
function userSearch () {
    var userDialogElement = openDialog("userDialog", g.ctx + "pc/sys/user/index?select=1&single=0", {
        title: "用户选择",
        width: '80%',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userDialogElement.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save,
            handler: function () {
                topWin.frames['userDialog'].chooseRow(function (rows) {
                    //数组得用rows[0]
                    $('#mqeMceName').textbox('setValue', rows[0].username);
                    userDialogElement.dialog('close');
                });
            }
        }, {
            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                userDialogElement.dialog('close');
            }
        }]
    })
}
/**
 * 附件上传
 **/
function uploadFilesDialog(val){

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

// 选择附件回调
function returnAddRequirefileUpload(ids) {

    var rows = $('#detail_table').datagrid('getSelected');
    var inx = $('#detail_table').datagrid('getRowIndex', rows);
    $('#detail_table').datagrid('endEdit', inx);
    $('#detail_table').datagrid('updateRow', {
        index: inx,
        row: {
            attachments: ids
        }
    })}