/**
 * 回访 问卷信息
 * */

var wid = helper.request.queryString("oid");
$(document).ready(function() {
	if(wid != null && wid != undefined && wid != "") {
		getWorkOrderInfo(); //获取工单信息
		GetHJJG(); //获取呼叫结果
		getQuestionPager(); //获取问卷
	}
//	$('#btn_submit').on('click', submitPages);
	$('#btn_submit').click(function(){
		submitPages();
	});
	//点击电话号码外呼
	$("#CallOut").click(function(event) {
		if($("#visit_tel").text()) {
			calloutopt($("#visit_tel").text());
		}
	});
});

//外呼
function calloutopt(telphone) {
	event.stopPropagation();
	if(telphone) {
		$.ajax({
			type: "get",
			url: huayi.config.callcenter_url + "CallOutOpt/GetCallOutprefix",
			async: true,
			dataType: 'json',
			data: {
				token: $.cookie("token"),
				phone: telphone
			},
			success: function(result) {
				if(result.state.toLowerCase() == "success") {
					var guid = uuid();
					$("#TelCode").val(guid);
					top.obj.Type = "MakeCall";
					top.obj.DestinationNumber = result.data.phone;
					top.obj.Header = result.data.fix;
					top.obj.TaskType = "1"; //0:拨号外呼；1:问卷外呼；
					top.obj.TaskPhoneID = $("#F_Id").val(); //回访的电话工单ID
					top.Send();
				}

			}
		});
	}
}

//提交问卷
function submitPages() {
//	if(!$('input[name="check"]:checked').val()) {
//		layer.confirm('呼叫结果必须选择！', {
//			icon: 2,
//			btn: ['确定']
//		});
//		return;
//	}
//	var ans = getAnswers(); //获取答案
	//请求
	$.ajax({
		type: "POST",
		url: huayi.config.callcenter_url + "WorkOrder/RBakWorkOrder",
		dataType: 'json',
		data: {
//			cusid: $("#F_CusID").val(), //客户档案ID
//			workorderid: wid, //	是	string	工单来源
//			ans: ans, //单选格式：试题Id_选项Id|总分(选项最大分数)|得分score|选项title
//			hjjgid: $('input[name="check"]:checked').val(), //呼叫结果ID
            orderid: wid,//	工单ID
            cont:$("#cont").val(),
			token: $.cookie("token")
		},
		async: true,
		success: function(data) {
			if(data.state === "success") {
				var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
				parent.layer.close(index); //再执行关闭
				parent.$('#workorderlist').bootstrapTable('refresh');
				parent.layer.msg('提交成功');
			}
		},
	});

}

