var state_type = "";
var prod_name = "";
var recom_type = "";
var current_page = 1;
var page_size = 10;
var pro_cate_id = "";
var img_url = "";

var file_name = '';

var price_html = '<div class="price">' +
	'<div style="margin-bottom: 5px;" class="form-group">' +
	'<input type="text" class="form-control pro_price_type" id="" >' +
	'</div>' +
	' <div style="margin-bottom: 5px;" class="form-group">' +
	'<div class="input-group">' +
	'<input class="form-control pro_price" type="text" >' +
	'<div class="input-group-addon">元</div>' +
	'</div>' +
	' </div>' +
	' <button  type="button" style="margin-bottom: 5px;" class="btn btn-danger btn-xs del_price">删除</button>' +
	'</div>'
$(document).ready(function() {
	host = window.location.host;
	host2 = document.domain;
	console.log(host);
	console.log(host2);
	base_info();
	get_product_list();
	$('#sale_hour').html(getOptHtml());
});

//产品基础信息
function base_info() {
	$.ajax({
		url: base_api + "prod/prod/get-cms-category", //请求地址
		data: {},
		type: "post",
		dataType: "json",
		async: false,
		success: function(data) {
			ZZLog(data)
			if(data.flag) {
				base_html(data.data);
			} else {
				ZZAlertInfo(data['msg'], function() {
					ifLogin(data);
				});
			}
		},
		error: function(error) {
			ZZAlertInfo(infoApiError);
		}
	});
}

//获取产品列表数据
function get_product_list() {
	state_type = $("#select_type").val();
	prod_name = $("#prod_name").val();
	recom_type = $("#recom_type").val();
	$.ajax({
		url: base_api + "prod/prod/prod-list", //请求地址
		data: {
			cms_category_id: state_type,
			is_recom: recom_type,
			pro_cate_name: prod_name,
			current_page: current_page,
			page_size: page_size
		},
		type: "post",
		dataType: "json",
		async: false,
		success: function(data) {
			ZZLog(data)
			if(data.flag) {
				product_list_html(data.data);
				create_page(data.data.page);
			} else {
				ZZAlertInfo(data['msg'], function() {
					ifLogin(data);
				});
			}
		},
		error: function(error) {
			ZZAlertInfo(infoApiError);
		}
	});
}

//生成产品基础信息
function base_html(data) {
	//产品分类
	var temp = '<option value="">全部</option>';
	for(var i = 0, j = data.cms_category.length; i < j; i++) {
		temp += '<option value="' + data.cms_category[i].cms_category_id + '">' + data.cms_category[i].category_name + '</option>'
	}
	$("#select_type").html(temp);
	//产品类型
	var temp2 = '';
	for(var i = 0, j = data.base_category.length; i < j; i++) {
		temp2 += '<option value="' + data.base_category[i].category_id + '">' + data.base_category[i].category_name + '</option>'
	}
	$("#base_prod").html(temp2);
	//不能新增车票新增
	$("#base_prod option[value=1]").remove();
	$("#base_prod_edit").html(temp2);
	//新增产品分类
	var temp3 = '<option value="-1">自定义</option>';
	for(var i = 0, j = data.cms_category.length; i < j; i++) {
		temp3 += '<option value="' + data.cms_category[i].cms_category_id + '">' + data.cms_category[i].category_name + '</option>'
	}
	$("#prod_classify").html(temp3);
	$("#prod_classify_edit").html(temp3);

	$("#prod_classify").on("change", function() {
		var cms_category_id = $(this).val();
		if(cms_category_id <= "0") {
			$(".custom_prod").show();
		} else {
			$(".custom_prod").hide();
		}
	});
	$("#prod_classify_edit").on("change", function() {
		var cms_category_id = $(this).val();
		if(cms_category_id <= "0") {
			$(".custom_prod_edit").show();
		} else {
			$(".custom_prod_edit").hide();
		}
	});

}

