/**
 * 供应商绩效考核整改通知单详情
 *
 * Created by likui on 2019/9/16.
 */
'use strict';
var el = {
    pageType: '#pageType',
    noticeId: '#id',
    supplierCode: '#supplierCode',
    supplierName: '#supplierName',
    tbMeasures: '#tbMeasures',
    tbLog: '#tbLog'
};

$(function () {
    var pageType = parseFloat($(el.pageType).val());
    var noticeId = $(el.noticeId).val();
    initDataGrid(noticeId, pageType);
    initLogDataGrid(noticeId);
});


/**
 * 初始化整改措施表格
 */
function initDataGrid(noticeId, pageType) {
    var defaults = {
        url: g.ctx + 'pc/spe/rectifiedNotice/rest/measuresList',
        method: "GET",
        queryParams: {
            noticeId: noticeId
        },
        // loadMsg: '数据远程载入中,请等待...',
        loadMsg: suplierModel.loadData,
        singleSelect: true,
        pagination: false,
        checkbox: true,
        rownumbers: true,
        height: 350,
        autoSave: true
    };

    var columns = [
        {
            field: 'ck',
            checkbox: true
        },
        {
            field: 'id',
            hidden: true
        },
        {
            field: 'createFlag',
            hidden: true
        },
        {
            field: 'noticeOrderId',
            hidden: true
        },
        {
            field: 'indexRemark',
            title: '不合格项',
            width: 360
        },
        {
            field: 'measuresContent',
            title: '处理措施',
            width: 360
        },
        {
            field: 'personLiable',
            // title: '责任人',
            title: suplierModel.person_liable,
            width: 90
        },
        {
            field: 'attachments',
            // title: '附件操作',
            title: khzg.fjcz,
            width: 90,
            align: 'center',
            formatter: function (value, row, index) {
                return '<a href="javascript:lookAttachment(\'' + value + '\')" >' + buttonI18n.check + '</a>';
            }
        },
        {
            field: 'planCompleteTime',
            // title: '计划完成时间',
            title: khzg.plan_endTime,
            width: 130,
            formatter: function (value) {
                if (value) {
                    return moment(value).format('YYYY-MM-DD HH:mm:ss');
                }
                return '';
            }
        },
        {
            field: 'actualCompleteTime',
            // title: '完成时间',
            title: suplierModel.actual_complete_time,
            width: 140,
            formatter: function (value) {
                if (value) {
                    return moment(value).format('YYYY-MM-DD HH:mm:ss');
                }
                return '';
            }
        }
    ];

    if (pageType === 1) {
        defaults.toolbar = [
            // {
            //     // text : '添加',
            //     text: buttonI18n.addTJ,
            //     iconCls: 'icon-add',
            //     handler: function () {
            //         addMeasures(noticeId);
            //     }
            // }, "-",
            // {
            //     // text : '删除',
            //     text: buttonI18n.delete,
            //     iconCls: 'icon-remove',
            //     handler: function () {
            //         removeMeasures();
            //     }
            // }
        ];
        columns = [
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'id',
                hidden: true
            },
            {
                field: 'createFlag',
                hidden: true
            },
            {
                field: 'noticeOrderId',
                hidden: true
            },
            {
                field: 'indexRemark',
                title: '不合格项',
                width: 360
            },
            {
                field: 'measuresContent',
                title: '处理措施',
                width: 360,
                editor: {
                    type: 'textbox',
                    options: {
                        // prompt: '请输入不合格项'
                        prompt: '请输入不合格项'
                    }
                }
            },
            {
                field: 'personLiable',
                // title: '责任人',
                title: suplierModel.person_liable,
                width: 90,
                editor: {
                    type: 'textbox',
                    options: {
                        // prompt: '请输入责任人'
                        prompt: khzg.zrr_placeholder
                    }
                }
            },
            {
                field: 'attachments',
                // title: '附件操作',
                title: khzg.fjcz,
                width: 90,
                align: 'center',
                formatter: function (value, row, index) {
                    // return '<a href="javascript:" onclick="uploadRequireFileUI(' + index + ')">操作</a>';
                    return '<a href="javascript:" onclick="uploadRequireFileUI(' + index + ')">' + commonTxt.operate + '</a>';
                }
            },
            {
                field: 'planCompleteTime',
                // title: '计划完成时间',
                title: khzg.plan_endTime,
                width: 130,
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm:ss');
                    }
                    return '';
                },
                editor: {
                    type: 'datetimebox',
                    options: {
                        // prompt: '请选择计划完成时间',
                        prompt: khzg.plan_endTimePlaceholder,
                        panelWidth: '160',
                        panelHeight: '250',
                        editable: false
                    }
                }
            },
            {
                field: 'actualCompleteTime',
                // title: '完成时间',
                title: suplierModel.actual_complete_time,
                width: 140,
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm:ss');
                    }
                    return '';
                },
                editor: {
                    type: 'datetimebox',
                    options: {
                        // prompt: '请选择完成时间',
                        prompt: khzg.select_endTime,
                        panelWidth: '160',
                        panelHeight: '250',
                        editable: false
                    }
                }
            }
        ];
        //跟踪
    } else if (pageType === 2) {
        columns = [
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'id',
                hidden: true
            },
            {
                field: 'createFlag',
                hidden: true
            },
            {
                field: 'noticeOrderId',
                hidden: true
            },
            {
                field: 'indexRemark',
                title: '不合格项',
                width: 360
            },
            {
                field: 'measuresContent',
                title: '处理措施',
                width: 360
            },
            {
                field: 'personLiable',
                // title: '责任人',
                title: suplierModel.person_liable,
                width: 90
            },
            {
                field: 'attachments',
                // title: '附件操作',
                title: khzg.fjcz,
                width: 90,
                align: 'center',
                formatter: function (value, row, index) {
                    // return '<a href="javascript:" onclick="uploadRequireFileUI(' + index + ')">操作</a>';
                    return '<a href="javascript:" onclick="uploadRequireFileUI(' + index + ')">' + commonTxt.operate + '</a>';
                }
            },
            {
                field: 'planCompleteTime',
                // title: '计划完成时间',
                title: khzg.plan_endTime,
                width: 130,
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm:ss');
                    }
                    return '';
                }
            },
            {
                field: 'actualCompleteTime',
                // title: '完成时间',
                title: suplierModel.actual_complete_time,
                width: 140,
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm:ss');
                    }
                    return '';
                },
                editor: {
                    type: 'datetimebox',
                    options: {
                        // prompt: '请选择完成时间',
                        prompt: khzg.select_endTime,
                        panelWidth: '160',
                        panelHeight: '250',
                        editable: false
                    }
                }
            },
            {
                field: 'status',
                // title: '状态',
                title: buttonI18n.status,
                width: 80,
                formatter: function (value) {
                    if ((value * 1) === 0) {
                        return 'open';
                    }
                    if ((value * 1) === 1) {
                        return 'close';
                    }
                },
                editor: {
                    type: 'combobox',
                    options: {
                        valueField: 'value',
                        textField: 'label',
                        data: [{label: 'open', value: 0}, {label: 'close', value: 1}],
                        editable: false,
                        panelHeight: 'auto',
                        onSelect: function (data) {
                            if (data.value === 1) {
                                var row = $(el.tbMeasures).edatagrid('getSelected');
                                if (null != row) {
                                    row.actualCompleteTime = Date.parse(new Date());
                                }
                            }
                        }
                    }
                }
            }
        ];
    }
    defaults.columns = [columns];

    var settings = jQuery.extend(true, {}, defaults);
    $(el.tbMeasures).edatagrid(settings);
}