//获取问卷
function getQuestionPager() {
	$(".tbody").empty();
	$.ajax({
		type: "get",
		url: huayi.config.callcenter_url + "QuestionAnswer/GetQuestionPager",
		async: true,
		dataType: "json",
		data: {
			token: $.cookie("token"),
		},
		success: function(data) {
			if(data.state.toLowerCase() == 'success') {
				var questions = data.data;
				var html = '';
				if(questions && questions.length > 0) {
					for(var i = 0; i < questions.length; i++) {
						html += '<li>';
						html += '<div class="Back">';
						html += '<h3 class="size-14 QuesTitle">' + questions[i].title + '</h3>';
						html += '</div>';
						//选项
						var quesitems = questions[i].quesitems;
						if(quesitems && quesitems.length > 0) { //单选
							html += '<div class="radio clearfix" id="radios_' + i + '">';
							html += '<ul class="Ul">'
							for(var j = 0; j < quesitems.length; j++) {
								html += '<li>'
								html += '<label style="font-weight: normal;">'
								html += '' + (j + 1) + '.';
								html += '<input type="radio" class="quesitems" value="' + quesitems[j].id + '" name="radio_' + questions[i].id + '"><span>' + quesitems[j].title + ' （' + quesitems[j].score + '分）</span></label>'
								html += '</li>'
							}
							html += '</ul>'
							html += '</div>'
							html += '</li>'
						}
					}
					$(html).appendTo("#questionBody");
				}
			}
		}
	});
}
function formatterState(val) {
	//工单状态0待指派，1待处理，2已处理 原来的状态 不用！！！！
	// 0新工单待指派，1已指派待接单，2已接单待处理，3已退回待处理，4异常退回待处理，5处理中，10已完结
	var stateStr = '-';
	var stateClass = '';
	switch(val) { 
		case 0:
			stateStr = '待指派';
			stateClass = 'audit_wait';
			break;
		case 1:
			stateStr = '待接单';
			stateClass = 'audit_refuse';
			break;
		case 2:
			stateStr = '待处理';
			stateClass = 'audit_revoke';
			break;
		case 3:
			stateStr = '已退回';
			stateClass = 'audit_termination'; 
			break;
		case 4:
			stateStr = '异常退回';
			stateClass = 'audit_termination';
			break;
		case 5:
			stateStr = '处理中';
			stateClass = 'audit_doned';
			break;
		case 10:
			stateStr = '已完结';
			stateClass = 'audit_done';
			break;
		case 12:
			stateStr = '已完结';
			stateClass = 'audit_doneti';
			break;
		default:
			break;
	}

	return '<span class="' + stateClass + '">' + stateStr + '</span>';
}
//获取工单信息
function getWorkOrderInfo() {
	$.getJSON(huayi.config.callcenter_url + 'WorkOrder/GetWorkOrder', {
		"orderid": wid,
		"token": $.cookie("token")
	}, function(result) {
		if(result.state.toLowerCase() == "success") {
			if(result.data.data && result.data.data.length > 0) {
				var data = result.data.data[0];
				$("#F_CusID").text(data.CustomerID), //客户档案ID
				$("#F_Id").text(data.ID); //回访的电话工单ID
				$("#visit_name").text(data.WorkOrderID); //客户姓名
				$("#visit_regdd").text(data.GDLXName); //工单类型
				$("#visit_shijian").text(data.CreateTime); //创建时间
				$('#visit_zhuangtai').html(formatterState(data.State)); //工单状态  
				$("#visit_Xigmin").text(data.Customer); //客户姓名
				$("#visit_tel").text(data.CustomerTel); //客户电话
				
				$("#xq_company").text(data.County); //公司名称

				$("#visit_regin").text(formatterIsEffective(data.IsEffective)); //工单有效性
				$("#visit_pro").text(data.GDLYName); //工单来源
				$('#xq_handle').text(data.YWLXName); //业务办理（业务类型）					
				$("#xq_responseUser").text(data.AuditUserNameRel); //接收人
				$("#visit_buildingnum").text(data.CreateUserName1); //创建人
				$("#visit_clcontent").text(data.clcontent); //处理内容
				$("#visit_detail").text(decodeURIComponent(data.Detail)); //反馈内容
				if(data.TypeClass === 107) { //咨询
					$('.visit_complain').hide();
				} else if(data.TypeClass === 108) { //投诉
					$('.visit_complain').show();
					data.ComplaintDepartment = data.ComplaintDepartment === null ? '' : data.ComplaintDepartment;
					data.CustomerTypeName = data.CustomerTypeName === null ? '' : data.CustomerTypeName;
					$("#visit_fkdep").text(data.ComplaintDepartment + data.CustomerTypeName); //投诉类型
					if(data.ResponDept != "-1") {
						data.ResponDept = data.ResponDept === 1 ? '是' : '否';
					} else {
						data.ResponDept = '保密';
					}
					$("#visit_isquality").text(data.ResponDept); //是否过质保
					data.AuditUserNameRel = data.AuditUserNameRel === "" ? '——' : data.AuditUserNameRel;
					$("#visit_responseUser").text(data.AuditUserNameRel); //接收人
				}
				$("#visit_code").text(data.CreateUserNameRel); //创建人
				$("#visit_detail").html(decodeURIComponent(data.Detail)); //反馈内容
				$("#visit_clcontent").html(decodeURIComponent(data.clcontent)); //处理内容
				if(data.IsEffective === 0) {
					$('.visit_notes').hide();
				} else {
					$('.visit_notes').show();
					$("#visit_note").text(data.Province); //无效原因
				}
			}
		}
	});
}

