$(document).ready(function() {
	$(".form_date_start").datetimepicker({
		format: 'yyyy-mm-dd',
		autoclose: true,
		minView: 2,
		pickerPosition: "bottom-left"
	});
	$(".form_date_end").datetimepicker({
		format: 'yyyy-mm-dd',
		autoclose: true,
		minView: 2,
		pickerPosition: "bottom-left"
	});
});

var pagesize = '10';
var list_currpage = '1';
var wechat_name = '';
var fx_phone = '';
var start_reg_time = '';
var end_reg_time = '';
//审核当前页面参数
let examine_current_page = '1';
var dis_wechat_name = '';
var dis_fx_phone = '';
var dis_start_reg_time = '';
var dis_end_reg_time = '';
var dis_status = '';
var is_bind = 0;

window.onload = function() {
	//	$('#start_date').val(getDateTime(0));
	//	$('#end_date').val(getDateTime(0));
	//初始化查询条件
	initSearch();
	//初始化 分销商列表
	firstReloadSupplierListData();
	//初始化 分销商审核
	httpFirstExamineList();
}

function initSearch() {
    $.ajax({
        url: base_api + 'user/fx-user/init-search', //请求地址
        type: "post",
        dataType: "json",
        async: false,
        success: function(res_data) {
            if(res_data.flag == false) {
                ZZAlertInfo(res_data['msg'], function() {
                    ifLogin(res_data);
                });
            } else {
                ZZLog(res_data.data);
                var list = res_data.data.mainList;
                var html = '<option value="">全部</option>';
                list.forEach(dict => {
                    html += '<option value="'+dict.id+'">'+dict.user_name+'</option>';
				});
                $('#search_main_1').append(html);
                $('#search_main_2').append(html);

                var area_list = res_data.data.userAreaList;
                var areaHtml = '<option value="">全部</option>';
                area_list.forEach(dict => {
                    areaHtml += '<option value="'+dict.area_id+'">'+dict.area_name+'</option>';
            	});
                $('#search_user_area_1').append(areaHtml);
                $('#search_user_area_2').append(areaHtml);

            }
        },
        error: function(error) {
            ZZAlertInfo(infoApiError);
        }
    });
}

//分销商列表
function firstReloadSupplierListData() {
	wechat_name = $('#user_name').val();
	fx_phone = $('#user_phone').val();
	start_reg_time = $('#start_date').val();
	end_reg_time = $('#end_date').val();
	let current_page = '1';
	let urlstr = base_api + 'user/fx-user/fx-user-list';
	let search_main = $('#search_main_1').val();
	let user_area = $('#search_user_area_1').val();
	let data = { wechat_name, fx_phone, start_reg_time, end_reg_time, current_page, page_size: pagesize,search_main,user_area }
	ZZLog(urlstr, JSON.stringify(data));
	$.ajax({
		url: urlstr, //请求地址
		data: data,
		type: "post",
		dataType: "json",
		async: false,
		success: function(res_data) {
			if(res_data.flag == false) {
				ZZAlertInfo(res_data['msg'], function() {
					ifLogin(res_data);
				});
			} else {
				ZZLog(res_data.data)
				let data = res_data.data;
				is_bind =  data.is_bind;
				totalpage = data.page.total_pages;
				let HTML = '';
				data.user_list.forEach(dict => {
					let tempHTML = listRePlaceData(dict);
					HTML += tempHTML;
				})
				if(data.user_list.length <= 0) {
					let html = `<tr style="text-align: center;">
										<td style="color: red;" colspan="6">无查询结果</td>
									</tr>`;
					$('#list_info').html(html);
				} else {
					$('#list_info').html(HTML);
					input_username1();
				}
				if(totalpage == 0) {
					$('#pageDivList').hide();
				} else {
					createPage(current_page, totalpage);
					$('#pageDivList').show();
				}
				$('#list_info').show();
			}
		},
		error: function(error) {
			ZZAlertInfo(infoApiError);
		}
	});
}

//创建分页控件
function createPage(currpage, totalpage) {
	$("#pageDivList").createPage({
		pageCount: totalpage, //总页数
		current: currpage, //当前页
		turndown: 'true', //是否显示跳转框，显示为true，不现实为false,一定记得加上引号...
		backFn: function(p) {
			list_currpage = p;
			listHttpData();
		}
	})
}

