var windowId, proName = window.location.pathname.split("/")[1],
    sysUrl = "http://" + window.location.host + "/" + proName, toEdit, weightEdit;
var  ishistory=false;
$(function () {
    getmonth("pjyf");
    initGrid();
});

function getmonth(id) {
    var db1 = document.getElementById(id);
    var db = $(db1);
    db.datebox({
        onShowPanel: function () {//显示日趋选择对象后再触发弹出月份层的事件，初始化时没有生成月份层
            span.trigger('click'); //触发click事件弹出月份层
            //fix 1.3.x不选择日期点击其他地方隐藏在弹出日期框显示日期面板
            if (p.find('div.calendar-menu').is(':hidden')) p.find('div.calendar-menu').show();
            if (!tds) setTimeout(function () {//延时触发获取月份对象，因为上面的事件触发和对象生成有时间间隔
                tds = p.find('div.calendar-menu-month-inner td');
                tds.click(function (e) {
                    e.stopPropagation(); //禁止冒泡执行easyui给月份绑定的事件
                    var year = /\d{4}/.exec(span.html())[0];//得到年份
                    var month = parseInt($(this).attr('abbr'), 10); //月份，这里不需要+1
                    month = month < 10 ? '0' + month : month;
                    db.datebox('hidePanel')//隐藏日期对象
                        .datebox('setValue', year + '-' + month); //设置日期的值
                });
            }, 0);
            yearIpt.unbind();//解绑年份输入框中任何事件
        },
        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: function (d) {
            return d.getFullYear() + '-' + (d.getMonth() + 1);
        }
    });
    var p = db.datebox('panel'), //日期选择对象
        tds = false, //日期选择对象中月份
        aToday = p.find('a.datebox-current'),
        yearIpt = p.find('input.calendar-menu-year'),//年份输入框
//显示月份层的触发控件
        span = aToday.length ? p.find('div.calendar-title span') ://1.3.x版本
            p.find('span.calendar-text'); //1.4.x版本
    if (aToday.length) {//1.3.x版本，取消Today按钮的click事件，重新绑定新事件设置日期框为今天，防止弹出日期选择面板
        aToday.unbind('click').click(function () {
            var now = new Date();
            now = now < 10 ? '0' + now : now;
            db.datebox('hidePanel').datebox('setValue', now.getFullYear() + '-' + (now.toString() + 1));
        });
    }
}
//加载列表
function initGrid() {
    var toolbar = [{
        text: '查询',
        iconCls: 'icon-search',
        handler: doSearch
    }, {
        text: '增加',
        iconCls: 'icon-add',
        handler: doAdd
    }, {
        text: '修改',
        iconCls: 'icon-cut',
        handler: doEdit
    }, {
        text: '删除',
        iconCls: 'icon-delete',
        handler: doDelete
    }, {
        text: '权重分值设置',
        iconCls: 'icon-config',
        handler: updateWeightScore
    },
        {
            text: '权重信息管理',
            iconCls: 'icon-config',
            handler: function () {
                ishistory=false;
                addweight();
            }
        }
    ];

    $('#tableGrid').datagrid({
            toolbar: toolbar,
            rownumbers: true,
            singleSelect: true,
            queryParams: getQueryParams(),
            url: 'ywglbmkhAction!listYwglbmkhByPage.do',
            columns: [[
                {
                    field: 'A',
                    checkbox: 'true',
                    width: 30
                },
                {field: 'khdxbh', title: '编号', hidden: false, width: 120},
                {field: 'khdxmc', title: '名称', hidden: false, width: 120},
                {field: 'pjyf', title: '评价月份', hidden: false, width: 75},
                {field: 'score', title: '得分', hidden: false, width: 70},
                {field: 'cjrq', title: '创建时间', hidden: false, width: 200},
                {field: 'cjry', title: '创建人', hidden: false, width: 200},
                {field: 'xgrq', title: '修改时间', hidden: false, width: 200},
                {field: 'xgry', title: '修改人', hidden: false, width: 200},
                {field: 'bz', title: '备注', hidden: false, width: 200}
            ]]
        }
    );
}