//格式化 工单状态
//function formatterState(val) {
//	var stateStr = '-';
//	var stateClass = '';
//	switch(val) { //工单状态0待指派，1待处理，2已处理
//		case 0:
//			stateStr = '待指派';
//			stateClass = 'audit_wait';
//			break;
//		case 1:
//			stateStr = '待处理';
//			stateClass = 'audit_revoke';
//			break;
//		case 2:
//			stateStr = '已处理';
//			stateClass = 'audit_done';
//			break;
//		default:
//			break;
//	}
//
//	return '<span class="' + stateClass + '">' + stateStr + '</span>';
//}

//格式化 工单有效性
function formatterIsEffective(val) {
	var stateStr = '-';
	var stateClass = '';
	switch(val) { //是否有效工单项(0有效，1无效)
		case 0:
			stateStr = '有效';
			stateClass = 'audit_done';
			break;
		case 1:
			stateStr = '无效';
			stateClass = 'audit_revoke';
			break;
		default:
			break;
	}
	return '<span class="' + stateClass + '">' + stateStr + '</span>';
}

//获取呼叫结果
function GetHJJG() {
	$.ajax({
		type: "get",
		url: huayi.config.callcenter_url + "Dictionary/GetDicValueListByFlag",
		dataType: 'json',
		data: {
			flag: 'HJJG',
			token: $.cookie("token")
		},
		async: true,
		success: function(data) {
			var Count = data.data;
			for(var i = 0; i < Count.length; i++) {
				var listItem = '<li>' +
					'<input id="listR_' + i + '" type="radio" name="check" value="' + Count[i].F_DictionaryValueId + '" />' +
					'<label for="listR_' + i + '">' + Count[i].F_Name + '</label>' +
					'</li>';
				$(listItem).appendTo($("#Tgetruset"));
			}
		}
	});
}

//获取试题答案
function getAnswers() {
	//单选格式：试题Id_选项Id|总分(选项最大分数)|得分score|选项title
	var anArr = [];
	var anForm = $('#questionBody').find('.radio');
	if(anForm && anForm.length > 0) {
		anForm.each(function(i, v) {
			var str = '';
			var radioScores = []; //放每个选项分数
			var inputType = $(v).find('input.quesitems').attr('type');
			if(inputType == 'radio') { //单选
				var radioName = $(v).find('input.quesitems').attr('name');
				var radioQid = radioName && radioName.split('_')[1]; //试题Id
				var radioVal = $(v).find('input[name=' + radioName + ']:checked').val(); //选项Id
				var radioTxt = $(v).find('input[name=' + radioName + ']:checked').siblings('span').text();
				var radioScore = (radioTxt && radioTxt.split(' （')[1]).substring(0, (radioTxt && radioTxt.split(' （')[1]).length - 2); //选项score
				var radioTitle = radioTxt && radioTxt.split(' （')[0]; //选项title
				var radioSpans = $(v).find('input[name=' + radioName + ']').siblings('span');
				radioSpans.each(function(j, n) {
					var radTxt = $(n).text();
					var radScorce = (radTxt && radTxt.split(' （')[1]).substring(0, (radTxt && radTxt.split(' （')[1]).length - 2); //选项score
					radioScores.push(radScorce);
				});
				var radioMaxScore = Math.max.apply(null, radioScores);
				if(radioQid && radioVal && radioMaxScore && radioScore && radioTitle) {
					str = radioQid + '_' + radioVal + '|' + radioMaxScore + '|' + radioScore + '|' + radioTitle;
					anArr.push(str);
				}
			}
		});
	}
	return anArr;
}