var selectQuotaCodes = {}
var selectDimensionCodes = {}
var enableDrag = 0

//加载考核维度列表
function initDimensionGrid(templateId) {
    $("#tbDimension").edatagrid({
        url: g.ctx + 'pc/spe/supAppraiseTemplate/rest/supTemDimension/list?templateId=' + templateId,
        method: "GET",
        loadMsg: '数据远程载入中,请等待...',
        singleSelect: false,
        checkbox: true,
        rownumbers: true,
        autoSave: true,
        height: 445,
        columns: [[{
            field: 'ck', checkbox: true
        }, {
            field: 'templateId', hidden: true
        }, {
            field: 'dimensionId', hidden: true
        }, {
            field: 'dimensionCode', hidden: true
        }, {
            field: 'dimensionName', title: '考核维度', width: 270
        }, {
            field: 'totalScore', title: '总分', width: 200, editor: {
                type: 'numberbox', options: {
                    min: 0, max: 100, precision: 0
                }
            }
        }]],
        toolbar: [{
            text: '添加', iconCls: 'icon-add', handler: function () {
                addDimension();
            }
        }, "-", {
            text: '删除', iconCls: 'icon-remove', handler: function () {
                delDimension();
            }
        }],
        onLoadSuccess: function (data) {
            $.each(data.rows, function (idx, itm) {
                selectDimensionCodes[itm.dimensionCode] = 1
            })
            $("#tbDimension").datagrid('enableDnd');
        },
        onStartDrag: function (row) {
            $("#tbDimension").edatagrid("saveRow");
        }
    });
}

//考核模板新增—考核维度添加
function addDimension() {
    $("#tbDimension").edatagrid('saveRow');
    var rows = $("#tbDimension").edatagrid('getRows');
    var selected = [];
    $.each(rows, function (index, item) {
        selected.push(item.dimensionCode);
    })
    openDimensionDialog(selected);
}

function openDimensionDialog(selected) {
    var url = g.ctx + "pc/spe/supAppraiseTemplate/dimension/chose?selected=" + selected.join(',');
    dimensionDialo = openDialog('dimensionDialo', url, {
        title: '添加维度', width: 300, height: 400, cache: false, modal: true, border: 'thin', onClose: function () {
            dimensionDialo.dialog('destroy');
        }, buttons: [{
            text: '确定', handler: function () {
                var selectRows = topWin.frames['dimensionDialo'].page.getSelectedRows();
                $.each(selectRows, function (index, item) {
                    if (selected.indexOf(item.dimensionCode) == -1) {
                        //需要进行转换
                        let row = {
                            dimensionCode: item.dimensionCode,
                            dimensionName: item.dimensionName
                        }
                        $("#tbDimension").edatagrid('appendRow', row);
                    }
                });
                dimensionDialo.dialog('close');
            }
        }, {
            text: '关闭', handler: function () {
                dimensionDialo.dialog('close');
            }
        }]
    });
}