//分页数据
function listHttpData() {
	let urlstr = base_api + 'user/fx-user/fx-user-list';
	let current_page = list_currpage;
    let search_main = $('#search_main_1').val();
    let user_area = $('#search_user_area_1').val();
	let data = { wechat_name, fx_phone, start_reg_time, end_reg_time, current_page, page_size: pagesize,search_main,user_area }
	ZZLog('分页查询参数', data);
	$.ajax({
		url: urlstr, //请求地址
		data: data,
		type: "post",
		dataType: "json",
		async: false,
		success: (res_data) => {
			if(res_data.flag == false) {
				ZZAlertInfo(res_data['msg'], function() {
					ifLogin(res_data);
				});
			} else {
				ZZLog(res_data.data)
				let data = res_data.data;
                is_bind =  data.is_bind;
				totalpage = data.page.total_pages;
				let HTML = '';
				data.user_list.forEach(dict => {
					let tempHTML = listRePlaceData(dict);
					HTML += tempHTML;
				})
				if(data.user_list.length <= 0) {
					let html = `<tr style="text-align: center;">
										<td style="color: red;" colspan="6">无查询结果</td>
									</tr>`;
					$('#list_info').html(html);
				} else {
					$('#list_info').html(HTML);
					input_username1();
				}

				$('#list_info').show();
			}
		},
		error: (error) => {
			ZZAlertInfo(infoApiError);
		}
	});
}

function showUserName(ob) {
	var show_div = $(ob).find('.user_name_show');
    var hiden_div = $(ob).find('.user_name_hidden');
    show_div.css('display','none');
    hiden_div.css('display','');
}
function hiddenUserName(ob) {
	if($(ob).attr('data-click')==0) {
        var show_div = $(ob).find('.user_name_show');
        var hiden_div = $(ob).find('.user_name_hidden');
        show_div.css('display','');
        hiden_div.css('display','none');
	}
}
//分销商列表数据替换
function listRePlaceData(data) {
	let status_str = data.fx_status; //2 停用  1 开启
	let status_png = data.fx_status_id == '2' ? '/web/admin/images/guan.png' : '/web/admin/images/kai.png';
    let change_price=data.change_price_power == 0 ? '/web/admin/images/guan.png' : '/web/admin/images/kai.png'
    let change_price_hotel=data.change_price_power_hotel == 0 ? '/web/admin/images/guan.png' : '/web/admin/images/kai.png'
	let HTML = `<tr>
					<td>${data.fx_uid}</td>
					<td>${data.wechat_name}</td>
					<td style="padding:0px;margin:0px"  onmouseover="showUserName(this);" onmouseout="hiddenUserName(this);"  data-click="0">
						<div style="display: ;" class="user_name_show">${data.user_name}</div>
						<div style="display: none;"  class="user_name_hidden"><input data-fx_uid="${data.fx_uid}" onclick="$(this.parentNode.parentNode).attr('data-click','1')" class="user_name1" style="height:25px;width:105px;" type="text" value="${data.user_name}"/></div>
					</td>
					<td>${data.fx_phone}</td>
	                <td>${data.reg_time}</td>
	                <td>${data.remaining_sum}
	                	<div><a style="font-size: 12px;color: #9d9d9d;cursor: pointer;" onclick="toBalancePage(${data.fx_uid})">[查看详细]</a></div>
	                </td>
	                <td>${data.total_commission}</td>
	                <td>${data.closed_commission}</td>
	                <td><img onclick="changeStatus(${data.fx_uid},${data.fx_status_id})" data-info="状态" style="width: 33px;height: 30px;cursor: pointer;" src="${status_png}"></td>
	                <td style="color: #9d9d9d">
	               		<div><img onclick="changePrice(${data.change_price_power},${data.fx_uid},1)" data-info="检票" style="width: 33px;height: 30px;cursor: pointer;" src="${change_price}">自由行</div>
	                	<div><img onclick="changePrice(${data.change_price_power_hotel},${data.fx_uid},2)" data-info="检票" style="width: 33px;height: 30px;cursor: pointer;" src="${change_price_hotel}">酒店</div>
	                </td>
	                <td>
	                <div >${data.user_area}</div>
	                <div ><a style="font-size: 12px;color: #9d9d9d;cursor: pointer;" data-toggle="modal" data-target=".setAreaAdscription" onclick="setAreaAdscription(${data.fx_uid},'${data.wechat_name}')">[设置区域]</a></div>
					</td>
	                <td >
	                	<div style="font-weight: 900;">${data.main_user_name}</div>
	                	<div style="margin-top: 5px;">${data.main_corp_name}</div>
	                `;
    		if(is_bind){
                HTML += `<div><a  style="font-size: 12px;color: #9d9d9d;cursor: pointer;" data-toggle="modal" data-target=".setMainCorp"  onclick= "setMainCorp(${data.fx_uid})">[设置负责人]</a></div>`;
            }
	          HTML += `</td>
	                <td>
						<div>
							<button type="button" class="btn btn-primary btn-xs mar_r" data-toggle="modal" data-target=".bs-example-modal-sm" onclick="seeEticket(${data.fx_uid})">查看二维码</button>
						</div>
						<div style="margin-top: 5px;">
							<button type="button" class="btn btn-success btn-xs mar_r"  onclick= "seeCommission(${data.fx_uid})">查看佣金</button>
						</div>
	                </td>
	             </tr>`;
	return HTML;

}
function changePrice(change_price_power,fx_uid,type){
    let data = {change_price_power,fx_uid,type};
    let urlstr = base_api + 'user/fx-user/upt-price-change';
    $.ajax({
        url: urlstr, //请求地址
        data: data,
        type: "post",
        dataType: "json",
        async: false,
        success: function(res_data) {
            if(res_data.flag == false) {
                ZZAlertInfo(res_data['msg'], function() {
                    ifLogin(res_data);
                });
            } else {
                ZZLog(res_data);
                listHttpData()
            }
        },
        error: function(error) {
            ZZAlertInfo(infoApiError);
        }
    });
}

