var param = getStorJson('fill_order_20170307');

var adult_count = 0;
window.onload = function() {
    for(var i=0;i<param.prod_arr.length;i++){
    	var obj=param.prod_arr[i];
    	if(obj['prod_name']==='成人票' || obj['prod_name']==='成人'){
    		adult_count += Math.floor(obj['prod_count']);
		}
	}
	ifLogin(function(flag) {
		$('body').show();
		httpLoadInfo();
	})

}

function httpLoadInfo() {
	//清空缓存
	//	param = {
	//		pro_cate_id: '1',
	//		if_back: '1', //只有去程 1  往返 2
	//		prod_arr: [{
	//			prod_id: '1',
	//			prod_count: '1',
	//			prod_name: "成人"
	//		}, {
	//			prod_id: '2',
	//			prod_count: '1',
	//			prod_name: "儿童"
	//		}],
	//		total_money: '340',
	//		go_info: {
	//			go_start_date: '2017-03-07',
	//			go_start_time: '07:30',
	//			go_run_id : '111',
	//			go_pro_cate_name: '中星君廷大酒店 - 迪士尼乐园'
	//		},
	//		back_info: {
	//			back_start_date: '2017-03-08',
	//			back_start_time: '07:30',
	//			back_run_id : '111',
	//			back_pro_cate_name: '迪士尼乐园 - 中星君廷大酒店'
	//		}
	//	}

	if(!param) {
		alert('缺少参数');
		$('body').hide();
		return;
	}
	$('body').show();


	//
	var html = '';
	for(var i=0;i<adult_count;i++){
		var tempHTML = '<div class="ui_p_t15 text_c_80">乘车人'+(i+1)+'</div>' +
							'<div class="ub ub-ver ui_p_t05 ui_p_b10 bor_b_e5">' +
								'<input style="width: 100%;" class="travel_people_name ulev1 text_c_2b" type="text" value="" placeholder="必填，姓名" />' +
							'</div>' +
							'<div class="ui_p_t15 text_c_80">乘车人'+(i+1)+'身份证</div>' +
							'<div class="ub ub-ver ui_p_t05 ui_p_b10 bor_b_e5">' +
								'<input maxlength="18" style="width: 100%;" class="travel_people_cardid ulev1 text_c_2b" type="text" placeholder="必填，身份证"/>' +
							'</div>';
		html+=tempHTML;
	}
	$('.travel_people_list').html(html);
	$('.travel_people_cardid').off('blur');
    $('.travel_people_cardid').on('blur',function(){
        var cardid = $(this).val();

        if(cardid!==""){
            var info = getCardIdInfo(cardid);
            if(info.flag===false){
                alert($(this).parent().prev().html()+'输入不正确');
                $(this).focus();
                return false;
            }
        }

    });



	//	param.if_back == '0' ? $('#back_info').hide() : $('#back_info').show();
	//去程信息
	var go_dict = param.go_info;
	var go_month = getMonthAndDayByDate(go_dict.go_start_date, 'month');
	var go_day = getMonthAndDayByDate(go_dict.go_start_date, 'day');
	$('.go_time').text('去程: ' + go_month + '月' + go_day + '日（' + go_dict.go_start_time + '）出发');
	$('.go_pro').text(go_dict.go_pro_cate_name);
	//返程信息
	if(param.if_back == '1') {
		var back_dict = param.back_info;
		var back_month = getMonthAndDayByDate(back_dict.back_start_date, 'month');
		var back_day = getMonthAndDayByDate(back_dict.back_start_date, 'day');
		$('.back_time').text('返程: ' + back_month + '月' + back_day + '日（' + back_dict.back_start_time + '）出发');
		$('.back_pro').text(back_dict.back_pro_cate_name);
		$('.back_info').show();
	} else {
		$('.back_info').hide();
	}

	$('#total_price').text(param.total_money);

	var arr = param.prod_arr;
	var HTML = '';
	for(var i = 0, m = arr.length; i < m; i++) {
		var dict = arr[i];
		var str = '';
		if(dict['prod_count'] == 0) {
			continue;
		}
		if(i != 0) {
			str = '</br>';
		}
		//		var tempHTML = `${str}<span class="text_c_2b ulev1">${dict['prod_count']}</span>
		//					<span class="text_c_2b ulev1 ui_m_r05">${dict['prod_name']}</span>`;
		var tempHTML = str + '<span class="text_c_2b ulev1">' + dict['prod_count'] + '</span>' +
			'<span class="text_c_2b ulev1 ui_m_r05">' + dict['prod_name'] + '</span>';
		HTML += tempHTML;
	}
	$('#person_count').html(HTML);
}
$(document).ready(function() {
	var timer_paysuccess = null; //实时刷是否支付
	var _pay_type = '1'; //微信支付：1    支付宝支付：2   预付款支付:3

	$('#wx_pay').on('click', function() {
		_pay_type = '1';
		resetPayTypeCSS()
		$('#wx_pay').removeClass('bor_pay_un');
		$('.p_wx').removeClass('pay_w_icon_unsel');
		$('#wx_pay').addClass('bor_pay');
		$('.p_wx').addClass('pay_w_icon_sel');

	})

//	$('#ali_pay').on('click', function() {
//		_pay_type = '2';
//		resetPayTypeCSS()
//		$('#ali_pay').addClass('bor_pay');
//		$('.p_ali').addClass('pay_z_icon_sel');
//		$('#ali_pay').removeClass('bor_pay_un');
//		$('.p_ali').removeClass('pay_z_icon_unsel');
//
//	})

	$('#advance_pay').on('click', function() {
		_pay_type = '3';
		resetPayTypeCSS()
		$('#advance_pay').addClass('bor_pay');
		$('.p_advance').addClass('pay_advance_icon_sel');
		$('#advance_pay').removeClass('bor_pay_un');
		$('.p_advance').removeClass('pay_advance_icon_unsel');
	})

	function resetPayTypeCSS() {
		$('#wx_pay').removeClass('bor_pay');
		$('.p_wx').removeClass('pay_w_icon_sel');
		$('#wx_pay').addClass('bor_pay_un');
		$('.p_wx').addClass('pay_w_icon_unsel');

//		$('#ali_pay').removeClass('bor_pay');
//		$('.p_ali').removeClass('pay_z_icon_sel');
//		$('#ali_pay').addClass('bor_pay_un');
//		$('.p_ali').addClass('pay_z_icon_unsel');

		$('#advance_pay').removeClass('bor_pay');
		$('.p_advance').removeClass('pay_advance_icon_sel');
		$('#advance_pay').addClass('bor_pay_un');
		$('.p_advance').addClass('pay_advance_icon_unsel');
	}

	//点击蒙板
	$('#close_cha').on('click', function() {
		closeDidClicked();
	})

	function closeDidClicked() {
		$('.model').fadeOut();
		$('.container-div').removeClass('mod_fil');
        $('body').css("position",'');
		clearInterval(timer_paysuccess);
		timer_paysuccess = null;
	}
	//去结算
	$('#go_settlement').on('click', function() {
		$('#qr_code_img').attr('src', 'images/base.png');
		$('#close_cha').hide();
		if(timer_paysuccess) {
            $('body').css("position",'');
			clearInterval(timer_paysuccess);
			timer_paysuccess = null;
		}

		var prod_arr = [];
		for(var i = 0, m = param['prod_arr'].length; i < m; i++) {
			var dict = param['prod_arr'][i];
			var obj = {
				prod_id: dict['prod_id'],
				prod_count: dict['prod_count']
			}
			prod_arr.push(obj);
		}

		var pro_cate_id = param.pro_cate_id ? param.pro_cate_id : "";
		var if_back = param.if_back ? param.if_back : "0";
		var prod_arr = JSON.stringify(prod_arr) ? JSON.stringify(prod_arr) : "";
		var total_money = param['total_money'] ? param['total_money'] : "";
		var contacts_name = $('#contacts_name').val();
		var contacts_phone = $('#contacts_phone').val();
		var pay_type = _pay_type ? _pay_type : '1';
		var start_date = param.go_info.go_start_date ? param.go_info.go_start_date : '';
		var start_time = param.go_info.go_start_time ? param.go_info.go_start_time : '';
		var run_id = param.go_info.go_run_id ? param.go_info.go_run_id : '';

		//add date:2017-04-01 13:45:07
		var back_run_id = "";
		var back_prod_arr = [];
		var back_start_date = "";
		var back_start_time = "";
		var back_pro_cate_id = "";
		var is_line = "";
		if(param['if_back'] != "0") {
			is_line = param['is_line'] ? param['is_line'] : "";
//			if(param['is_line'] == '1') {
				for(var i = 0, m = param['back_prod_arr'].length; i < m; i++) {
					var dict = param['back_prod_arr'][i];
					var obj = {
						prod_id: dict['prod_id'],
						prod_count: dict['prod_count']
					}
					back_prod_arr.push(obj);
				}
//			}
			back_run_id = param.back_info.back_run_id ? param.back_info.back_run_id : '';
			back_start_time = param.back_info.back_start_time ? param.back_info.back_start_time : '';
			back_start_date = param.back_info.back_start_date ? param.back_info.back_start_date : '';
			back_pro_cate_id = param['back_pro_cate_id'] ? param['back_pro_cate_id'] : '';
			back_prod_arr = JSON.stringify(back_prod_arr) ? JSON.stringify(back_prod_arr) : "";
		}

		if(pro_cate_id.trim().length <= 0) return;
		if(prod_arr.length <= 0) return;
		if(contacts_name.trim().length <= 0) {
			$('#contacts_name').focus();
			alert('请输入联系人姓名');
			return;
		}
		if(contacts_phone.trim().length != 11) {
			$('#contacts_phone').focus();
			alert('手机号格式不正确');
			return;
		}


        //乘车人
        var names = [];
        $('.travel_people_name').each(function(index,dom){
            var name = $(this).val();
            name!=="" && names.push(name);
        });
        var cardids = [];
        $('.travel_people_cardid').each(function(index,dom){
            var cardid = $(this).val();
            cardid!=="" && cardids.push(cardid);
        });

        if(cardids.length!==names.length){
            alert('请完善乘车人信息');
            return;
        }
        var passanger_arr = [];
        var allow_flag = true;
        for(var i=0;i<cardids.length;i++){
            var name = names[i];
            var cardid = cardids[i];

            if(name.trim()!==""){
            	var info = getCardIdInfo(cardid);
            	if(info.flag!==false){
                    passanger_arr.push({
                        passenger_name:name,
                        passenger_cardid:cardid
                    });
				}else{
                    allow_flag=false;
					// alert('乘车人'+Math.floor(i+1)+' 身份证号输入不正确');
					break;
				}
			}else{
            	if(passanger_arr.length<=0){
            		allow_flag = false;
            		alert('请填写乘车人'+(i+1)+'信息');
            		break;
				}
			}


            // if(name.trim()===""){
            //     allow_flag=false;
            //     alert('请填写乘车人'+Math.floor(i+1));
            //     return;
            // }
            //
            // var info = getCardIdInfo(cardid);
            // if(info.flag===false){
            //     allow_flag=false;
            //     alert('乘车人'+Math.floor(i+1)+' 身份证号输入不正确');
            //     return;
            // }
            //
            // passanger_arr.push({
            //     passenger_name:name,
            //     passenger_cardid:cardid
            // });
        }

		if(allow_flag===false)return;

		//补齐数组
		var len = adult_count-passanger_arr.length;
		for(var i=0;i<len;i++){
			passanger_arr.length>0 && passanger_arr.push(passanger_arr[0]);
		}

		if(_pay_type.trim().length <= 0) return;
		//		if(total_money.trim().length <= 0) return;
		if(_pay_type == '1') {
			$('.pay_type').addClass('weixin');
			$('.pay_type').removeClass('zhifubao');
			$('.qr_pay_type').text('微信扫码支付:');
			$('.container-div').addClass('mod_fil');
			$('.model').fadeIn();
		} else if(_pay_type == '2') {
			$('.pay_type').addClass('zhifubao');
			$('.pay_type').removeClass('weixin');
			$('.qr_pay_type').text('支付宝扫码支付:');
			$('.container-div').addClass('mod_fil');
			$('.model').fadeIn();
		} else if(_pay_type == '3') {
			var result = confirm('预付款支付   ' + param.total_money + '元');
			if(!result) return;
		} else {}
		$('#pay_money').text(total_money);
		var data = {
			pro_cate_id: pro_cate_id,
			back_pro_cate_id: back_pro_cate_id,
			if_back: if_back,
			is_line: is_line,
			prod_arr: prod_arr,
			back_prod_arr: back_prod_arr,
			contacts_name: contacts_name,
			contacts_phone: contacts_phone,
            passanger_arr: JSON.stringify(passanger_arr),
			pay_type: _pay_type,
			start_date: start_date,
			back_start_date: back_start_date,
			start_time: start_time,
			back_start_time: back_start_time,
			run_id: run_id,
			back_run_id: back_run_id
		}
		ZZLog(base_api + 'prod/prod/make-order', data);
		if(_pay_type==='1' || _pay_type==='2'){
            $('body').css("position",'fixed');
		}
		submit();

		function submit() {
			$.ajax({
				type: "post",
				url: base_api + 'prod/prod/make-order',
				data: data,
				dataType: 'json',
				//				traditional: true, //这里设置为true
				success: function(res_data) {
					ZZLog(res_data);
					if(false == res_data['flag']) {
						if(codeNotLogin == res_data['code']) {
							location.href = res_data['url'] + '/web/fx/';
							//							alert(infoNotLogin);
						} else if(codeNotRegister == res_data['code']) {
							location.href = 'register.html';
						} else {
							alert(res_data['msg']);
						}
						closeDidClicked();
					} else {
						if(_pay_type == '3') {
							location.href = 'pay_success.html';
							return;
						}
						var data = res_data['data'];
						var total_money = data['total_money'];
						var qr_code = data['qr_code'];
						var pay_type = data['pay_type'];
						var order_id = data['order_id'];

						if(pay_type == '1') {
							$('.pay_type').addClass('weixin');
							$('.pay_type').removeClass('zhifubao');
							$('.qr_pay_type').text('微信扫码支付:');
						} else if(pay_type == '2') {
							$('.pay_type').addClass('zhifubao');
							$('.pay_type').removeClass('weixin');
							$('.qr_pay_type').text('支付宝扫码支付:');
						}else{}
						$('#pay_money').text(total_money);
						$('#qr_code_img').attr('src', qr_code);

						$('#close_cha').show();
						timer_paysuccess = setInterval(ifPaySuccess, 3000);

						function ifPaySuccess() {
							var _data = {
								order_id: order_id
							}
							ZZLog(base_api + 'prod/prod/check-order', JSON.stringify(_data));
							$.ajax({
								type: "post",
								url: base_api + 'prod/prod/check-order',
								data: _data,
								dataType: 'json',
								success: function(res_data) {
									ZZLog(res_data);
									if(false == res_data['flag']) {
										if(codeNotLogin == res_data['code']) {
											var URL = '/web/fx/fill_order_unbus.html';
											URL = encodeURI(URL);
											location.href = res_data['url'] + URL;
											//											alert(infoNotLogin);
										} else {
											alert(res_data['msg']);
										}
									} else {
										//..
										var data = res_data['data'];
										var order_status = data['order_status'];
										//1:待支付   2:已支付
										if('2' == order_status) {
											closeDidClicked();
											setTimeout(function() {
												location.href = 'pay_success.html';
											}, 1000);
										}
									}
								},
								error: function() {
									alert(infoApiError);
								}
							});
						}
					}
				},
				error: function() {
					alert(infoApiError);
					closeDidClicked();
				}
			});
		}
	})

})