//查询条件
function getQueryParams() {
    var sParam = {};
    sParam.khtype = $('#khlb').combobox("getValue");
    sParam.LIKEkhdxbh = $('#LIKEkhdxbh').textbox("getValue");
    sParam.LIKEkhdxmc = $('#LIKEkhdxmc').textbox("getValue");
    sParam.pjyf = $('#pjyf').datebox("getValue");
    return sParam;
}


//增加
function doAdd() {
    toEdit = false;
    windowId = top.$.createWin({
        title: '增加信息',
        width: 400,
        height: 400,
        data: {khlb: $('#khlb').combobox('getValue')},
        buttons: [{
            text: $.fn.textbox.defaults.ok,
            handler: saveNodeInfo
        }],
        url: sysUrl + "/yw/operationcount/videoarchivecount/orderpartmentcount/orderpartmentcount_show.jsp"
    });
}

//修改
function doUpdate(index) {
    toEdit = true;
    var selRows = $('#tableGrid').datagrid('getRows')[index];
    windowId = top.$.createWin({
        title: '修改信息',
        width: 400,
        height: 400,
        data: selRows,
        buttons: [{
            text: $.fn.textbox.defaults.ok,
            handler: saveNodeInfo
        }],
        url: sysUrl + "/yw/operationcount/videoarchivecount/orderpartmentcount/orderpartmentcount_show.jsp"
    });
}

//查询
function doSearch() {
    $("#monthlykpi").hide();
    $('#searchGridDiv').show();
    $('#searchweightGridDiv').hide();
    $('#historyWeightDiv').hide();
    $('#tableGrid').datagrid('load', getQueryParams());
}

function doDelete() {
    var selRows = $('#tableGrid').datagrid('getSelected');
    if (!selRows) {
        $.showMsg('请先选择记录! ');
        return;
    }
    top.$.dlg.confirm('确认删除?', function () {
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: 'ywglbmkhAction!delete_Ywglbmkh.do',
            data: {
                xh: selRows.xh
            },
            success: function (flag) {
                if (flag == "success") {
                    $.showMsg("操作成功！");
                    doSearch();
                } else {
                    $.showMsg("操作失败！");
                }
            }
        });
    });
}

//保存
function saveNodeInfo() {
    var win = $.getTopWindowById(windowId);
    var jq = win.$;
    var model = $.getFormValues("childform", windowId);
    var insertmodel = {};
//	console.log(model);
    if (!win.$('#childform').form('enableValidation').form('validate')) {
        return;
    }
    insertmodel = model;
    insertmodel.khdxbh = jq("#khdxbh").combobox('getValue');
    insertmodel.khdxmc = jq("#khdxbh").combobox('getText');
    insertmodel.XGTJxh = jq("#xh").val();
    insertmodel.khtype = jq("#khtype").val();
    if (toEdit) {//修改
        model.XGTJxh = jq('#xh').val();
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: 'ywglbmkhAction!update_Ywglbmkh.do',
            data: model,
            success: function (value) {
                if (value == "success") {
                    $.showMsg("操作成功！");
                    top.$("#" + windowId).dialog('close');
                    doSearch();
                } else if (value == "same") {
                    $.showMsg("已存在！");
                } else {
                    $.showMsg("操作失败！");
                }
            }
        });
    } else {
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: 'ywglbmkhAction!insert_Ywglbmkh.do',
            data: model,
            success: function (value) {
                if (value == "success") {
                    $.showMsg("操作成功！");
                    top.$("#" + windowId).dialog('close');
                    doSearch();
                } else if (value == "same") {
                    $.showMsg("已存在！");
                } else {
                    $.showMsg("操作失败！");
                }
            }
        });
    }
}

//打开修改
function doEdit() {
    var selIndex = $('#tableGrid').datagrid('getRowIndex', $("#tableGrid").datagrid('getSelected'));
    if (selIndex == -1) {
        $.showMsg('请先选择一行! ');

    } else {
        doUpdate(selIndex);
    }
}