//生成产品列表
function product_list_html(data) {
	var temp = '';
	for(var i = 0, j = data.prod_list.length; i < j; i++) {
		var prodOBJ = data.prod_list[i];
		var price_temp = "";
		var commission_temp = "";
		var recom = (prodOBJ.is_recom_id == 0) ? "推荐" : "取消推荐";
		for(var h = 0, k = prodOBJ.price_name.length; h < k; h++) {
			var dict = prodOBJ.price_name[h];
			price_temp += dict['prod_name'] + '&nbsp;(价格:' + dict['prod_price'] + '元&nbsp;/&nbsp;佣金:' + dict['commission'] + '元)<br/>';
			//			price_temp += dict['prod_name'] + '&nbsp;(价格:' + dict['prod_price'] + '&nbsp;/&nbsp;佣金:'+dict['commission']+'元)<br/>';
		}
		var cstr1 = '提前' + prodOBJ.sale_day + '天';
		var s_hour = prodOBJ.sale_hour;
		if(s_hour < 10) {
			cstr1 += '0' + s_hour + ':00前';
		} else {
			cstr1 += s_hour + ':00前';
		}
		temp += '<tr>' +
			'<td>' + prodOBJ.pro_cate_id + '</td>' +
			'<td>' + prodOBJ.category_name + '</td>' +
			'<td>' + prodOBJ.base_category + '</td>' +
			'<td>' + prodOBJ.pro_cate_name + '</td>' +
			//TODO
			'<td>' + cstr1 + '</td>' +
			'<td>' + price_temp + '</td>' +
//			'<td style="display:none;" id="com' + prodOBJ.pro_cate_id + '">' + prodOBJ.commission + '</td>' +
			'<td>' +
			'<button dict=' + JSON.stringify(prodOBJ.price_name) + ' c_price="' + prodOBJ.commission + '" pro_cate_id="' + prodOBJ.pro_cate_id + '" type="button" class="btn btn-info btn-xs mar_r com_price" data-toggle="modal" data-target=".bs-example-modal-sm">自定义佣金</button>' +
			'<button edit_data_no="' + i + '" type="button" class="btn btn-success btn-xs mar_r edit" data-toggle="modal" data-target=".bs-example-modal-bj">编辑</button>' +
			'<button id="' + prodOBJ.pro_cate_id + '" recom_id="' + prodOBJ.is_recom_id + '" type="button" class="btn btn-default btn-xs mar_r is_recom">' + recom + '</button>' +
			'</td>' +
			'</tr>'
	}
	$("#prod_list").html(temp);

	$(".com_price").on("click", function() {
		
		//自定义佣金弹层
		var ticket_arr = $(this).attr('dict');
		ticket_arr = JSON.parse(ticket_arr);
		
		pro_cate_id = $(this).attr("pro_cate_id");
//		$("#com_price").val($(this).attr("c_price"));
		var temp_com_price = 0;
		if(ticket_arr.length!=0) temp_com_price = ticket_arr[0]['commission'];
		for (var i=0,m=ticket_arr.length;i<m;i++) {
			var v = ticket_arr[i];
			if(temp_com_price!=parseInt(v['commission'])){
				$("#com_price").val(0);
				$('#com_tab').children().eq(0).removeClass('active');
				$('#com_tab').children().eq(1).addClass('active');
				
				$('#one_key').removeClass('active');
				$('#ticket_setting').addClass('active');
				break;
			}else{
				$("#com_price").val(v['commission']);
				
				$('#com_tab').children().eq(0).addClass('active');
				$('#com_tab').children().eq(1).removeClass('active');
				
				$('#one_key').addClass('active');
				$('#ticket_setting').removeClass('active');
			}
		}
		

		
		var ticket_html = '';
		ticket_arr.forEach(function(v, i) {
			var cstr = `<div class="one_line" style="margin:0 10px 10px 10px;">
						<span style="display: inline-block;width:200px;text-align: right;">${v.prod_name}：</span>
						<div class="form-group">
							<div style="width: 130px;" class="input-group">
								<input data-prod-id=${v.prod_id} value=${v.commission} class="form-control ticket_commission" type="text" placeholder="佣金" onkeyup="this.value=this.value.replace(/[^0-9Xx]/g,'')" onafterpaste="this.value=this.value.replace(/[^0-9Xx]/g,'')" />
								<div class="input-group-addon">元</div>
							</div>
						</div>
					</div>`;
			ticket_html += cstr;
		})
		$('#ticket_setting').children().eq(0).html(ticket_html);

	});
	$(".edit").on("click", function() {
		var edit_data_no = $(this).attr("edit_data_no");
		var edit_data = data.prod_list[edit_data_no];
		pro_cate_id = edit_data.pro_cate_id;
		edit_info(edit_data);
	});
	$(".is_recom").on("click", function() {
		var cate_id = $(this).attr("id");
		var recom_id = $(this).attr("recom_id");
		$.ajax({
			url: base_api + 'prod/prod/recom-prod', //请求地址
			data: {
				pro_cate_id: cate_id
			},
			type: "post",
			dataType: "json",
			async: false,
			success: function(data) {
				ZZLog(data)
				if(data.flag) {
					get_product_list();
				} else {
					ZZAlertInfo(data['msg'], function() {
						ifLogin(data);
					});
				}
			},
			error: function(error) {
				ZZAlertInfo(infoApiError);
			}
		});

	});
}

