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

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

/**
 * 初始化整改措施表格
 */
function initDataGrid(noticeId) {
    var defaults = {
        queryParams: {
            noticeId: noticeId
        },
        loadMsg: '数据远程载入中,请等待...',
        singleSelect: true,
        pagination: false,
        checkbox: true,
        rownumbers: true,
        height: 350,
        autoSave: true
    };

    var columns = [
        {
            field: 'ck',
            checkbox: true
        },
        {
            field: 'id',
            hidden: true
        },
        {
            field: 'noticeOrderId',
            hidden: true
        },
        {
            field: 'measuresContent',
            title: '处理措施',
            width: 360
        },
        {
            field: 'personLiable',
            title: '责任人',
            width: 90
        },
        {
            field: 'attachments',
            title: '附件操作',
            width: 90,
            align: 'center',
            formatter: function (value, row, index) {
                return '<a href="javascript:lookAttachment(' + row.id + ')" >查看</a>';
            }
        },
        {
            field: 'planCompleteTime',
            title: '计划完成时间',
            width: 130,
            formatter: function (value) {
                if (value) {
                    return moment(value).format('YYYY-MM-DD');
                }
                return '';
            }
        },
        {
            field: 'actualCompleteTime',
            title: '完成时间',
            width: 140,
            formatter: function (value) {
                if (value) {
                    return moment(value).format('YYYY-MM-DD HH:mm:ss');
                }
                return '';
            }
        },
        {
            field: 'status',
            title: '状态',
            width: 80,
            formatter: function (value) {
                if (value === 0) {
                    return 'open';
                }
                if (value === 1) {
                    return 'close';
                }
            }
        }
    ];

    defaults.toolbar = [
        {
            text: '添加',
            iconCls: 'icon-add',
            handler: function () {
                addMeasures(noticeId);
            }
        }, "-",
        {
            text: '删除',
            iconCls: 'icon-remove',
            handler: function () {
                removeMeasures();
            }
        }
    ];
    columns = [
        {
            field: 'ck',
            checkbox: true
        },
        {
            field: 'id',
            hidden: true
        },
        {
            field: 'noticeOrderId',
            hidden: true
        },

        {
            field: 'indexRemark',
            title: '不合格项',
            width: 360,
            editor: {
                type: 'textbox',
                options: {
                    prompt: '请输入不合格项'
                }
            }
        },
        {
            field: 'measuresContent',
            title: '处理措施',
            width: 360,
            editor: {
                type: 'textbox',
                options: {
                    prompt: '请输入处理措施'
                }
            }
        },
        {
            field: 'personLiable',
            title: '责任人',
            width: 90,
            editor: {
                type: 'textbox',
                options: {
                    prompt: '请输入责任人'
                }
            }
        },
        {
            field: 'attachments',
            title: '附件操作',
            width: 90,
            align: 'center',
            formatter: function (value, row, index) {
                return '<a href="javascript:" onclick="uploadRequireFileUI(' + index + ')">操作</a>';
            }
        },
        {
            field: 'planCompleteTime',
            title: '计划完成时间',
            width: 130,
            // formatter: function (value) {
            //     if (value) {
            //         return moment(value).format('YYYY-MM-DD');
            //     }
            //     return '';
            // },
            editor: {
                type: 'datetimebox',
                options: {
                    prompt: '请选择计划完成时间',
                    panelWidth: '160',
                    panelHeight: '250',
                    editable: false
                }
            }
        },
        {
            field: 'actualCompleteTime',
            title: '完成时间',
            width: 140,
            formatter: function (value) {
                if (value) {
                    return moment(value).format('YYYY-MM-DD HH:mm:ss');
                }
                return '';
            }
        },
        {
            field: 'status',
            title: '状态',
            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);
    if (it !== '') {
        $.each(it, function (i, n) {
            $(el.tbMeasures).edatagrid('appendRow', {indexRemark: n});
        })
    }
}

/**
 * 初始化审批日志表格
 *
 * @param noticeId 整改通知单ID
 */
function initLogDataGrid(noticeId) {
    $(el.tbLog).datagrid({
        url: g.ctx + 'supplier/appraise/rectified/notice/rest/log/list',
        queryParams: {
            noticeId: noticeId
        },
        loadMsg: '数据远程载入中,请等待...',
        singleSelect: true,
        pagination: false,
        checkbox: true,
        rownumbers: true,
        height: 370,
        columns: [[
            {
                field: 'noticeOrderId',
                hidden: true
            },
            {
                field: 'examineStatus',
                title: '审核状态',
                width: 120,
                formatter: function (value) {
                    if (value === 1) {
                        return '<span style="color: green;">审批通过</span>';
                    }
                    if (value === 2) {
                        return '<span style="color: red;">拒绝</span>';
                    }
                    return '';
                }
            },
            {
                field: 'examineUserCode',
                title: '审核人工号',
                width: 130
            },
            {
                field: 'examineUserName',
                title: '审核人姓名',
                width: 140
            },
            {
                field: 'examineView',
                title: '审核意见',
                width: 300
            },
            {
                field: 'examineTime',
                title: '审核时间',
                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,
        indexRemark: '',
        measuresContent: '',
        personLiable: '',
        measuresAttachment: '',
        actualCompleteTime: '',
        status: 0
    });
}

/**
 * 删除整改措施
 */
function removeMeasures() {
    var rows = $(el.tbMeasures).edatagrid('getSelections');
    if (rows.length === 0) {
        topWin.layer.msg('请选中记录进行操作');
        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 uploadRequireFileUI(rec) {
    var rows = $(el.tbMeasures).datagrid('getRows');
    var row = rows[rec];
    openFileUploadDialog("noticeFileUploadDialog", {
        title: "附件上传",
        fileIds: row.attachments,
        callBack: function (fileIds) {
            console.log(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);
}

//选择SQE/MCE人员
$("#dataForm").on('click', el.mqeMceNameEasyUi, function () {
    var userDialogElement = openDialog("userDialog", g.ctx + "pc/sys/user/index?select=1&single=1", {
        title: "用户选择",
        width: '80%',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userDialogElement.dialog('destroy');
        },
        buttons: [{
            text: '选择', iconCls: 'icon-save', handler: function () {
                topWin.frames['userDialog'].chooseRow(function (rows) {
                    returnSelectUser(rows[0])
                    userDialogElement.dialog('close');
                });
            }
        }, {
            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                userDialogElement.dialog('close');
            }
        }]
    })
});

//选择SQE/MCE人员回调
function returnSelectUser(user) {
    $('#confirm_user_name').textbox('setValue', user.username);
    $('#confirm_user_code').val(user.accountName);
}

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

    var supplierPlanId = $(el.supplierPlanId).val();
    var planTemType = $(el.planTemType).val();
    var opinionRemark = $(el.opinionRemark).val();
    var confirmUserCode = $('#confirm_user_code').val();
    // if (!opinionRemark) {
    //     topWin.layer.msg('请输入整改意见', {icon: 2, time: 1000});
    //     return false;
    // }
    if (!confirmUserCode) {
        topWin.layer.msg('请选择确认人', {icon: 2, time: 1000});
        return false;
    }
    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];
        ob.id = item.isNewRecord ? 0 : item.id;
        ob.measuresContent = item.measuresContent;
        ob.personLiable = item.personLiable;
        ob.measuresAttachment = item.measuresAttachment;
        ob.planCompleteTime = item.planCompleteTime;
        ob.status = item.status;
        ob.attachments = item.attachments;
        if (item.actualCompleteTime) {
            ob.actualCompleteTime = moment(item.actualCompleteTime).format('YYYY-MM-DD HH:mm:ss');
        } else {
            ob.actualCompleteTime = '';
        }

        rows.push(ob);
    }

    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/spe/rectifiedNotice/rest/saveNotice',
        contentType: 'application/json',
        data: JSON.stringify({
            supplierPlanId: supplierPlanId,
            planTemType: planTemType,
            opinionRemark: opinionRemark,
            confirmUserCode: confirmUserCode,
            measures: rows
        }),
        success: function () {
            topWin.layer.msg('操作成功', {icon: 1, time: 500}, function () {
                callback();
            });
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}