function updateWeightScore() {
    $("#monthlykpi").show();
    $('#searchGridDiv').hide();
    $("#searchweightGridDiv").hide();
    $('#historyWeightDiv').hide();
    $("#postdata").text("");
    $("#tbody").html("");
    var totalsum = 0;
    var mapresult = new Map();
//查询月度考核信息，绑定到div中
    $.ajax({
        type: 'post',
        dataType: 'json',
        url: 'monthlyKPIAction!listMonthlyKPI.do',
        data: {},
        success: function (rows) {
            if (rows) {
                //拼接table
                var table = "";
                for (var f = 0; f < rows.length; f++) {
                    table = "";
                    table += " <tr><td>" + transformateEmpty(rows[f].targetdimension) + "</td>" +
                        " <td>" + transformateEmpty(rows[f].ordernum) + "</td>" +
                        " <td> " + transformateEmpty(rows[f].scope) + "</td> " +
                        " <td> " + transformateEmpty(rows[f].checkitem) + "</td> " +
                        " <td> " + transformateEmpty(rows[f].subitempoints) + "</td> " +
                        "<td width='110px'> <input type=\"text\" id=" + rows[f].id + " name=finalscore /></td></tr>";
                    $("#tbody").append(table);
                    $('#' + rows[f].id).numberbox({
                        min: 0,
                        max: rows[f].subitempoints,
                        precision: 0,
                        value: rows[f].finalscore,
                        onChange: function (n, o) {
                            mapresult.set(this.id, n);
                            totalsum = parseInt($("#totalsum").textbox('getValue'));
                            totalsum += (n - o);
                            $("#totalsum").textbox('setValue', totalsum);
                            $("#postdata").val(MapTOJson(mapresult));
                        }
                    });
                    totalsum += rows[f].finalscore;
                }
                $("#totalsum").textbox('setValue', totalsum);
            }
        }
    });

    function MapTOJson(m) {
        var str = '{';
        var i = 1;
        m.forEach(function (item, key, mapObj) {
            if (mapObj.size == i) {
                str += '"' + key + '":"' + item + '"';
            } else {
                str += '"' + key + '":"' + item + '",';
            }
            i++;
        });
        str += '}';
        return str;
    }

    // windowId = top.$.createWin({
    //     title: '权重信息',
    //     width: 900,
    //     height: 800,
    //     buttons: [{
    //         text: $.fn.textbox.defaults.ok,
    //         handler: saveWeightInfo
    //     }],
    //     url: sysUrl + "/yw/operationcount/videoarchivecount/orderpartmentcount/weight_show.jsp"
    // });

}

function saveWeightInfo() {
    if ($('#postdata').val() == "") {
        $.showMsg("无修改记录！");
        return;
    }
    $.ajax({
        type: 'post',
        dataType: 'json',
        url: 'monthlyKPIAction!batchupdateMonthlyKPI.do',
        data: {data: $('#postdata').val()},
        success: function (value) {
            if (value == "success") {
                $.showMsg("操作成功！");
                doSearch();
            } else if (value == "same") {
                $.showMsg("已存在！");
            } else {
                $.showMsg("操作失败！");
            }
        }
    });

}

function back() {
    $("#searchGridDiv").show();
    $('#monthlykpi').hide();
    $("#searchweightGridDiv").hide();
    $('#historyWeightDiv').hide();
}

function backtowehght() {
    $("#searchGridDiv").hide();
    $('#monthlykpi').hide();
    $("#searchweightGridDiv").show();
    $('#historyWeightDiv').hide();
}
function  getMaxVer(){
    $.ajax({
        type: 'post',
        dataType: 'json',
        url: 'monthlyKPIAction!maxMonthlyKPIByVer.do',
        success: function (value) {
            if (value && value.verlist) {
                $("#maxver").text(value.maxver);//版本最大值
                $("#usingver").text(value.usingver);//版本最大值
                var alarmTypeArr = [];
                for(var i=1;i<=parseInt(value.maxver);i++)
                {
                    alarmTypeArr.push({"id": i, "text": i});
                }
                $("#ver").combobox('loadData', alarmTypeArr);
            }
        }
    });
}
function transformateEmpty(str) {
    if (!str || str == null || str == "null") {
        return "";
    }
    return str;
}