/**
 * 初始化审批日志表格
 *
 * @param noticeId 整改通知单ID
 */
function initLogDataGrid(noticeId) {
    $(el.tbLog).datagrid({
        url: g.ctx + 'pc/spe/rectifiedNotice/rest/examineLogList',
        method: "GET",
        queryParams: {
            noticeId: noticeId
        },
        loadMsg: suplierModel.loadData,
        singleSelect: true,
        pagination: false,
        checkbox: true,
        rownumbers: true,
        height: 370,
        columns: [[
            {
                field: 'noticeOrderId',
                hidden: true
            },
            {
                field: 'examineStatus',
                // title: '审核状态',
                title: suplierModel.examine_status,
                width: 120,
                formatter: function (value) {
                    if (value === 1) {
                        // return '<span style="color: green;">审批通过</span>';
                        return '<span style="color: green;">' + suplierModel.examine_pass + '</span>';
                    }
                    if (value === 2) {
                        // return '<span style="color: red;">拒绝</span>';
                        return '<span style="color: red;">' + buttonI18n.refuse + '</span>';
                    }
                    return '';
                }
            },
            {
                field: 'examineUserCode',
                // title: '审核人工号',
                title: suplierModel.examine_user_code,
                width: 130
            },
            {
                field: 'examineUserName',
                // title: '审核人姓名',
                title: suplierModel.examine_user_name,
                width: 140
            },
            {
                field: 'examineView',
                // title: '审核意见',
                title: suplierModel.examine_view,
                width: 300
            },
            {
                field: 'examineTime',
                // title: '审核时间',
                title: suplierModel.examine_time,
                width: 140,
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm:ss');
                    }
                    return '';
                }
            }
        ]]
    });
}