////加载考核维度列表
function initQuotaGrid(templateId) {
    $("#tbQuota").edatagrid({
        iconCls: 'icon-list',
        method: "GET",
        url: g.ctx + 'pc/spe/supAppraiseTemplate/rest/supTemQuota/list?templateId=' + templateId,
        width: '100%',
        height: 450,
        autoSave: true,
        singleSelect: false,
        pagination: false,
        rownumbers: true,
        fitColumns: false,
        nowrap: true,
        remoteSort: false,
        striped: true,
        columns: [[{
            field: 'ck', checkbox: true
        }, {
            field: 'templateId', hidden: true
        }, {
            field: 'dimensionName', title: '考核维度', width: 100
        }, {
            field: 'quotaCode', title: '指标编码', width: 100
        }, {
            field: 'quotaDesc', title: '指标描述', width: 100, editor: {
                type: 'text', options: {}
            }
        }, {
            field: 'calculationFormula', title: '评分逻辑', width: 200, editor: {
                type: 'text', options: {}
            }
        }, {
            field: 'maxScore', title: '分值上限', width: 90, editor: {
                type: 'numberbox', options: {
                    min: 0, max: 999, precision: 0
                }
            }
        }, {
            field: 'quotaType', title: '指标类型', width: 100, editor: {
                type: 'combobox', options: {
                    valueField: 'id',
                    textField: 'text',
                    editable: false,
                    data: [{id: 1, text: '模板导入'}, {id: 2, text: '公式计算'}, {
                        id: 3, text: '系统获取'
                    }, {id: 4, text: '手动输入'}]
                }
            }, formatter: function (value) {
                if (!value) {
                    return '';
                }
                if (value == 1) {
                    return '模板导入';
                } else if (value == 2) {
                    return '公式计算';
                } else if (value == 3) {
                    return '系统获取';
                } else if (value == 4) {
                    return '手动输入';
                }
            }
        }]],
        toolbar: [{
            text: '添加', iconCls: 'icon-add', handler: function () {
                addQuota();
            }
        }, "-", {
            text: '删除', iconCls: 'icon-remove', handler: function () {
                removeQuota('');
            }
        }, {
            text: '启用拖拽', iconCls: 'icon-folder-move', id: "drag_btn", handler: () => {
                $("#tbQuota").edatagrid('saveRow');
                if (enableDrag) {
                    enableDrag = 0;
                    $("#tbQuota").datagrid('enableDnd', -1);
                    $("#drag_btn").linkbutton({"text": "启用拖拽"});
                } else {
                    enableDrag = 1;
                    $("#tbQuota").datagrid('enableDnd');
                    $("#drag_btn").linkbutton({"text": "禁用拖拽"});
                }
            }
        }],
        onLoadSuccess: function (data) {
            $.each(data.rows, function (idx, itm) {
                selectQuotaCodes[itm.quotaCode] = 1
            })
        },
        onStartDrag: function (row) {
            $("#tbQuota").edatagrid("saveRow");
        },
        onBeforeDrag: function () {
            if (!enableDrag) {
                return false;
            }
        }
    });
}

//考核模板新增—考核指标新增
function addQuota() {
    var existRows = $("#tbQuota").datagrid('getRows'), quotaIds = [];
    var dcMapIndex = {};
    $.each(existRows, function (index, item) {
        dcMapIndex[item.dimensionCode] = index;
        quotaIds.push(item.quotaCode);
    });

    var choseDim = [];
    var rows = $("#tbDimension").edatagrid('getRows');
    $.each(rows, function (index, item) {
        choseDim.push(item.dimensionCode);
    });

    var url = g.ctx + 'pc/spe/supAppraiseTemplate/quota/chose?quotaCodes=' + quotaIds.join(',') + '&choseDimCodes=' + choseDim.join(',');
    //var url = g.ctx + 'pc/spe/supAppraiseTemplate/quota/chose';
    var choseDialog = openDialog('addQuota', url, {
        title: '选择模板指标项目',
        width: 500,
        height: 600,
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            choseDialog.dialog('destroy');
        },
        buttons: [{
            text: '确定', handler: function () {
                var data = topWin.frames['addQuota'].page.confirmChose();
                var i = 1;
                $.each(data.rows, function (index, item) {
                    if (selectQuotaCodes[item.quotaCode] === undefined) {
                        var insertIndex = dcMapIndex[item.dimensionCode];
                        if (insertIndex == undefined) {
                            insertIndex = 0;
                        }
                        $("#tbQuota").datagrid('insertRow', {
                            index: insertIndex + i, row: {
                                quotaCode: item.quotaCode,
                                supplierFlag: item.supplierFlag,
                                quotaDesc: item.quotaDesc,
                                scoreLogic: item.scoreLogic,
                                dimensionCode: item.dimensionCode,
                                dimensionName: item.dimensionName,
                                maxScore: item.maxScore,
                                quotaType: item.quotaType,
                                calculationFormula: item.calculationFormula
                            }
                        });
                        i = i + 1;
                    }
                });
                $("#tbQuota").datagrid('enableDnd');
                choseDialog.dialog('close');
            }
        }, {
            text: '关闭', handler: function () {
                choseDialog.dialog('close');
            }
        }]
    });
}

