var m_QuestionGroupCache = [];
var m_SelectQuestionGroupId = "";
var m_Prologue = "";
$(function () {
    $("#myPageAlert").hide();
    $("#divWelcome").hide();

    BindGroup();
    //homeObj.getautoreplay();
    //homeObj.getprologue();
    robatcss();
    $(function () { $("[data-toggle='tooltip']").tooltip(); });
});

function robatcss() {
    $(".left").css({
        height: $(window).height()
    });
    $(".right").css({
        height: $(window).height()
    });
    $(".robat-content").css({
        height: $(window).height()
    });
    $(".table-responsive").css({
        height: $(window).height() - 60
    });
    $(".talklist-m").css({
        height: $(window).height() 
    });
    $(".robat-default").css({
        height: $(window).height()-100
    });
    $(".rob-type-list-l").css({
        height: $(window).height() - 68
    });
    $("#divContent").css({
        height: $(window).height() - 125
    });
    
    
}
$(window).resize(function () {
    robatcss();
});
function AsyncGetAutoReplayResult(jsonResult) {
    if (jsonResult.success) {
        if (jsonResult.result.ishave) {
            $("#cbxIsOpen").prop("checked", jsonResult.result.info.isopen);
            $("#selectStartHour").val(jsonResult.result.info.starthour);
            $("#selectStartM").val(jsonResult.result.info.startminute);
            $("#selectEndHour").val(jsonResult.result.info.endhour);
            $("#selectEndM").val(jsonResult.result.info.endminute);
        } else {
            //设置checked为不选中
            $("#cbxIsOpen").prop("checked", false);
            //四个select的初始值设置为0
            $("#selectStartHour").val(0);
            $("#selectStartM").val(0);
            $("#selectEndHour").val(0);
            $("#selectEndM").val(0);
        }
    }
    $("#AutoReplayConfigModel").modal("show");
}

function BindGroup() {
    $(".loading").show();
    $(".loadingcover").show();
    var strJson = $.toJSON({ source: 1 });
    homeObj.getquizgrouplist(strJson);
}

//获取知识库组名称
function GetGroupName(groupid) {
    for (var i = 0; i < m_QuestionGroupCache.length; i++) {
        if (m_QuestionGroupCache[i].qgid == groupid) {
            return m_QuestionGroupCache[i].qgname;
        }
    }
    return "-";
}

//获取知识库组回调
function AsyncGetQuizGroupListResult(jsonResult) {
    if (jsonResult.success) {
        var objselectGroup = $("#selectGroup");
        objselectGroup.empty();//清空

        m_QuestionGroupCache = jsonResult.result.list;
        strTreeContent += "<ul class=\"list-unstyle\">";
        var strTreeContent = "<li id='groupall' onclick=\"SelectGroup('');\" class=\"list-header-l list-selected-l\"><i class=\"fa fa-list\" aria-hidden=\"true\"></i> 全部分类</li>";//树型菜单内容
        for (var i = 0; i < jsonResult.result.list.length; i++) {
            var item = jsonResult.result.list[i];
            strTreeContent += "<li id=\"" + item.qgid + "\" onclick=\"SelectGroup('" + item.qgid + "');\">" + item.qgname + "<span>(" + item.count + ")</span></li>";
                
            objselectGroup.append("<option value='" + item.qgid + "'>" + item.qgname
                + "</option>");
        }
        strTreeContent += "</ul>";
        $("#divulQuestionGroupList").html(strTreeContent);

        BindData();
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }

    $(".loadingcover").hide();
    $(".loading").hide();
}
//选择组
function SelectGroup(qgid) {
    nPageIndex = 0;
    m_SelectQuestionGroupId = qgid;
    BindData();
   
    $("#divulQuestionGroupList").find("li[class='list-header-l list-selected-l']").removeClass("list-selected-l");
    $("#divulQuestionGroupList").find("li[class='list-selected-l']").removeClass("list-selected-l");
  
    if (qgid.length > 0) {
        $("#" + qgid).addClass("list-selected-l list-selected-l");
    } else {
        $("#groupall").addClass("list-selected-l list-selected-l");
    }
}

//查询
function BindData() {
    $("#txtQueryQuestion").val($.trim($("#txtQueryQuestion").val()));

    var strJson = $.toJSON({
        groupid: m_SelectQuestionGroupId,
        question: $("#txtQueryQuestion").val(),
        source: 1,
        pageindex: nPageIndex,
        pagesize: nPageSize
    });
    homeObj.getquestionlist(strJson);
}