function create_page(page) {
	$(".pageDiv").createPage({
		pageCount: page.total_pages, //总页数
		current: current_page, //当前页
		turndown: 'true', //是否显示跳转框，显示为true，不现实为false,一定记得加上引号...
		backFn: function(p) {
			current_page = p;
			get_product_list();
			//这里是翻页后的请求
		}
	});
}
//添加、删除价格和价格类型
$("#new_prod").on("click", function() {
	$("#add_price_type").append(price_html);
	$(".del_price").on("click", function() {
		$(this).closest(".price").remove();
	});
});
//添加、删除价格和价格类型
$("#new_prod_edit").on("click", function() {
	$("#add_price_type_edit").append(price_html);
	$(".del_price").on("click", function() {
		$(this).closest(".price").remove();
	});
});

//上传图片插件
$(function() {
	$("input[type=file]").change(function() {
		var form = $('#file_upload_edit');
		file_name = $(this).val();
		form[0].reset();
		$(this).parents(".uploader").find(".filename").val(file_name);
	});
	$("input[type=file]").each(function() {
		if($(this).val() == "") {
			$(this).parents(".uploader").find(".filename").val("No file selected...");
		}
	});
});

//新增产品保存
function doUpload() {
	//产品类型id
	var prod_category_id = $("#base_prod").val();
	//产品分类id
	var cms_category_id = $("#prod_classify").val();
	//产品分类名字
	var cms_category_name = "";
	if(cms_category_id == "-1") {
		cms_category_id = "0";
		cms_category_name = $(".custom_prod input").val();
		if(cms_category_name == "") {
			cms_category_id = "-1";
		}
	} else {
		cms_category_name = $("#prod_classify option:selected").text();
	}

	//产品名称
	var pro_cate_name = $("#pro_cate_name").val();
	//价格类型
	var price_type_arr = [];
	//可售数量
	var may_amount = $("#may_amount").val();
	//详情说明
	var details = $("#details").val();
	//产品描述
	var prod_des = $('#prod_description').val();
	//截止售卖时间
	var s_day = document.getElementById("sale_day").value;
	s_day = s_day == '' ? 0 : s_day;
	var s_hour = $("#sale_hour").val();
	s_hour = s_hour == '' ? 0 : s_hour;
	var close_sale_time = (parseInt(s_hour) - 0 - parseInt(s_day) * 24 - 0);
	close_sale_time = close_sale_time == 0 ? 0 : close_sale_time;
	$("#add_price_type").find(".price").each(function(index, domE) {
		var pro_price_type = $(this).find(".pro_price_type").val();
		var pro_price = $(this).find(".pro_price").val();
		var price_type = {
			"price_type_name": pro_price_type,
			"price_type_price": pro_price
		}
		price_type_arr.push(price_type);
	});

	console.log(cms_category_name + "," + cms_category_id);
	//	if ($("#fileUpload").val().length <= 0) {
	//		alert("请选择图片");
	//		return false;
	//	}
	$.ajax({
		url: base_api + 'prod/prod/add-prod', //请求地址
		data: {
			category_id: prod_category_id,
			pro_cate_name: pro_cate_name,
			price_type: JSON.stringify(price_type_arr),
			cms_category_id: cms_category_id,
			cms_category_name: cms_category_name,
			memo: details,
			show_img: img_url,
			prod_des: prod_des,
			close_sale_time: close_sale_time
		},
		type: "post",
		dataType: "json",
		async: false,
		success: function(data) {
			ZZLog(data)
			if(data.flag) {
				$('#my_big_modal').modal('hide');
				window.location.href = "product_list.html";
			} else {
				ZZAlertInfo(data['msg'], function() {
					ifLogin(data);
				});
			}
		},
		error: function(error) {
			ZZAlertInfo(infoApiError);
		}
	});

}
//新增产品上传图片
$(".upload_img").on("change", function() {
	var form = $("form[name=file_form]"); //其中的form1是我form的名称  
	var options = {
		url: base_api + 'prod/prod/upload-img',
		type: 'post',
		dataType: "json",
		success: function(data) {
			ZZLog(data);
			if(data.flag) {
				$("#img").html('<img width="80" height="80" src="' + data.data.url + '"/>');
				img_url = data.data.url;
			} else {
				ZZAlertInfo(data['msg'], function() {
					ifLogin(data);
				});
			}

		}
	};
	form.ajaxSubmit(options);

});

