var el = {
    form : '#form',
    qualityNotice: '#qualityNotice',
    emptyTd: '.empty-td',
    qualityNoticeData: '.quality_notice_data',
    qualityNoticeCode: '#qualityNoticeCode',
    suppllierName: '#suppllierName',
    badReason: '#badReason',
    problemSource: '#problemSource',
    auditAttachment: '#auditAttachment',
    ncrBidAttachment: '#ncrBidAttachment',
    ncrAttachment: '#ncrAttachment',
    planAuditTimeStr: '#planAuditTimeStr',
    userIdMap: {},
}

var searchData;
/**
 * 初始化页面特殊输入框
 */
$(function () {

    timeSelect();
    // 初始化稽核原因下拉框
    $('#auditReason').combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=audit_reason',
        panelHeight: 260,
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
    // 初始化稽核结果下拉框
    $('#auditResult').combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=audit_result',
        panelHeight: 260,
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
    //是否为风险供应商
    $('#isRiskSupplier').combobox({
        editable: false,
        panelHeight: 'auto',
        valueField: 'value',
        textField: 'label',
        prompt:'--请选择--',
        data: [
            {value: '', label: ''},
            {value: '0', label: '是'},
            {value: '1', label: '否'}
        ],
        // multiple: true,
    });
    //NCR结案审批
    $('#ncrExamine').combobox({
        editable: false,
        panelHeight: 'auto',
        valueField: 'value',
        textField: 'label',
        data: [
            {value: '0', label: 'Onging'},
            {value: '1', label: 'Closed'}
        ],
        // multiple: true,
    });
    // 初始化公司下拉框
    $('#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);
        }
    });


});



function searchPCName(value){

    // const uploadOptions = {
    //     title: '稽核附件上传',
    //     lookFlag: false,
    // }
    //     uploadOptions.callBack = function (fileIds) {
            $.ajax({
                url: g.ctx + 'pc/spe/qmAuditManage/rest/find?supplierId=' + value,
                method: "POST",
                // contentType: 'application/json',
                data: value,
                success: function (responseData) {
                    searchData = responseData;
                    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});
                }
            });
        // }
}
/**
 * @param call
 * 编辑和保存
 */
// $("#supplierName").searchbox({
//     // min:0,
//     // precision:4,
//
//     onChange:function (newValue, oldValue) {
//
//         var formData = $(el.form).serializeJson();
//         newValue = formData.supplierId;
//         searchPCName(newValue)
//         setTimeout(function(){
//             $('#purchaseCategoryName').textbox('setValue',searchData.body);
//         },1000);
//
//     }
// })