//查询列表回执
function AsyncGetQuestionListResult(jsonResult) {
    if (jsonResult.success) {
        if (jsonResult.result.list.length > 0) {
            var strContent = "";
            nPageCount = Math.ceil(Number(jsonResult.result.total) / nPageSize);
            strContent += "<table class=\"table table-hover\" style=\"width:100%\"><tr>";
            strContent += GetTableHeadNoOrderStr("序号");
            strContent += GetTableHeadNoOrderStr("分类");
            strContent += GetTableHeadNoOrderStr("关键字");
            strContent += GetTableHeadNoOrderStr("回复");
            strContent += GetTableHeadNoOrderStr("操作");
            strContent += "</tr>";

            for (var i = 0; i < jsonResult.result.list.length; i++) {
                var item = jsonResult.result.list[i];
                var strTrClass = i % 2 == 0 ? "even" : "odd";
                var qanswer = "";
                var qquestion = "";
                qanswer = item.qanswer.length > 25 ? item.qanswer.substring(0, 25) + "..." : item.qanswer;
                qquestion = item.qquestion.length > 15 ? item.qquestion.substring(0, 15) + "..." : item.qquestion;
                strContent += "<tr style=\"cursor:pointer\" class=\"" + strTrClass + "\">";
                strContent += "<td><p style=\"width:50px\">" + item.index + "</p></td>";
                strContent += "<td><p style=\"width:80px\">" + GetGroupName(item.qgid) + "</p></td>";
                strContent += "<td><p style=\"width:180px\">" + qquestion + "</p></td>";
                strContent += "<td><p style=\"width:280px\">" + qanswer + "</p></td>";
                strContent += "<td class=\"form-inline rob-modify\"><a href='javascript:void(0);' onclick=\"ShowEditModel(1, '" + item.qgid + "', '" + item.qid + "', '" + escape(item.qquestion) + "', '" + escape(item.qanswer) + "','" + item.isopen + "','" + item .sleeptime+ "');\">修改</a> | <a href='javascript:void(0);' onclick=\"ShowDeleteModel('" + item.qid + "','" + escape(item.qquestion) + "');\">删除</a></td>";
                strContent += "</tr>";
            }

            strContent += "</table>";

            $("#divNoData").hide();
            $("#divContent").html(strContent);
            $("#DivFooter").html(GetPageFootStr(nPageIndex, jsonResult.result.total));
            $("#DivFooter").show();
        } else {
            $("#divContent").html("");
            $("#divNoData").show();
            $("#DivFooter").hide();
        }
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
}

function ShowEditModel(type, qgid, qid, question, answer,isopen,sleeptime) {
    //重置界面
    $("#hidEditQuestionId").val("");
    $("#txtQuesion").val("");
    $("#txtAnswer").val("");
    $("#selectGroup").prop('selectedIndex', 0);
    $("#selInterval").attr("disabled", true);
    $("#ckOpenDelayed").attr("checked", false);
    $("#selInterval").val("");
    var isOpen = isopen == "0" ? false : true;
    if (type == 1) {
        //修改
        $("#selectGroup").val(qgid);
        $("#hidEditQuestionId").val(qid);
        $("#txtQuesion").val(unescape(question));
        $("#txtAnswer").val(unescape(answer));
        $("#ckOpenDelayed").prop("checked", isOpen);
        if (isOpen) {
        	$("#selInterval").removeAttr("disabled");
        } else {
        	$("#selInterval").attr("disabled", true);
        }
        


        if (sleeptime == "5") {
        	$("#selInterval").prop('selectedIndex', 0);
        } else if (sleeptime == "10") {
        	$("#selInterval").prop('selectedIndex', 1);
        } else if (sleeptime == "20") {
        	$("#selInterval").prop('selectedIndex', 2);
        } else {
        	$("#selInterval").val("");
        }
    }
    $("#EditModal").modal("show");
}

//提交
function SetEdit() {
    var objselectGroup = $("#selectGroup");
    var objhidEditQuestionId = $("#hidEditQuestionId");
    var objtxtQuesion = $("#txtQuesion");
    var objtxtAnswer = $("#txtAnswer");
    var bisOpen = $("#ckOpenDelayed").is(':checked');
    var strsleepyime = $("#selInterval")

    objhidEditQuestionId.val($.trim(objhidEditQuestionId.val()));
    objtxtQuesion.val($.trim(objtxtQuesion.val()).replace(/["]/g, '').replace(/[']/g, ''));
    objtxtAnswer.val($.trim(objtxtAnswer.val()).replace(/["]/g, '').replace(/[']/g, ''));

    if (objselectGroup.val().length == 0) {
        ShowError("myPageAlert", "没有问题组，请您先维护问题组再进行添加问题库！");
        return;
    }

    if (objtxtQuesion.val().length == 0 || objtxtAnswer.val().length == 0) {
        ShowError("myPageAlert", "问题和答案均不可以为空！");
        return;
    }

    if (objtxtAnswer.val().length > 400) {
        ShowError("myPageAlert", "回复内容长度不能超过400！");
        return;
    }
    var sleep = "";
    if (!bisOpen) {
    	sleep = "";
    }else{
    	sleep = strsleepyime.val();
    }
    var stropen = bisOpen ? 1 : 0;

    if (objhidEditQuestionId.val().length > 0) {
        var strJson = $.toJSON({
            qgid: objselectGroup.val(),
            qid: objhidEditQuestionId.val(),
            qquestion: objtxtQuesion.val(),
            qanswer: objtxtAnswer.val(),
            isopen: stropen,
            sleeptime: sleep,
        	sort:""
        });
        homeObj.updatequiz(strJson);
    } else {
        //添加
        var strJson = $.toJSON({
            qgid: objselectGroup.val(),
            qquestion: objtxtQuesion.val(),
            qanswer: objtxtAnswer.val(),
            type: 1,
            isopen: stropen,
            sleeptime: sleep,
			sort:""
        });
        homeObj.addquiz(strJson);
    }
}

function AsyncAddQuizResult(jsonResult) {
    if (jsonResult.success) {
        $("#EditModal").modal("hide");
        BindGroup();
        ShowMsg("myPageAlert", "操作成功！");
    } else {
        ShowError("myPageAlert", "操作失败：" + jsonResult.error);
    }
}

function AsyncUpdateQuizResult(jsonResult) {
    if (jsonResult.success) {
        $("#EditModal").modal("hide");
        BindGroup();
        ShowMsg("myPageAlert", "操作成功！");
    } else {
        ShowError("myPageAlert", "操作失败：" + jsonResult.error);
    }
}

//删除
function ShowDeleteModel(qid, question) {
    $("#hidDeleteQuesionts").val(qid);
    $("#spDeleteQuestion").html("确认要删除【" + unescape(question) + "】吗？");
    $("#DeleteModal").modal("show");
}

//确认删除
function SetDelete() {
    var objhidDeleteQuesionts = $("#hidDeleteQuesionts");

    objhidDeleteQuesionts.val($.trim(objhidDeleteQuesionts.val()));

    if (objhidDeleteQuesionts.val().length == 0) {
        ShowError("myPageAlert", "参数错误！");
        return;
    }
    var strJson = $.toJSON({
        qid: objhidDeleteQuesionts.val()
    });
    homeObj.deletequiz(strJson);
}

function AsyncDeleteQuizResult(jsonResult) {
    if (jsonResult.success) {
        $("#DeleteModal").modal("hide");
        ShowMsg("myPageAlert", "操作成功！");
        BindGroup();
    } else {
        ShowError("myPageAlert", "操作失败：" + jsonResult.error);
    }
}

//设置配置
function SetAutoReplayConfig() {
    var objcbxIsOpen = $("#cbxIsOpen");
    var objselectStartHour = $("#selectStartHour");
    var objselectStartM = $("#selectStartM");
    var objselectEndHour = $("#selectEndHour");
    var objselectEndM = $("#selectEndM");
        
    var strJson = $.toJSON({
        isopen: objcbxIsOpen.is(":checked"),
        starthour: objselectStartHour.val(),
        endhour: objselectEndHour.val(),
        startminute: objselectStartM.val(),
        endminute: objselectEndM.val()
    });
    homeObj.setautoreplay(strJson);
}

function AsyncSetAutoReplayResult(jsonResult) {
    if (jsonResult.success) {
        $("#AutoReplayConfigModel").modal("hide");
        ShowMsg("myPageAlert", "操作成功！");
    } else {
        ShowError("myPageAlert", "操作失败：" + jsonResult.error);
    }
}
//获取开场白回调
function AsyncGetPrologueResult(jsonResult) {
    if (jsonResult.success && jsonResult.result.ishave == true) {
        $("#cbxOpeningIsOpen").prop("checked", jsonResult.result.info["isopen"]);
        $("#txtOpeningText").val(jsonResult.result.info["sendbody"]);
        m_Prologue = jsonResult.result.info["sendbody"]
    } else {
        //设置checked为不选中
        $("#cbxOpeningIsOpen").prop("checked", false);
        //textarea内容清空
        $("#txtOpeningText").val("");
    }
    $("#AutoOpeningModel").modal("show");
}

//设置开场白
function SetOpeningConfig() {
    var Isprologue = $("#cbxOpeningIsOpen").is(":checked");
    var prologue = $("#txtOpeningText");
    if (prologue.val().length < 1) {
        ShowMsg("myPageAlert", "开场白内容不可为空，可以关闭开场白功能！");
        return;
    }
    //var pattern = new RegExp("~'#$^&*");
    //if (pattern.test(prologue.val())) {
    //    ShowMsg("myPageAlert", "不可包含特殊字符！");
    //    $("#txtOpeningText").val(m_Prologue);
    //    return;
    //}
    var strJson = $.toJSON({
        isopen: Isprologue,
        sendbody: prologue.val()
    });
    homeObj.setprologue(strJson);
}
function AsyncSetPrologueResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "操作成功！");
    } else {
        ShowError("myPageAlert", "操作失败：" + jsonResult.error);
    }
    $("#AutoOpeningModel").modal("hide");
}

//getprologue
//setprologue

//设置关键字回复时间单击事件
function RobatShow() {
    homeObj.getautoreplay();
}
//设置开场白单击事件
function OpeningRemarks() {
    homeObj.getprologue();
}
//机器人自动回复，开启时间间隔
function OpenDelayed() {
	var bisOpen = $("#ckOpenDelayed").is(':checked');
	var strsleeptime = $("#selInterval");
	if (bisOpen) {
		$("#selInterval").removeAttr("disabled");
		if (strsleeptime.val() == null) {
			$("#selInterval").prop('selectedIndex', 0);
		}
	} else {
		$("#selInterval").attr("disabled", true);
		$("#selInterval").val("");
	}
	
}