function addweight() {
    getMaxVer();
    $("#searchGridDiv").hide();
    $('#monthlykpi').hide();
    $("#searchweightGridDiv").show();
    if (!ishistory){
        $('#historyWeightDiv').hide();
    }else {
        $('#historyWeightDiv').show();
    }

    var toolbar = [
        {
            text: '查询',
            iconCls: 'icon-search',
            handler: doWeightSearch
        }
    ];
   if(!ishistory){
    toolbar.push({
            text: '增加',
            iconCls: 'icon-add',
            handler: doWeightAdd
        }, {
            text: '修改',
            iconCls: 'icon-cut',
            handler: doWeightUpdate

        }, {
            text: '删除',
            iconCls: 'icon-delete',
            handler: doWeightDelete
        },
        {
            text: '历史版本管理',
            iconCls: 'icon-config',
            handler:function(){
                ishistory=true;
                addweight()
            }
        }
        ,
        {
            text: '返回考核',
            iconCls: 'icon-undo',
            handler: back
        })
} else {
        toolbar.push(
        {
            text: '返回权重管理',
            iconCls: 'icon-undo',
            handler: function() {
                ishistory=false;
                addweight();
            }

        });
}
    $('#tableWeightGrid').datagrid({
            toolbar: toolbar,
            rownumbers: true,
            singleSelect: true,
            queryParams: getWeightQueryParams(),
            url: 'monthlyKPIAction!listMonthlyKPIByVer.do',
            columns: [[
                {
                    field: 'A',
                    checkbox: 'true',
                    width: 30
                },
                {field: 'id', title: '编号', hidden: false, width: 120},
                {field: 'targetdimension', title: '指标维度', hidden: false, width: 120},
                {field: 'ordernum', title: '序号', hidden: false, width: 75},
                {field: 'scope', title: '适用范围', hidden: false, width: 70},
                {field: 'checkitem', title: '考核内容', hidden: false, width: 200},
                {field: 'checkitem', title: '考核指标及措施', hidden: false, width: 200},
                {field: 'subitempoints', title: '分项分值', hidden: false, width: 200},
                {field: 'finalscore', title: '分项得分', hidden: false, width: 200}

            ]]
        }

        //是否显示 操作按钮

    );

}
function doWeightSearch() {
    $("#monthlykpi").hide();
    $('#searchGridDiv').hide();
    $('#searchweightGridDiv').show();
    if(ishistory)$('#historyWeightDiv').show();
    else   $('#historyWeightDiv').hide();
    $('#tableWeightGrid').datagrid('load', getWeightQueryParams());
}
function dohistoryWeightSearch() {
    ishistory = true;
    $("#monthlykpi").hide();
    $('#searchGridDiv').hide();
    $('#searchweightGridDiv').show();
    $('#historyWeightDiv').show();
    $('#tableWeightGrid').datagrid('load', getWeightQueryParams());
}
function getWeightQueryParams() {
    var sParam = {};
    if(ishistory) {
        sParam.ver = $('#ver').combobox("getValue");
    }
    return sParam;
}

//增加
function doWeightAdd() {
    getMaxVer();
    weightEdit = false;
    windowId = top.$.createWin({
        title: '增加信息',
        width: 600,
        height: 300,
        buttons: [{
            text: $.fn.textbox.defaults.ok,
            handler: saveWeightNodeInfo
        }],
        url: sysUrl + "/yw/operationcount/videoarchivecount/orderpartmentcount/weight_show.jsp"
    });
}

//修改
function doWeightUpdate() {
    getMaxVer();
    var selIndex = $('#tableWeightGrid').datagrid('getRowIndex', $("#tableWeightGrid").datagrid('getSelected'));
    if (selIndex == -1) {
        $.showMsg('请先选择一行! ');
        return;
    }
    weightEdit = true;
    windowId = top.$.createWin({
        title: '修改信息',
        width: 600,
        height: 300,
        data: $('#tableWeightGrid').datagrid('getRows')[selIndex],
        buttons: [{
            text: $.fn.textbox.defaults.ok,
            handler: saveWeightNodeInfo
        }],
        url: sysUrl + "/yw/operationcount/videoarchivecount/orderpartmentcount/weight_show.jsp"
    });
}