//余额列表页面
function toBalancePage(fx_uid){
	window.open('balance_list.html?fx_uid='+fx_uid);
}
//查看二维码
function seeEticket(fx_uid) {
	let data = { fx_uid };
	let urlstr = base_api + 'user/fx-user/get-qr-code';
	$.ajax({
		url: urlstr, //请求地址
		data: data,
		type: "post",
		dataType: "json",
		async: false,
		success: function(res_data) {
			if(res_data.flag == false) {
				ZZAlertInfo(res_data['msg'], function() {
					ifLogin(res_data);
				});
			} else {
				ZZLog(res_data);
				$('#eticket').attr('src', res_data.data.qr_code);
              	$('#new_eticket').attr('src', res_data.data.new_qr_code);
			}
		},
		error: function(error) {
			ZZAlertInfo(infoApiError);
		}
	});
}

//查看明细
function seeCommission(fx_uid) {
	window.location.href = 'commission_details.html?fx_uid=' + fx_uid;
}

//启用停用
function changeStatus(fx_uid, fx_status_id) {
	let data = { fx_uid, fx_status_id };
	let urlstr = base_api + 'user/fx-user/change-fx-user';
	$.ajax({
		url: urlstr, //请求地址
		data: data,
		type: "post",
		dataType: "json",
		async: false,
		success: function(res_data) {
			if(res_data.flag == false) {
				ZZAlertInfo(res_data['msg'], function() {
					ifLogin(res_data);
				});
			} else {
				listHttpData();
			}
		},
		error: function(error) {
			ZZAlertInfo(infoApiError);
		}
	});
}

//搜索
function searchDidClick() {
	firstReloadSupplierListData();
}