function saveOrUpdate(call) {

    if($(el.form).form('validate')){
        var formData = $(el.form).serializeJson();
        var flag = formData.flag;
        var ncrBidData = $(el.ncrBidAttachment).attr('data-fileIds')
        formData.ncrBidAttachment = ncrBidData
        var auditData = $(el.auditAttachment).attr('data-fileIds')
        formData.auditAttachment = auditData
        var textarea = document.getElementById('supplierAdvantage');
        // 获取 textarea 的值并去除首尾空格
        var supplierAdvantage = textarea.value.trim();
        var textarea1 = document.getElementById('supplierDisadvantage');
        var supplierDisadvantage = textarea1.value.trim();
        var ncrData = $(el.ncrAttachment).attr('data-fileIds')
        var auditReasonO = document.getElementById('auditReason');
        var auditReason = auditReasonO.value


        if(flag == 1){
            if (formData.auditAttachment === null || formData.auditAttachment === undefined || formData.auditAttachment === "") {
                layer.msg("请上传稽核报告附件");
                return;
            }
        }
        console.log(8888888888888888888)
        console.log(auditReason)
        if(auditReason == 4){
            if (supplierAdvantage=== null || supplierAdvantage === undefined || supplierAdvantage === "") {
                layer.msg("当前稽核原因下供应商优势为必填项");
                return;
            }
            if (supplierDisadvantage=== null || supplierDisadvantage === undefined || supplierDisadvantage === "") {
                layer.msg("当前稽核原因下供应商劣势为必填项");
                return;
            }
        }

        if (formData.ncrBidAttachment === null || formData.ncrBidAttachment === undefined || formData.ncrBidAttachment === "") {
            layer.msg("请上传NCR清单附件");
            return;
        }
        formData.ncrAttachment = ncrData
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            contentType: 'application/json',
            url: g.ctx + 'pc/spe/qmAuditManage/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 submit(call) {

    if($(el.form).form('validate')){
        var formData = $(el.form).serializeJson();
        var auditData = $(el.auditAttachment).attr('data-fileIds')
        formData.auditAttachment = auditData
        var ncrBidData = $(el.ncrBidAttachment).attr('data-fileIds')
        formData.ncrBidAttachment = ncrBidData
        var ncrData = $(el.ncrAttachment).attr('data-fileIds')
        // 获取 textarea 元素
        var textarea = document.getElementById('supplierAdvantage');
        // 获取 textarea 的值并去除首尾空格
        var supplierAdvantage = textarea.value.trim();
        var textarea1 = document.getElementById('supplierDisadvantage');
        var supplierDisadvantage = textarea1.value.trim();
        // var supplierAdvantage = formData.supplierAdvantage;
        // var supplierDisadvantage = formData.supplierDisadvantage;
        var auditReasonO = document.getElementById('auditReason');
        var auditReason = auditReasonO.value
        if(auditReason == 4){
            if (supplierAdvantage=== null || supplierAdvantage === undefined || supplierAdvantage === "") {
                layer.msg("当前稽核原因下供应商优势为必填项");
                return;
            }
            if (supplierDisadvantage=== null || supplierDisadvantage === undefined || supplierDisadvantage === "") {
                layer.msg("当前稽核原因下供应商劣势为必填项");
                return;
            }
        }

        if (formData.auditAttachment === null || formData.auditAttachment === undefined || formData.auditAttachment === "") {
            layer.msg("请上传稽核报告附件");
            return;
        }
        if (formData.ncrBidAttachment === null || formData.ncrBidAttachment === undefined || formData.ncrBidAttachment === "") {
            layer.msg("请上传NCR清单附件");
            return;
        }
        formData.ncrAttachment = ncrData
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            contentType: 'application/json',
            url: g.ctx + 'pc/spe/qmAuditManage/rest/submit',
            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 saveOrUpdate1(call) {

    if($(el.form).form('validate')){
        var formData = $(el.form).serializeJson();
        var auditData = $(el.auditAttachment).attr('data-fileIds')
        formData.auditAttachment = auditData
        var ncrData = $(el.ncrAttachment).attr('data-fileIds')
        if (formData.auditAttachment === null || formData.auditAttachment === undefined || formData.auditAttachment === "") {
            layer.msg("请上传稽核报告附件");
            return;
        }
        formData.ncrAttachment = ncrData
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            contentType: 'application/json',
            url: g.ctx + 'pc/spe/qmAuditManage/rest/saveOrUpdate1',
            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 saveOrUpdate2(call) {
    if($(el.form).form('validate')){
        var formData = $(el.form).serializeJson();
        var auditData = $(el.auditAttachment).attr('data-fileIds')
        formData.auditAttachment = auditData
        var ncrData = $(el.ncrAttachment).attr('data-fileIds')
        if (formData.auditAttachment === null || formData.auditAttachment === undefined || formData.auditAttachment === "") {
            layer.msg("请上传稽核报告附件");
            return;
        }
        formData.ncrAttachment = ncrData
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            contentType: 'application/json',
            url: g.ctx + 'pc/spe/qmAuditManage/rest/saveOrUpdate2',
            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: true,
        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 categorySearch() {
var purchaseCategoryDialog = openDialog("purchaseCategoryDialog", g.ctx + 'pc/sys/purchaseCategory/index?select=1', {
    title: '采购品类选择器',
    width: '80%',
    height: '80%',
    cache: false,
    modal: true,
    border: false,
    draggable: false,
    shadow: false,
    onClose: function () {
        purchaseCategoryDialog.dialog('destroy');
    },
    buttons: [{
        text: itablei8n.save,
        handler: function () {
            topWin.frames['purchaseCategoryDialog'].chooseRow(function (row) {
                $("#purchaseCategoryCode").val(row.firstLevelPurchaseCode);
                $('#purchaseCategoryName').textbox('setValue', row.firstLevelPurchaseName);
                purchaseCategoryDialog.dialog('close');
            });
        }
    }, {
        text: itablei8n.close, handler: function () {
            purchaseCategoryDialog.dialog('close');
        }
    }]
})
}


/**
 * 选择用户
 */
function userSearch (type) {
    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]
                    if(type===1){
                        //稽核组长
                        $('#auditMasterName').textbox('setValue', rows[0].username);
                        $('#auditMaster').val(rows[0].id);
                    }else if(type===2){
                        //策略采购
                        $('#policyPurchaseName').textbox('setValue', rows[0].username);
                        $('#policyPurchase').val(rows[0].id);
                    }else if(type===3) {
                        //采购主管
                        $('#purchaseMasterName').textbox('setValue', rows[0].username);
                        $('#purchaseMaster').val(rows[0].id);
                    }
                    userDialogElement.dialog('close');
                });
            }
        }, {
            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                userDialogElement.dialog('close');
            }
        }]
    })
}
function userSearch1 () {
    userSearch(1)
}
function userSearch2 () {
    userSearch(2)
}
function userSearch3 () {
    userSearch(3)
}

/**
 * 选择时间
 */
function timeSelect(){
    //日期选择对象
    var p = $(el.planAuditTimeStr).datebox('panel'),
        //日期选择对象中月份
        tds = false,
        //显示月份层的触发控件
        span = p.find('span.calendar-text');
    $(el.planAuditTimeStr).datebox({
        //显示日趋选择对象后再触发弹出月份层的事件，初始化时没有生成月份层
        onShowPanel: function () {
            //触发click事件弹出月份层
            span.trigger('click');
            if (!tds)
                //延时触发获取月份对象，因为上面的事件触发和对象生成有时间间隔
                setTimeout(function () {
                    tds = p.find('div.calendar-menu-month-inner td');
                    tds.click(function (e) {
                        //禁止冒泡执行easyui给月份绑定的事件
                        e.stopPropagation();
                        //得到年份
                        var year = /\d{4}/.exec(span.html())[0],
                            //月份
                            //之前是这样的month = parseInt($(this).attr('abbr'), 10) + 1;
                            month = parseInt($(this).attr('abbr'), 10);

                        //隐藏日期对象
                        $(el.planAuditTimeStr).datebox('hidePanel')
                            //设置日期的值
                            .datebox('setValue', year + '-' + month);
                    });
                }, 0);
        },
        //配置parser，返回选择的日期
        parser: function (s) {
            if (!s) return new Date();
            var arr = s.split('-');
            return new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, 1);
        },
        //配置formatter，只返回年月 之前是这样的d.getFullYear() + '-' +(d.getMonth());
        formatter: function (d) {
            var currentMonth = (d.getMonth() + 1);
            var currentMonthStr = currentMonth < 10 ? ('0' + currentMonth) : (currentMonth + '');
            return d.getFullYear() + '-' + currentMonthStr;
        }
    });
    }
