/**
 * 问卷调查
 * */
Zepto(function($) {
	//获取乡镇
	getCounty();
	//获取问卷
	getPagers();
	//绑定提交按钮
	$("#submit").on('tap', submitHandle);
});

//提交
function submitHandle() {
	var telreg = /^\d{3,12}$/;
	var that = this;
	if(!$.trim($("#h_userName").val())) {
		mui.toast("请您输入姓名后再提交");
		return;
	}
	if(!$.trim($("#h_telphone").val())) {
		mui.toast("请您输入手机号码后再提交");
		return;
	}
	if($.trim($("#h_telphone").val())) {
		if(!telreg.test($.trim($("#h_telphone").val()))) {
			mui.toast("请您输入正确手机号码");
			return;
		}
	}

	var anArrs = getAnswers();
	$.ajax({
		type: "post",
		url: huayi.config.callcenter_url + 'WxLogin/AddPagers',
		async: true,
		beforeSend: function() {
			mui(that).button('loading');
		},
		data: {
			//openid: helper.cookies.get("openid"),//string	是
			openid: 'oKOqcvw24ZMtsRKlpjBFKHAWuDmI', ///测试 ID
			cusname: $('#h_userName').val(), //string	是	姓名
			telphone: $('#h_telphone').val(), //string	是	联系电话
			phone: $('#h_phone').val(), //string	否	固定电话
			countryid: $('#h_county').attr('data-index'), //int	否	乡镇	
			address: $('#h_address').val(), //string	否	住址			
			ans: anArrs, //string	否	答案，数组形式["15_20_单选选项内容","17_25|36|58_复选选项内容1|选项内容2|选项内容3","30_0_问答题"]*/
		},
		dataType: 'json',
		success: function(data) {
			mui(that).button('reset');
			if(data.state.toLowerCase() == "success") {
				mui.toast("提交成功");
				debugger
				window.location.href = 'WorkList.html';
			}
		},
		error: function(textStatus) {
			mui(that).button('reset');
			mui.toast('网络繁忙，请稍后再试...');
		},
		complete: function(XMLHttpRequest, textStatus) {
			mui(that).button('reset');
			if(textStatus == 'timeout') {
				var xmlhttp = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHttp");
				xmlhttp.abort();
				mui.toast('网络超时，请稍后再试...');
			}
		},
	});

}

//获取试题答案
function getAnswers() {
	/*单选 quesid_radio.val_radio.text;
	多选quesid_25|36|58_复选选项内容1|选项内容2|选项内容3
	问答题quesid_0_问题.text*/

	var anArr = [];
	var anForm = $('#questionBody').find('.queForm');
	anForm.forEach(function(v, i) {
		var str = '';
		var inputType = $(v).find('input').attr('type');

		if(inputType == 'radio') { //单选
			//单选 quesid_radio.val_radio.text;
			var radioName = $(v).find('input').attr('name');
			var radioQid = radioName && radioName.split('_')[1];
			var radioVal = $('input[name=' + radioName + ']:checked').val();
			var radioTxt = $('input[name=' + radioName + ']:checked').prev().text();
			if(radioVal && radioTxt) {
				str = radioQid + '_' + radioVal + '_' + radioTxt;
				anArr.push(str);
			}
		} else if(inputType == 'checkbox') { //多选
			//多选quesid_25|36|58_复选选项内容1|选项内容2|选项内容3
			var checkboxName = $(v).find('input').attr('name');
			var checkboxQid = checkboxName && checkboxName.split('_')[1];
			var checkboxCheckedEl = $('input[name=' + checkboxName + ']:checked');
			if(checkboxCheckedEl && checkboxCheckedEl.length > 0) {
				var cVal = '';
				var cTxt = '';
				checkboxCheckedEl.forEach(function(val, j) {
					cVal += '|' + $(val).val();
					cTxt += '|' + $(val).prev().text();
				});
				cVal = cVal && cVal.substring(1);
				cTxt = cTxt && cTxt.substring(1);
				str = checkboxQid + '_' + cVal + '_' + cTxt;
				anArr.push(str);
			}

		}
		//多选
		if($(v).find('textarea')) {
			var textareaName = $(v).find('textarea').attr('name');
			var textareaQid = textareaName && textareaName.split('_')[1];
			var textareaVal = $(v).find('textarea').val();
			if(textareaVal) {
				str = textareaQid + '_' + 0 + '_' + textareaVal;
				anArr.push(str);
			}
		}
	});
	return anArr;
}