/**
 * 添加整改措施
 */
function addMeasures(noticeId) {
    // 新增一个带默认值的行
    $(el.tbMeasures).edatagrid('addRow', {
        id: 0,
        noticeOrderId: noticeId,
        measuresContent: '',
        personLiable: '',
        measuresAttachment: '',
        actualCompleteTime: '',
        status: 0
    });
}


/**
 * 删除整改措施
 */
function removeMeasures() {
    var rows = $(el.tbMeasures).edatagrid('getSelections');
    if (rows.length === 0) {
        // topWin.layer.msg('请选中记录进行操作');
        topWin.layer.msg(suplierModel.selectone);
        return false;
    }
    for (var i = 0; i < rows.length; i++) {
        var rowIndex = $(el.tbMeasures).datagrid('getRowIndex', rows[i]);
        $(el.tbMeasures).datagrid('updateRow', {
            index: rowIndex,
            row: {noticeOrderId: -1}
        });
        $(el.tbMeasures).datagrid('deleteRow', rowIndex);
    }
}

function lookAttachment(fileIds) {
    openFileUploadDialog("noticeFileUploadDialog", {
        title: "附件查看",
        fileIds: fileIds,
        lookupFlag: 1
    })
}

//附件上传
function uploadRequireFileUI(rec) {
    var rows = $(el.tbMeasures).datagrid('getRows');
    var row = rows[rec];
    openFileUploadDialog("noticeFileUploadDialog", {
        title: "附件上传",
        fileIds: row.attachments,
        callBack: function (fileIds) {
            returnAddRequirefileUpload(fileIds.join(","))
        }
    })
}

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

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

    $(el.tbMeasures).datagrid('beginEdit', inx);
}

/**
 * 保存整改数据
 *
 * @param callback 回调函数
 */
function saveData(callback) {
    var eaRows = $(el.tbMeasures).edatagrid('getRows');
    $.each(eaRows, function (index, item) {
        $(el.tbMeasures).edatagrid('endEdit', index);
    });

    var noticeId = $(el.noticeId).val();

    var insertedRows = $(el.tbMeasures).edatagrid('getChanges', 'inserted');
    var updatedRows = $(el.tbMeasures).edatagrid('getChanges', 'updated');
    var result = insertedRows.concat(updatedRows);

    var rows = [];
    for (var n = 0; n < result.length; n++) {
        var ob = {}, item = result[n];
        if (!item.id) {
            ob.id = 0;
        } else {
            ob.id = item.id;
        }
        ob.noticeOrderId = item.noticeOrderId ? item.noticeOrderId : noticeId;
        ob.measuresContent = item.measuresContent;
        ob.personLiable = item.personLiable;
        ob.attachments = item.attachments;
        ob.planCompleteTime = item.planCompleteTime;
        ob.planCompleteTime = item.planCompleteTime;
        ob.status = item.status;
        if (item.actualCompleteTime) {
            ob.actualCompleteTime = moment(item.actualCompleteTime).format('YYYY-MM-DD HH:mm:ss');
        } else {
            ob.actualCompleteTime = '';
        }

        rows.push(ob);
    }

    if (eaRows.length == 0) {
        // topWin.layer.msg("请添加整改措施");
        topWin.layer.msg(khzg.add_zgcs);
        return false;
    }
    for (var i = 0; i < eaRows.length; i++) {
        var flag = false;
        var msg = "";
        if (!eaRows[i].measuresContent) {
            // msg = "整改措施第" + (i + 1) + "行，" + "处理措施" + "不能为空";
            msg = khzg.zgcs + khzg.the + (i + 1) + suplierModel.line + ", " + suplierModel.measures_content + suplierModel.cannot_empty;
            topWin.layer.msg(msg, {time: 2000});
            flag = true;
            return false;
        }
        if (!eaRows[i].personLiable) {
            // msg = "整改措施第" + (i + 1) + "行，" + "责任人" + "不能为空";
            msg = khzg.zgcs + khzg.the + (i + 1) + suplierModel.line + ", " + suplierModel.person_liable + suplierModel.cannot_empty;
            topWin.layer.msg(msg, {time: 2000});
            flag = true;
            return false;
        }
        if (!eaRows[i].planCompleteTime) {
            // msg = "整改措施第" + (i + 1) + "行，" + "计划时间" + "不能为空";
            msg = khzg.zgcs + khzg.the + (i + 1) + suplierModel.line + ", " + suplierModel.plan_complete_time + suplierModel.cannot_empty;
            topWin.layer.msg(msg, {time: 2000});
            flag = true;
            return false;
        }
    }
    var data = {
        noticeId: noticeId,
        attachments: $(el.attachments).val(),
        measures: JSON.stringify(rows)
    };

    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/spe/rectifiedNotice/rest/updateRectification',
        contentType: 'application/json',
        data: JSON.stringify({
            noticeId: noticeId,
            attachments: $("#fileIds").attr('data-fileIds'),
            measures: rows
        }),
        success: function () {
            topWin.layer.msg(commonTxt.operateSuccess, {icon: 1, time: 500}, function () {
                callback();
            });
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message)
        }
    });
}