//编辑产品上传图片
$(".upload_img_edit").on("change", function() {
	var form = $("form[name=file_form_edit]"); //其中的form1是我form的名称
	var options = {
		url: base_api + 'prod/prod/upload-img',
		type: 'post',
		dataType: "json",
		success: function(data) {
			ZZLog(data);
			$(".uploader").find(".filename").val('');
			if(data.flag) {
				$("#img_edit").html('<img width="80" height="80" src="' + data.data.url + '"/>');
				img_url = data.data.url;
				form.find('.filename').val(file_name);
			} else {
				ZZAlertInfo(data['msg'], function() {
					ifLogin(data);
				});
			}

		}
	};
	form.ajaxSubmit(options);

});

function domain_price() {

	//判断是一键还是按票种
	var $one_key = $('#one_key');
	var $ticket_key = $('#ticket_setting');
	var setting_type = '';
	if($ticket_key.hasClass('active')) {
		setting_type = 'prod';
		prod();
	} else {
		setting_type = 'one';
		one_key();
	}

	function prod() {
		var prod_commission_arr = [];
		$('.ticket_commission').each(function(index,dom){
			var prod_id = $(this).attr('data-prod-id');
			var commission = $(this).val();
			if(commission=='')commission = 0;
			prod_commission_arr.push({prod_id,commission});
		})
		$.ajax({
			url: base_api + 'prod/prod/define-commission-prod', //请求地址
			data: {
				prod_commission_arr:JSON.stringify(prod_commission_arr)
			},
			type: "post",
			dataType: "json",
			async: false,
			success: function(data) {
				ZZLog(data)
				if(data.flag) {
					$('#myModal').modal('hide');
					$(".ticket_commission").val("0");
					get_product_list();
				} else {
					ZZAlertInfo(data['msg'], function() {
						ifLogin(data);
					});
				}
			},
			error: function(error) {
				ZZAlertInfo(infoApiError);
			}
		});
	}

	function one_key() {
		var commission_way_id = $("input[name=inlineRadioOptions]").val();
		var com_price = $("#com_price").val();
		$.ajax({
			url: base_api + 'prod/prod/define-commission', //请求地址
			data: {
				pro_cate_id: pro_cate_id,
				commission_way_id: commission_way_id,
				commission: com_price
			},
			type: "post",
			dataType: "json",
			async: false,
			success: function(data) {
				ZZLog(data)
				if(data.flag) {
//					$("#com" + pro_cate_id).text(com_price);
					$('#myModal').modal('hide');
					$("#com_price").val("");
					get_product_list();
				} else {
					ZZAlertInfo(data['msg'], function() {
						ifLogin(data);
					});
				}
			},
			error: function(error) {
				ZZAlertInfo(infoApiError);
			}
		});
	}

}

//、、、、、、、、、、、、、编辑、、、、、、、、、、、、、、//

//替换编辑信息
function edit_info(data) {
	ZZLog(data);

	$('#sale_hour_edit').html(getOptHtml());

	$("#base_prod_edit").val(data.category_id);
	if(data.cms_category_id <= 0) {
		$(".custom_prod_edit").show();
	} else {
		$(".custom_prod_edit").hide();
	}

	$("#prod_classify_edit").val(data.cms_category_id);

	$("#pro_cate_name_edit").val(data.pro_cate_name);
	$('#prod_description_div').val(data.prod_des);
	$("#add_price_type_edit").find(".price").remove();
	var temp = "";
	for(var i = 0, j = data.price_name.length; i < j; i++) {
		temp += '<div prod_id="' + data.price_name[i].prod_id + '" class="price">' +
			'<div style="margin-bottom: 5px;" class="form-group">' +
			'<input type="text" class="form-control pro_price_type" value="' + data.price_name[i].prod_name + '" >' +
			'</div>' +
			' <div style="margin-bottom: 5px;" class="form-group">' +
			'<div class="input-group">' +
			'<input class="form-control pro_price" type="text" value="' + data.price_name[i].prod_price + '" >' +
			'<div class="input-group-addon">元</div>' +
			'</div>' +
			'</div>' +
			' <button  type="button" style="margin-bottom: 5px;" class="btn btn-danger btn-xs del_price">删除</button>' +
			'</div>'
	}
	$("#add_price_type_edit").append(temp);
	$(".del_price").on("click", function() {
		$(this).closest(".price").remove();
	});
	if(data.show_img == "") {
		$("#img_edit").html('暂无图片');

	} else {
		$("#img_edit").html('<img width="80" height="80" src="' + data.show_img + '"/>');
		img_url = data.show_img;
	}
	$("#file_upload_edit").find(".filename").val("No file selected...");
	$("#details_edit").val(data.memo);
	//update fuhc 2017-05-18
	$('#sale_day_edit').val(data.sale_day);
	$('#sale_hour_edit').val(data.sale_hour);

}