//获取问卷
function getPagers() {
	$('#questionBody').empty();
	$.ajax({
		type: "get",
		url: huayi.config.callcenter_url + 'WxLogin/GetPagers',
		async: true,
		data: {
			//openid: helper.cookies.get("openid"),
			openid: 'oKOqcvw24ZMtsRKlpjBFKHAWuDmI', ///测试 ID
		},
		success: function(data) {
			data = JSON.parse(data);
			if(data.state.toLowerCase() == "success") {
				var res = data.data;
				if(res) {
					$('#que_header_title').text(res.F_Title); //问卷标题
					$('#que_header_content').text(res.F_Remark); //问卷说明
					var questions = res.F_Questions; //问卷的试题
					//questype 2单选 3 多选  1问答
					if(questions && questions.length > 0) {
						//遍历问卷的试题
						for(var i = 0; i < questions.length; i++) {
							var questype = questions[i].questype; //试题类型
							var quesid = questions[i].quesid; //试题id
							var quesitems = questions[i].quesitems; //试题选项
							var html = '';
							//根据试题的类型渲染页面
							if(questype == 2) {
								html = '<div class="mui-card">' +
									'<div class="mui-card-header">' +
									'<div class="qus_title"><span class="qus_type qus_radio">单选题</span>' + questions[i].questitle + '</div>' +
									'</div>' +
									'<form class="mui-input-group queForm">'
								if(quesitems && quesitems.length > 0) {
									for(var j = 0; j < quesitems.length; j++) {
										html += '<div class="mui-input-row mui-radio mui-left">' +
											'<label>' + quesitems[j].itemname + '</label>' +
											'<input name="radio_' + quesid + '" type="radio" value="' + quesitems[j].itemid + '">' +
											'</div>'
									}
								}
								html += '</form></div>';

							} else if(questype == 3) {
								html = '<div class="mui-card">' +
									'<div class="mui-card-header">' +
									'<div class="qus_title">' +
									'<span class="qus_type qus_check">多选题</span>' + questions[i].questitle +
									'</div>' +
									'</div>' +
									'<form class="mui-input-group queForm">'

								if(quesitems && quesitems.length > 0) {
									for(var k = 0; k < quesitems.length; k++) {
										html += '<div class="mui-input-row mui-checkbox mui-left">' +
											'<label>' + quesitems[k].itemname + '</label>' +
											'<input name="checkbox_' + quesid + '" value="' + quesitems[k].itemid + '" type="checkbox">' +
											'</div>'
									}
								}
								html += '</form></div>';
							} else if(questype == 1) {
								html = '<div class="mui-card">' +
									'<div class="mui-card-header">' +
									'<div class="qus_title">' +
									'<span class="qus_type qus_answer">问答题</span>' + questions[i].questitle +
									'</div>' +
									'</div>' +
									'<form class="mui-input-group queForm">' +
									'<div class="mui-input-row h_content">' +
									'<textarea name="textarea_' + quesid + '" class="mui-input-clear" placeholder="请输入。。。"></textarea>' +
									'</div>' +
									'</form>' +
									'</div>';

							}
							$('#questionBody').append(html);
						}
					}

				}

			}
		}
	});
}

//获取乡镇
function getCounty() {
	$.ajax({
		type: "get",
		url: huayi.config.callcenter_url + "WxLogin/GetAreaList",
		dataType: 'json',
		async: true,
		data: {
			openid: 'oKOqcvw24ZMtsRKlpjBFKHAWuDmI', //微信openid 测试用
			//openid: helper.cookies.get("openid"), 
		},
		success: function(data) {
			if(data.state.toLowerCase() == "success") {
				var res = data.data;
				if(res.length > 0) {
					//下拉弹出
					(function($, doc) {
						$.init();
						$.ready(function() {
							var t_countyDatas = [];
							res.forEach(function(item, index) {
								t_countyDatas.push({
									value: item.F_DictionaryValueId,
									text: item.F_Name
								});
							});
							var countyPicker = new $.PopPicker();
							countyPicker.setData(t_countyDatas);
							var showCountybtn = doc.getElementById('showCountyPicker');
							var countyRes = doc.getElementById('h_county');
							showCountybtn.addEventListener('tap', function(event) {
								countyPicker.show(function(items) {
									countyRes.value = items[0].text;
									countyRes.setAttribute("data-index", items[0].value);
								});
							}, false);

						});
					})(mui, document);
				}
			}
		}
	});
}