//重置
function resetDidClick() {
	$('#start_date').val('');
	$('#end_date').val('');
	$('#user_name').val('');
	$('#user_phone').val('');
    $('#search_main_1').val('');
    $('#search_user_area_1').val('');
	firstReloadSupplierListData();
}
//用户名  -- 列表
function input_username1() {
	let pass_value = '';
	$('.user_name1').on('focus', function() {
		pass_value = $(this).val().trim();
	})
	$('.user_name1').on('blur', function() {
		let fx_uid = $(this).attr('data-fx_uid');
		let user_name = $(this).val().trim();
		if(pass_value == user_name){
            $(this.parentNode.parentNode).attr('data-click',0);
            hiddenUserName(this.parentNode.parentNode);
            return;
		}
		let data = {
			fx_uid,
			user_name
		}
		ZZLog(base_api + 'user/fx-user/update-user-name', JSON.stringify(data));
		$.ajax({
			type: "post",
			url: base_api + 'user/fx-user/update-user-name',
			async: true,
			data: data,
			dataType: "json",
			success: (res_data) => {
				ZZLog(res_data);
				if(false == res_data['flag']) {
					ZZAlertInfo(res_data['msg'], function() {
						ifLogin(res_data);
					});
				}else{
					$(this.parentNode.parentNode).find('.user_name_show').html(user_name);
                    $(this.parentNode.parentNode).attr('data-click',0);
                    hiddenUserName(this.parentNode.parentNode);
				}
			},
			error: () => {
				ZZAlertInfo(infoApiError);
			}
		});
	})
}
//用户名  -- 审核
function input_username2() {
	let pass_value = '';
	$('.user_name2').on('focus',function(){
		pass_value = $(this).val().trim();
	})
	$('.user_name2').on('blur', function() {
		let fx_uid = $(this).attr('data-fx_uid');
		let user_name = $(this).val().trim();
        if(pass_value == user_name){
            $(this.parentNode.parentNode).attr('data-click',0);
            hiddenUserName(this.parentNode.parentNode);
            return;
        }
		ZZLog('fx_uid=', fx_uid);
		let data = {
			fx_uid,
			user_name
		}
		ZZLog(base_api + 'user/fx-user/update-user-name', JSON.stringify(data));
		$.ajax({
			type: "post",
			url: base_api + 'user/fx-user/update-user-name',
			async: true,
			data: data,
			dataType: "json",
			success: (res_data) => {
				ZZLog(res_data);
				if(false == res_data['flag']) {
					ZZAlertInfo(res_data['msg'], function() {
						ifLogin(res_data);
					});
				} else {
                    $(this.parentNode.parentNode).find('.user_name_show').html(user_name);
                    $(this.parentNode.parentNode).attr('data-click',0);
                    hiddenUserName(this.parentNode.parentNode);
				}
			},
			error: () => {
				ZZAlertInfo(infoApiError);
			}
		});
	})
}

//审核

function httpFirstExamineList() {
	dis_wechat_name = $('#user_name_dis').val();
	dis_fx_phone = $('#user_phone_dis').val();
	dis_start_reg_time = $('#start_date_dis').val();
	dis_end_reg_time = $('#end_date_dis').val();
	dis_status = $('#dis_status').val();
	examine_current_page = '1';
	let data = {
		current_page: examine_current_page,
		page_size: pagesize,
		wechat_name : dis_wechat_name,
		fx_phone : dis_fx_phone,
		start_reg_time : dis_start_reg_time,
		end_reg_time : dis_end_reg_time,
		status : dis_status,
        search_main : $('#search_main_2').val(),
        user_area:$('#search_user_area_2').val()
	}
	ZZLog(base_api + 'user/fx-user/check-fx-user', JSON.stringify(data));
	$.ajax({
		type: "post",
		url: base_api + 'user/fx-user/check-fx-user',
		data: data,
		dataType: "json",
		success: (res_data) => {
			ZZLog(res_data);
			if(false == res_data['flag']) {
				ZZAlertInfo(res_data['msg'], function() {
					ifLogin(res_data);
				});
			} else {
				let data = res_data['data'];
				let page = data['page'];
				//分页控件
				$("#pageDivExamine").createPage({
					pageCount: page['total_pages'], //总页数
					current: examine_current_page, //当前页
					turndown: 'true', //是否显示跳转框，显示为true，不现实为false,一定记得加上引号...
					backFn: (p) => {
						examine_current_page = p;
						httpExamineList();
					}
				});
				if(page['total_pages'] > 0) {
					$('#pageDivExamine').show();
				} else {
					$('#pageDivExamine').hide();
				}
				let distributor_confirm_list = data['fx_list'];
				if(distributor_confirm_list.length <= 0) {
					let html = `<tr style="text-align: center;">
										<td style="color: red;" colspan="4">无查询结果</td>
									</tr>`;
					$('#examine_table_list').html(html);
				} else {
					let HTML = getExamineHTML(distributor_confirm_list);
					$('#examine_table_list').html(HTML);
					input_username2();
				}

			}
		},
		error: () => {
			ZZAlertInfo(infoApiError);
		}
	});
}