//修改产品保存按钮
function doUpload_edit() {
	//产品类型id
	var prod_category_id = $("#base_prod_edit").val();
	//产品分类id
	var cms_category_id = $("#prod_classify_edit").val();
	//产品分类名字
	var cms_category_name = "";
	if(cms_category_id == "-1") {
		cms_category_id = "0";
		cms_category_name = $(".custom_prod_edit input").val();
		if(cms_category_name == "") {
			cms_category_id = "-1";
		}
	} else {
		cms_category_name = $("#prod_classify_edit option:selected").text();
	}

	//产品名称
	var pro_cate_name = $("#pro_cate_name_edit").val();
	//价格类型
	var price_type_arr = [];
	//可售数量
	var may_amount = $("#may_amount_edit").val();
	//详情说明
	var details = $("#details_edit").val();
	//产品描述
	var prod_des = $('#prod_description_div').val();
	//截止售卖时间
	var s_day = document.getElementById("sale_day_edit").value;
	s_day = s_day == '' ? 0 : s_day;
	var s_hour = $("#sale_hour_edit").val();
	s_hour = s_hour == '' ? 0 : s_hour;
	var close_sale_time = (parseInt(s_hour) - 0 - parseInt(s_day) * 24 - 0);
	close_sale_time = close_sale_time == 0 ? 0 : close_sale_time;
	$("#add_price_type_edit").find(".price").each(function(index, domE) {
		var prod_id = $(this).attr("prod_id");
		if(prod_id == undefined) {
			prod_id = "0";
		}
		var pro_price_type = $(this).find(".pro_price_type").val();
		var pro_price = $(this).find(".pro_price").val();
		var price_type = {
			"price_type_name": pro_price_type,
			"prod_id": prod_id,
			"price_type_price": pro_price
		}
		price_type_arr.push(price_type);
	});

	console.log(price_type_arr);
	//	if ($("#fileUpload").val().length <= 0) {
	//		alert("请选择图片");
	//		return false;
	//	}
	$.ajax({
		url: base_api + 'prod/prod/upt-prod', //请求地址
		data: {
			category_id: prod_category_id,
			pro_cate_name: pro_cate_name,
			pro_cate_id: pro_cate_id,
			price_type: JSON.stringify(price_type_arr),
			cms_category_id: cms_category_id,
			cms_category_name: cms_category_name,
			memo: details,
			show_img: img_url,
			prod_des: prod_des,
			close_sale_time: close_sale_time
		},
		type: "post",
		dataType: "json",
		async: false,
		success: function(data) {
			ZZLog(data)
			if(data.flag) {
				get_product_list();
//				base_info();
				$('#my_big_modal_edit').modal('hide');
			} else {
				ZZAlertInfo(data['msg'], function() {
					ifLogin(data);
				});
			}
		},
		error: function() {
			ZZAlertInfo(infoApiError);
		}
	});

}
//搜索
function search_prod() {
	current_page = 1;
	get_product_list();
}
//重置
function reset() {
	current_page = 1;
	$("#select_type").val("");
	$("#prod_name").val("");
	$("#recom_type").val("");
	get_product_list();
}
//加载小时
function getOptHtml() {
	var html = '';
	var h_arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
	h_arr.reverse();
	for(var i = 0, m = h_arr.length; i < m; i++) {
		var val = h_arr[i];
		var cstr = '';
		if(val < 10) {
			cstr = '0' + val + ':00';
		} else {
			cstr = val + ':00';
		}
		//		if(val==24)val=0;
		html += '<option value="' + val + '">' + cstr + '</option>';
	}
	return html;
}