function doWeightDelete() {
    getMaxVer();
    var selRows = $("#tableWeightGrid").datagrid('getSelected');
    if (selRows == -1) {
        $.showMsg('请先选择一行! ');
        return;
    }
    //删除文件信息，提醒是否生成新的版本
    top.$.dlg.confirm('确认删除?', function () {
        //遍历selIndex 获得xh
        var isnewver = "0";
        top.$.messager.defaults.ok = "是";
        top.$.messager.defaults.cancel = "否";
        top.$.messager.defaults.width = 350;//更改消息框宽度
        top.$.messager.confirm(
            '是否生成新的考核版本',
            '是否生成新的考核版本？'
            , function (r) {
                if (r) {
                    selRows.isnewver = "1";
                    $.ajax({
                        type: 'post',
                        dataType: 'json',
                        url: 'monthlyKPIAction!delete_MonthlyKPI.do',
                        data: selRows,
                        success: function (value) {
                            if (value == "success") {
                                $.showMsg("删除成功，新版本已生成！");
                                doWeightSearch();
                            }
                        }
                    });
                }else{
                    isnewver = "0";
                    $.ajax({
                        type: 'post',
                        dataType: 'json',
                        url: 'monthlyKPIAction!delete_MonthlyKPI.do',
                        data: {'isnewver': isnewver, keyword: selRows.id},
                        success: function (value) {
                            if (value == "success") {
                                $.showMsg("删除成功！");
                                doWeightSearch();
                            }
                        }
                    });
                }
            });
        top.$.messager.defaults.ok = "确定";
        top.$.messager.defaults.cancel = "取消";
        top.$.messager.defaults.width = 300;//改回消息框原宽度

    });

}

function enableWeight() {
    //
    var usingver = $("#ver").combobox("getValue");
    top.$.dlg.confirm('确认启用第' + usingver + '版考核标准？', function () {
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: 'monthlyKPIAction!update_MonthlyKPIByVer.do',
            data:{usingver:usingver},
            success: function (value) {
                if (value == "success") {
                    $.showMsg("操作成功！");
                    top.$("#" + windowId).dialog('close');
                    doWeightSearch();
                }
            }
        });
    });
}

//保存
function saveWeightNodeInfo() {
    var win = $.getTopWindowById(windowId);
    var jq = win.$;
    var model = $.getFormValues("weightform", windowId);
    var insertmodel = model;
    if (!win.$('#childform').form('enableValidation').form('validate')) {
        return;
    }
    if (parseInt(model.finalscore) > parseInt(model.subitempoints)) {
        $.showMsg("分项得分不能大于分项分值！");
        return;
    }
    //判断选择的版本号，最大版本号为空，则从1 开始
    insertmodel.maxver = $("#maxver").text();
    insertmodel.ver = $("#ver").combobox('getValue');//当前历史版本号
    insertmodel.usingver = $("#usingver").text();//当前选择版本号
    insertmodel.isnewver = jq("#isnewVer").combobox('getValue');//当是否生成新版本
    if (weightEdit) {//修改
        insertmodel.XGTJid = jq("#id").val();
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: 'monthlyKPIAction!update_MonthlyKPIByVer.do',
            data: insertmodel,
            success: function (value) {
                if (value == "success") {
                    $.showMsg("操作成功！");
                    top.$("#" + windowId).dialog('close');
                    doWeightSearch();
                } else if (value == "same") {
                    $.showMsg("已存在！");
                } else {
                    $.showMsg("操作失败！");
                }
            }
        });
    } else {
        $.ajax({
            type: 'post',
            dataType: 'json',
            url: 'monthlyKPIAction!insert_MonthlyKPIByVer.do',
            data: insertmodel,
            success: function (value) {
                if (value == "success") {
                    $.showMsg("操作成功！");
                    top.$("#" + windowId).dialog('close');
                    doWeightSearch();
                } else if (value == "same") {
                    $.showMsg("已存在！");
                } else {
                    $.showMsg("操作失败！");
                }
            }
        });
    }
}