function httpExamineList() {
	let data = {
		current_page: examine_current_page,
		page_size: pagesize,
		wechat_name : dis_wechat_name,
		fx_phone : dis_fx_phone,
		start_reg_time : dis_start_reg_time,
		end_reg_time : dis_end_reg_time,
		status : dis_status,
        search_main : $('#search_main_2').val(),
        user_area:$('#search_user_area_2').val()
	}
	ZZLog(base_api + 'user/fx-user/check-fx-user', JSON.stringify(data));
	$.ajax({
		type: "post",
		url: base_api + 'user/fx-user/check-fx-user',
		data: data,
		dataType: "json",
		success: (res_data) => {
			ZZLog(res_data);
			if(false == res_data['flag']) {
				ZZAlertInfo(res_data['msg'], function() {
					ifLogin(res_data);
				});
			} else {
				let data = res_data['data'];
				let page = data['page'];
				examine_current_page = page['current_page'];

				let distributor_confirm_list = data['fx_list'];
				let HTML = getExamineHTML(distributor_confirm_list);
				$('#examine_table_list').html(HTML);
				input_username2();
			}
		},
		error: () => {
			ZZAlertInfo(infoApiError);
		}
	});
}

function getExamineHTML(list) {
	let HTML = '';
	//	for(dict of list) {
	//		let tempHTML = getTRhtml(dict);
	//		HTML += tempHTML;
	//	}
	list.forEach(dict => {
		let tempHTML = getTRhtml(dict);
		HTML += tempHTML;
	})
	return HTML;
}

function getTRhtml(dict) {
	let cstr = '';
	let cstr2 = '';
	//1 审核未通过 2：审核通过 3： 待审核
	if('1' == dict['status']) {
		//		cstr = `<button type="button" class="btn btn-danger btn-xs mar_r">${dict['status_type']}</button>`;
		cstr2 = `<button type="button" class="btn btn-success btn-xs mar_r" onclick="click_examine(${dict['fx_uid']},'2')">审核通过</button>`;
	} else if('2' == dict['status']) {
		//		cstr = `<button type="button" class="btn btn-success btn-xs mar_r">${dict['status_type']}</button>`;
		cstr2 = `<button type="button" class="btn btn-danger btn-xs mar_r" onclick="click_examine(${dict['fx_uid']},'1')">审核不通过</button>`;
	} else if('3' == dict['status']) {
		//		cstr = `<button type="button" class="btn btn-warning btn-xs mar_r">${dict['status_type']}</button>`;
		cstr2 += `<button type="button" class="btn btn-info btn-xs mar_r" onclick="click_examine(${dict['fx_uid']},'2')">审核通过</button>`;
		cstr2 += `<button type="button" class="btn btn-danger btn-xs mar_r" onclick="click_examine(${dict['fx_uid']},'1')">审核不通过</button>`;
	} else {
		cstr = '';
	}
	let html = `<tr fx_uid="${dict['fx_uid']}">
					<td>${dict['nickname']}</td>
					<td style="padding:0px;margin:0px"  onmouseover="showUserName(this);" onmouseout="hiddenUserName(this);"  data-click="0">
						<div style="display: ;" class="user_name_show">${dict.user_name}</div>
						<div style="display: none;"  class="user_name_hidden"><input data-fx_uid="${dict.fx_uid}" onclick="$(this.parentNode.parentNode).attr('data-click','1')" class="user_name2" style="height:25px;width:105px;" type="text" value="${dict.user_name}"/></div>
					</td>
					<td>${dict['phone']}</td>
					<td>${dict['reg_time']}</td>
					<td>
						 ${dict['status_type']}
					</td>
					<td>
						<div>${dict['main_user_name']}</div>
						<div>${dict['main_corp_name']}</div>
					</td>
					<td>
						${cstr2}
					</td>
				</tr>`;
	return html;
}

function click_examine(fx_uid, status) {

	let data = {
		fx_uid,
		status
	}
	ZZLog(base_api + 'user/fx-user/through-fx-user', JSON.stringify(data));
	$.ajax({
		type: "post",
		url: base_api + 'user/fx-user/through-fx-user',
		data: data,
		success: (res_data) => {
			if(false == res_data['flag']) {
				ZZAlertInfo(res_data['msg'], function() {
					ifLogin(res_data);
				});
			} else {
				httpExamineList();
			}
		},
		error: () => {
			ZZAlertInfo(infoApiError);
		}
	});
}