/**
 * 保存整改数据
 *
 * @param callback 回调函数
 */
function submit(callback) {
    var eaRows = $(el.tbMeasures).edatagrid('getRows');
    $.each(eaRows, function (index, item) {
        $(el.tbMeasures).edatagrid('endEdit', index);
    });

    var noticeId = $(el.noticeId).val();

    var insertedRows = $(el.tbMeasures).edatagrid('getChanges', 'inserted');
    var updatedRows = $(el.tbMeasures).edatagrid('getChanges', 'updated');
    var result = insertedRows.concat(updatedRows);

    var rows = [];
    for (var n = 0; n < result.length; n++) {
        var ob = {}, item = result[n];
        if (!item.id) {
            ob.id = 0;
        } else {
            ob.id = item.id;
        }
        ob.noticeOrderId = item.noticeOrderId ? item.noticeOrderId : noticeId;
        ob.measuresContent = item.measuresContent;
        ob.personLiable = item.personLiable;
        ob.attachments = item.attachments;
        ob.planCompleteTime = item.planCompleteTime;
        ob.planCompleteTime = item.planCompleteTime;
        ob.status = item.status;
        if (item.actualCompleteTime) {
            ob.actualCompleteTime = moment(item.actualCompleteTime).format('YYYY-MM-DD HH:mm:ss');
        } else {
            ob.actualCompleteTime = '';
        }
        rows.push(ob);
    }

    if (eaRows.length == 0) {
        topWin.layer.msg(khzg.add_zgcs);
        return false;
    }
    for (var i = 0; i < eaRows.length; i++) {
        var flag = false;
        var msg = "";
        if (!eaRows[i].measuresContent) {
            // msg = "整改措施第" + (i + 1) + "行，" + "处理措施" + "不能为空";
            msg = khzg.zgcs + khzg.the + (i + 1) + suplierModel.line + ", " + suplierModel.measures_content + suplierModel.cannot_empty;
            topWin.layer.msg(msg, {time: 2000});
            flag = true;
            return false;
        }
        if (!eaRows[i].personLiable) {
            // msg = "整改措施第" + (i + 1) + "行，" + "责任人" + "不能为空";
            msg = khzg.zgcs + khzg.the + (i + 1) + suplierModel.line + ", " + suplierModel.person_liable + suplierModel.cannot_empty;
            topWin.layer.msg(msg, {time: 2000});
            flag = true;
            return false;
        }
        if (!eaRows[i].planCompleteTime) {
            // msg = "整改措施第" + (i + 1) + "行，" + "计划时间" + "不能为空";
            msg = khzg.zgcs + khzg.the + (i + 1) + suplierModel.line + ", " + suplierModel.plan_complete_time + suplierModel.cannot_empty;
            topWin.layer.msg(msg, {time: 2000});
            flag = true;
            return false;
        }
    }
    var data = {
        noticeId: noticeId,
        attachments: $(el.attachments).val(),
        measures: JSON.stringify(rows)
    };

    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/spe/rectifiedNotice/rest/updateRectification1',
        contentType: 'application/json',
        data: JSON.stringify({
            noticeId: noticeId,
            attachments: $("#fileIds").attr('data-fileIds'),
            measures: rows
        }),
        success: function () {
            topWin.layer.msg(commonTxt.operateSuccess, {icon: 1, time: 500}, function () {
                callback();
            });
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message)
        }
    });
}