//考核模板新增—考核指标删除
function removeQuota(delRows) {
    if (delRows === '') {
        delRows = $("#tbQuota").edatagrid('getSelections');
    }
    if (delRows.length === 0) {
        topWin.layer.msg('请选中记录进行操作');
        return;
    }
    let rowIdxs = []
    $.each(delRows, function (idx, itm) {
        delete selectQuotaCodes[itm.quotaCode]
        rowIdxs.push($("#tbQuota").edatagrid('getRowIndex', itm))
    })
    // 将指标删除
    removeTableRow("#tbQuota", rowIdxs);
}


//考核模板新增—考核维度删除
function delDimension() {
    $("#tbDimension").edatagrid('saveRow');
    var rows = $("#tbDimension").edatagrid('getChecked');
    var rmDcs = [];
    let removeRowIndex = []
    $.each(rows, function (index, row) {
        rmDcs.push(row.dimensionCode);
        delete selectQuotaCodes[row['dimensionCode']]
        var rowIndex = $("#tbDimension").edatagrid('getRowIndex', row);
        removeRowIndex.push(rowIndex)
    });
    // 将指标删除
    removeTableRow("#tbDimension", removeRowIndex);
    // 删除该维度下的指标项目
    var quotaRows = $("#tbQuota").edatagrid('getRows');
    let removeQuotaRowIdx = []
    $.each(quotaRows, function (idx, itm) {
        if (rmDcs.indexOf(itm.dimensionCode) !== -1) {
            delete selectQuotaCodes[itm['quotaCode']]
            var rowIndex = $("#tbQuota").edatagrid('getRowIndex', itm);
            removeQuotaRowIdx.push(rowIndex)
        }
    })
    // 将指标删除
    removeTableRow("#tbQuota", removeQuotaRowIdx);
}

function removeTableRow(tb, rowIndexs) {
    console.log('删除的rowIndex', rowIndexs)
    rowIndexs.reverse()
    $.each(rowIndexs, function (idx, itm) {
        $(tb).datagrid('deleteRow', itm);
    })
}

$(function () {
    var type = [{label: '全部', value: -1}, {label: '年度', value: 1}, {label: '季度', value: 2}, {
        label: '月度',
        value: 3
    }];
    // 初始化评价周期下拉框
    $("#evaluationCycle").combobox({
        valueField: 'value',
        textField: 'label',
        data: type,
        editable: false,
        required: true,
        panelHeight: 'auto',
        prompt: '-- 请选择 --'
    });
    var templateId = $("#id").val();
    initDimensionGrid(templateId === '' ? 0 : templateId);
    initQuotaGrid(templateId === '' ? 0 : templateId);
})

function saveData(callback) {
    // debugger
    $("#tbDimension").edatagrid('saveRow');
    $("#tbQuota").edatagrid('saveRow');
    if (!$("#form").form('validate')) {
        topWin.layer.msg("必填项未填写!")
        return
    }

    let postData = $("#form").serializeJson();
    var rowsDim = $("#tbDimension").edatagrid('getRows');
    var resultDim = [];
    for (var n = 0; n < rowsDim.length; n++) {
        var ob = {}, ite = rowsDim[n];
        ob.dimensionCode = ite.dimensionCode;
        ob.dimensionName = ite.dimensionName;
        ob.totalScore = ite.totalScore;
        ob.number = n;
        resultDim.push(ob);
    }
    postData.dimensions = resultDim;

    var rows = $("#tbQuota").edatagrid('getRows');
    var result = [];
    for (var i = 0; i < rows.length; i++) {
        var obj = {}, item = rows[i];
        obj.dimensionCode = item.dimensionCode;
        obj.dimensionName = item.dimensionName;
        obj.quotaCode = item.quotaCode;
        obj.quotaType = item.quotaType;
        obj.supplierFlag = item.supplierFlag;
        obj.quotaDesc = item.quotaDesc;
        obj.maxScore = item.maxScore;
        obj.calculationFormula = item.calculationFormula;
        obj.reportFlag = item.reportFlag;
        obj.evelSort = i;
        result.push(obj);
    }
    postData.quotas = result;

    $.ajax({
        url: g.ctx + 'pc/spe/supAppraiseTemplate/rest/saveOrUpdate',
        method: "POST",
        data: JSON.stringify(postData),
        contentType: 'application/json',
        success: function (data) {
            topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                topWin.layer.close(idx);
                callback();
            });
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}