function disSearchDidClick(){
	httpFirstExamineList();
}

function disResetDidClick(){
	dis_wechat_name = $('#user_name_dis').val('');
	dis_fx_phone = $('#user_phone_dis').val('');
	dis_start_reg_time = $('#start_date_dis').val('');
	dis_end_reg_time = $('#end_date_dis').val('');
	$('#search_main_2').val('');
    $('#search_user_area_2').val('');
	$("#dis_status option:first").prop("selected", 'selected');
	httpFirstExamineList();
}

//设置运营主体
var main_corp_list='';
function setMainCorp(fx_uid) {
    $.ajax({
            type: "post",
            url: base_api + 'user/fx-user/get-main-corp',
            dataType: "json",
            success: (res_data)=>{
            if(false == res_data['flag']) {
			ZZAlertInfo(res_data['msg'], function() {
				ifLogin(res_data);
			});
		} else {
			main_corp_list = res_data.data.list;
			var HTML = '';
			main_corp_list.forEach(dict => {
				HTML += '<tr class="show_main_tr">';
				HTML += '<td>'+dict.user_name+'</td>';
				HTML += '<td>'+dict.main_corp_name+'</td>';
				HTML += '<td><input class="btn btn-primary" type="button" onclick="bindMainUser('+fx_uid+','+dict.id+');" value="绑定"></td>';
				HTML += '</tr>';
			});
                $('.show_main_tr').remove();
				$('#mainCorpShowList table').append(HTML);
			}
		},
		error: ()=>{
			ZZAlertInfo(infoApiError);
		}
	});
}

function bindMainUser(fx_uid, main_corp_id) {
    ZZConfirm('确定设置用户的运营负责人么？',function (re) {
        var data = {
            fx_uid:fx_uid,
            main_corp_id:main_corp_id
        };
        $.ajax({
                type: "post",
                url: base_api + 'user/fx-user/bind-main-corp',
                dataType: "json",
				data:data,
                success: (res_data)=>{
                if(false == res_data['flag']) {
					ZZAlertInfo(res_data['msg'], function() {
						ifLogin(res_data);
					});
				} else {
					$('#setMainCorpDel').click();
					listHttpData();
				}
			},
			error: ()=>{
				ZZAlertInfo(infoApiError);
			}
		});
    });

}

///设置用户的区域
function setAreaAdscription(fx_uid,name) {
	$('#user_area_set_show_name').html(name);
	var data = {
        fx_uid:fx_uid
	};
    $('.show_are_tr').remove();
    $.ajax({
            type: "post",
            url: base_api + 'user/fx-user/get-user-area-list',
            dataType: "json",
            data:data,
            success: (res_data)=>{
				if(false == res_data['flag']) {
					ZZAlertInfo(res_data['msg'], function() {
						ifLogin(res_data);
					});
				} else {
					var list = res_data.data;
					var HTML = '';
					list.forEach(areaVal => {
						HTML += '<tr class="show_are_tr">';
						HTML += '<td>'+areaVal.area_id+'</td>';
						HTML += '<td>'+areaVal.area_name+'</td>';
						if(areaVal.is_bind == 1) {
                            HTML += '<td>已绑定</td>';
						} else  {
                            HTML += '<td><input class="btn btn-primary" type="button" onclick="bindUserArea('+fx_uid+','+areaVal.area_id+');" value="绑定"></td>';
						}
						HTML += '</tr>';
					});
					$('#areaAdscriptionShowList table').append(HTML);
				}
			},
			error: ()=>{
				ZZAlertInfo(infoApiError);
			}
		});
}
//绑定用户所属区域
function bindUserArea(fx_uid, area_id) {
	var data  ={
		fx_uid:fx_uid,
		area_id:area_id
	};
    $.ajax({
            type: "post",
            url: base_api + 'user/fx-user/bind-user-area',
            dataType: "json",
            data:data,
            success: (res_data)=>{
    			listHttpData();
    			$('#setAreaAdscriptionDel').click();
			},
			error: ()=>{
				ZZAlertInfo(infoApiError);
			}
	});
}
