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',
    attachments: '#attachments',
    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
    });
    // 初始化不良批次处理意向下拉框
    // $(el.defectiveBatches).combobox({
    //     url: g.ctx + 'pc/sys/dict/getDicByType?type=defective_batches',
    //     panelHeight: 'auto',
    //     method: 'GET',
    //     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
    });

});
//是否受理加载不良批次处理意向
// $(".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 loadGrid() {
//     $('#merge_table').datagrid({
//         //loadMsg: '数据远程载入中,请等待...',
//         loadMsg:suplierModel.msg11,
//         singleSelect: true,
//         pagination: false,
//         checkbox: true,
//         rownumbers: true,
//         fitColumns: true,
//         idFiled: "id",
//         // height: gridheight,
//         width: gridwidth,
//         onLoadSuccess:function(){
//         },
//         columns : [[
//             {
//                 field : 'ck',
//                 checkbox : true
//             },
//             {
//                 field : 'id',
//                 title : 'id',
//                 hidden :true
//             },
//             {
//                 field : 'noticeOrderCode',
//                 // title : '流水号',
//                 title : suplierModel.serialNumber,
//                 width : '15%',
//                 align : 'left'
//
//             },
//             {
//                 field : 'materialName',
//                 // title : '物料名称',
//                 title : materiaTable.materialName,
//                 width : '25%',
//                 align : 'left'
//             },
//             {
//                 field : 'badReason',
//                 // title : '不合格原因',
//                 title : suplierModel.unqualifiedReason,
//                 width : '25%',
//                 align : 'left'
//             },
//             {
//                 field : 'badRemark',
//                 // title : '不合格描述',
//                 title : suplierModel.unqualified_des,
//                 width : '30%',
//                 align : 'left'
//
//             }
//         ]],
//         toolbar : [
//             {
//                 // text : '新增',
//                 text : buttonI18n.add,
//                 iconCls : 'icon-add',
//                 handler : function() {
//                     addMerge();
//                 }
//             },
//             "-",  {
//                 // text : '删除',
//                 text :buttonI18n.delete,
//                 iconCls : 'icon-remove',
//                 handler : function() {
//                     deleteQuality();
//                 }
//             }
//         ],
//         onCheck:function (rowIndex, field, value) {
//
//         },
//         onClickCell: function (rowIndex, field, value) {
//         }
//     });
// }

//确认提交
function examineRelease(callback) {
    if($(el.form).form('validate')){
    var source = $("#source").val();
    var sup_agree_rma = $("input[name='supAgreeRma']:checked").val();
    console.log(source)
    if (sup_agree_rma == 1){
        if (source == 2){
            // if(!$("#defective_batches")){
            var defective_batches = $("#defectiveBatches").textbox('getValue');
            // }
            var visiting_name = $("#visitingName").val();
            var visiting_call = $("#visitingCall").val();
            var visiting_time = $("#visitingTime").val();
            if (!defective_batches){
                //layer.msg("请选择不良批次处理意向");
                layer.msg(suplierModel.msg12)
                return false;
            }


            var emergency_handling = 0;
            var risk_assessment = 0;
            var visiting_position = '';
        }

    }else {
        var emergency_handling = 0;
        var risk_assessment = 0;
        var defective_batches = 0;
        var visiting_name = 0;
        var visiting_call = 0;
        var visiting_time = '';
        var visiting_position = '';
    }

    var id = $("#id").val();

    var mergeFlag = $("input[name='mergeFlag']:checked").val();
    var sup_disagree_explain = $("#supDisagreeExplain").val();
    console.log(emergency_handling)
    console.log(risk_assessment)
    console.log(defective_batches)
    console.log(visiting_name)
    console.log(visiting_call)
    console.log(visiting_time)

    if (sup_agree_rma == 0 && !sup_disagree_explain){
        //layer.msg("请填写拒绝说明");
        layer.msg(suplierModel.msg21);
        return false;
    }
    var ids = [];
    if(mergeFlag == 1){
        var rows = $('#merge_table').datagrid('getRows');
        if (rows.length==0){
            //layer.msg("请选择整改内容归并");
            layer.msg(suplierModel.msg22);
            return false;
        }else {
            for(var i=rows.length-1;i>=0;i--) {
                ids.push(rows[i].id);
            }
        }
    }

    // var plan_time = $("#planTime").val();
    // if (!plan_time){
    //     //layer.msg("请填写预计到访时间");
    //     layer.msg("请填写总体预计完成时间");
    //     return false;
    // }

    var formData = $(el.form).serializeJson();
    var attachData = $(el.attachments).attr('data-fileIds')
    formData.attachments = attachData
    var url = "/pc/spe/qualityManage/launchedQualityManage/rest/examine";
    $.ajax({
        url: url,
        method: "post",
        contentType: 'application/json',
        data:JSON.stringify(formData),
        // data:JSON.stringify( {
        //     id:id,
        //     supAgreeRma:sup_agree_rma,
        //     supDisagreeExplain:sup_disagree_explain,
        //     mergeFlag:mergeFlag,
        //     emergencyHandling: emergency_handling,
        //     riskAssessment: risk_assessment,
        //     defectiveBatches: defective_batches,
        //     visitingName: visiting_name,
        //     visitingCall: visiting_call,
        //     visitingTime: visiting_time,
        //     visitingPosition: visiting_position,
        //     ids: ids.join(','),
        //     planTime: plan_time
        // }),
        success: function (data) {
            if (data) {
                layer.alert(commonTxt.operateSuccess, function (index) {
                    layer.alert(commonTxt.successConfirm);
                    callback();
                    return false;

                });

            } else {
                layer.alert(claimModel.opt_fail_msg);
            }
        },
        error: function (data) {
            layer.alert(claimModel.opt_fail_msg);
        }
    });
    }else{
        layer.msg("红色框为必输项，请填写！");
    }
}

/**
 * @param call
 * 编辑和保存
 */

// function saveOrUpdate(call) {
//     if($(el.form).form('validate')){
//         var formData = $(el.form).serializeJson();
//         var attachData = $(el.attachment).attr('data-fileIds')
//         formData.attachment = attachData
//         var batch_num = $("#batchNum").val();
//         var bad_num = $("#badNum").val();
//         if (parseInt(bad_num) > parseInt(batch_num)) {
//             layer.msg("不合格数量不能大于检验批数量");
//             return false;
//         }
//         var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
//         $.ajax({
//             contentType: 'application/json',
//             url: g.ctx + 'pc/spe/qualityManage/launchedQualityManage/rest/saveOrUpdate',
//             method: 'post',
//             data: JSON.stringify(formData),
//             success: function (data) {
//                 call();
//             },
//             complete: function(data) {
//                 top.layer.close(loading);
//             },
//             error: function (data) {
//                 layer.alert(JSON.parse(data.responseText).message);
//             }
//         });
//     }else{
//         layer.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');
            }
        }]
    })
}