<repo_name>melo1024/flaskWeb<file_sep>/app.py
# -*- coding:utf-8 -*-
""" 本地测试url
初始化：
http://127.0.0.1:5000/es/init?min_score=94&max_score=94&split_score=76
统计信息：
http://127.0.0.1:5000/all/count
球员数量统计：
http://127.0.0.1:5000/player/count
国家列表：
http://127.0.0.1:5000/nation/list
联赛列表：
http://127.0.0.1:5000/league/list
俱乐部列表：
http://127.0.0.1:5000/club/list?leagueName=美国足球职业大联盟
天赋列表：
http://127.0.0.1:5000/skill/list
活动列表：
http://127.0.0.1:5000/program/list
天赋等级提升（扑救大师）：
http://127.0.0.1:5000/skill/updata?code=5581e0a0-00d1-11e8-9a00-8105ee8c8a87
位置等级提升：
http://127.0.0.1:5000/job/updata?code=ST
青云对象存储：
http://127.0.0.1:5000/file

网站首页：
http://127.0.0.1:5000/fifamobile
"""
from flask import Flask, Response, send_file, send_from_directory, make_response
from flask import request, render_template
import esHandler
import qingstorHandler
from io import BytesIO
import tempfile
import os

"""Flask app"""
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/fifamobile')
def fifa_mobile():
    return render_template("players.html")

@app.route('/file')
def return_file():
    key = request.args.get('key')
    r = qingstorHandler.getRespByKey(key)
    b = bytes()
    for chunk in r.iter_content():
        b = b + chunk
    response = make_response(b)
    response.headers["Content-Disposition"] = "attachment; filename={}".format(key)
    return response


@app.route('/es/init', methods=['get'])
def init_es():
    min_score = request.args.get('min_score')
    max_score = request.args.get('max_score')
    split_score = request.args.get('split_score')
    if min_score is None or max_score is None or split_score is None:
        return 'Invalid request, pls check the url.'
    if min_score.isdigit() and max_score.isdigit() and split_score.isdigit():
        # # 初始化国家
        # esHandler.initNationIndex()
        # # 初始化联赛/俱乐部
        # esHandler.initLeagueAndClubIndex()
        # # 初始化天赋
        # esHandler.initSkillIndex()
        # # 初始化活动
        # esHandler.initProgramIndex()
        # # 初始化位置等级提升
        # esHandler.initJobLevelCapabilityIndex()
        # 初始化球员
        esHandler.initPlayerIndex(int(min_score), int(max_score), int(split_score))
        return 'ES init complete!'
    else:
        return 'Param type error.'


@app.route('/all/count', methods=['get'])
def countAll():
    return esHandler.countAll()

@app.route('/player/count', methods=['get'])
def count():
    return esHandler.countPlayers()

@app.route('/player/list', methods=['get'])
def searchPlayer():
    print(request.args)
    min_score = request.args.get('min_score')
    max_score = request.args.get('max_score')
    name = request.args.get('name')
    nation = request.args.get('nation')
    league = request.args.get('league')
    club = request.args.get('club')
    job = request.args.get('job')
    skill = request.args.get('skill')
    #活动，比如黄金周/七夕
    program = request.args.get('program')

    result = esHandler.searchPlayers(min_score, max_score, name, nation, league, club, job, skill, program)
    return result

@app.route('/nation/list', methods=['get'])
def searchNation():
    result = esHandler.searchNation()
    return result

@app.route('/league/list', methods=['get'])
def searchLeague():
    result = esHandler.searchLeague()
    return result

@app.route('/club/list', methods=['get'])
def searchClub():
    leagueName = request.args.get('leagueName')
    result = esHandler.searchClub(leagueName)
    return result

@app.route('/skill/list', methods=['get'])
def searchSkill():
    result = esHandler.searchSkill()
    return result

@app.route('/program/list', methods=['get'])
def searchProgram():
    result = esHandler.searchProgram()
    return result

@app.route('/job/updata', methods=['get'])
def searchJobLevelCapability():
    job = request.args.get('code')
    result = esHandler.searchJobLevelCapability(job)
    return result

@app.route('/skill/updata', methods=['get'])
def searchSkillLevelCapability():
    skill = request.args.get('code')
    result = esHandler.searchSkillLevelCapability(skill)
    return result

if __name__ == '__main__':
    app.run()
<file_sep>/simpleApp.py
# -*- coding:utf-8 -*-
from flask import Flask, render_template

"""Flask app"""
app = Flask(__name__)

@app.route('/fifamobile')
def fifa_mobile():
    return render_template("players.html")

@app.route('/test')
def test():
    return 'ok'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)<file_sep>/test.py
import requests

r = requests.get('http://img.wantuole.com/resources/backgrouds/VIP2.png')

print(r.content)<file_sep>/static/js/common.js
$(function() {
	initParts();
	setTimeout(function() {
		initCommonModule();
	}, 1000);
})

function initParts() {
	$("#banner").load("parts/banner.html");
	$("#functions").load("parts/functions.html");
}

function initCommonModule() {
	ajax.get('count?code=fifamobile', function(data) {
		$("#cardTotal").text(data.cardTotal);
	});
}

/**
 * 调用html2canvas框架进行截图下载功能
 * @param domId 容器Id
 * author Levin
 */
function domShot(domId) {
	//0.5.0-beta4方法
	html2canvas(document.querySelector("#" + domId), {
		allowTaint: true,
		height: $("#" + domId).outerHeight() + 20
	}).then(function(canvas) {
		var timestamp = Date.parse(new Date());
		$('#down_button').attr('href', canvas.toDataURL());
		$('#down_button').attr('download', timestamp + '.png');
		var fileObj = document.getElementById("down_button");
		fileObj.click();
	});
}

function getBackground(pn, r, score, hb, bg) {
	var imgUrl = "http://img.wantuole.com/resources/backgrouds/";
	var num = 0;
	var imgName = "";
	if(parseInt(hb) > 0) {
		num = parseInt((parseInt(score) - 70) / 10);
		if(bg == "CGER" || bg == 'SC' || bg == 'TC' || bg == 'T' || bg == 'TDYX' || pn.indexOf('剧情精英球员') >= 0 || bg == 'ZCBase')
			num = parseInt((parseInt(score) - 50) / 10);
		else if(bg == 'JLBZ')
			num = parseInt((parseInt(score) - 60) / 10);
		if(pn == '世界杯球员') {
			if(num > 4) {
				num = 4;
			}
		}
		imgName = bg + num + ".png";
	} else {
		num = parseInt((parseInt(score) - 50) / 10);
		if(bg != "BASIC") {
			imgName = bg + num + ".png";
		} else {
			switch(parseInt(r)) {
				case 1:
					imgName = "";
					break;
				case 2:
					imgName = "MR";
					break;
				case 3:
					imgName = "ER";
					break;
				case 4:
					imgName = "GR";
					break;
				case 5:
					imgName = "SR";
					break;
				case 6:
					imgName = "BR";
					break;
			}
			imgName = imgName + num + ".png";
		}
	}
	imgUrl = imgUrl + imgName;
	return imgUrl;
}

function getHead(pn, no, score, calcscore, head, count, haveas) {
	var imgUrl = "http://img.wantuole.com/FIFA%E8%B6%B3%E7%90%83%E4%B8%96%E7%95%8C/players/";
	if(pn == '世界杯球员') {
		var imgUrl = "http://img.wantuole.com/FIFA%E8%B6%B3%E7%90%83%E4%B8%96%E7%95%8C/wcplayers/";
	}
	var num = 0;
	var imgName = "";

	if(parseInt(haveas) == 1) {
		if(parseInt(score) >= 80) {
			if(calcscore)
				imgName = no + "_AS" + calcscore + ".png";
			else
				imgName = no + "_AS.png";
		} else {
			imgName = no + ".png";
		}
	} else {
		if(head == "TOTW") {
			if(score) {
				imgName = no + "_" + head + calcscore + ".png";
			} else {
				imgName = no + "_" + head + ".png";
			}
		} else {
			if(parseInt(count) > 1) {
				num = parseInt((parseInt(score) - calcscore) / 10);
				if(head == "IC" || head == "PI") {
					if(num == 0)
						num = 1;
				}

				if(num > count)
					num = count;
				imgName = no + "_" + head + num + ".png";
			} else {
				if(head) {
					if(parseInt(score) >= 80) {
						imgName = no + "_" + head + ".png";
						if(head == 'MM') {
							if(score >= 100) {
								imgName = no + "_L" + head + ".png";
							}
						} else if(head == 'LVL') {
							if(score >= 100) {
								imgName = no + "_LVLM.png";
							}
						}
					} else {
						if(calcscore == -1) {
							imgName = no + "_" + head + ".png";
						} else {
							imgName = no + ".png";
						}
					}
				} else
					imgName = no + ".png";
			}
		}
	}
	imgUrl = imgUrl + imgName;
	return imgUrl;
}

function getBasicValues(job, values) {
	var basicValues = [];
	if(job != 'GK') {
		basicValues[0] = Math.floor(values[1] * 0.45 + values[0] * 0.55);
		basicValues[1] = Math.floor(values[6] * 0.45 + values[7] * 0.20 + values[8] * 0.25 + values[16] * 0.1);
		basicValues[2] = Math.floor(values[17] * 0.45 + values[18] * 0.25 + values[19] * 0.3);
		basicValues[3] = Math.floor(values[4] * 0.55 + values[3] * 0.3 + values[15] * 0.15);
		basicValues[4] = Math.floor(values[11] * 0.50 + values[10] * 0.35 + values[5] * 0.15);
		basicValues[5] = Math.floor(values[2] * 0.6 + values[12] * 0.4);

	} else {
		basicValues[0] = values[6];
		basicValues[1] = values[7];
		basicValues[2] = values[9];
		basicValues[3] = values[8];
		basicValues[4] = Math.round(values[17] * 0.35 + values[18] * 0.3 + values[19] * 0.3 + values[16] * 0.05);
		basicValues[5] = Math.round(values[2] * 0.6 + values[12] * 0.4);
	}

	return basicValues;
}

//方法一:逐个字符检查是否中文字符
String.prototype.getByteLen = function() {
	var len = 0;
	for(var i = 0; i < this.length; i++) {
		if((this.charCodeAt(i) & 0xff00) != 0)
			len++;
		len++;
	}
	return len;
}<file_sep>/static/js/playerContrast.page.js
var selectedRaritie;
var selectedNation;
var selectedJob;
var leagues;
var selectedLeague;
var selectedClub;
var selectedProgram;
var selectedProgramChild = '';
var selectedSkill;
var programs = [];
var cards = [];
var filter = false;
var filterCards;
var index = 1;
var size = 30;
var dataTable;

var selectedPlayer;
var players = [];
var playerHead = [];
var playerInfo = [];
var maxValue = [];

$(function() {
	initPage();
})

function initPage() {
	$("#raritySelect").multiselect({
		includeSelectAllOption: false,
		selectAllText: ' 全选',
		nonSelectedText: '全部', //没有值的时候button显示值  
		nSelectedText: '个被选中', //有n个值的时候显示n个被选中 
		allSelectedText: '全选', //所有被选中的时候 全选（n）
		enableFiltering: false,
		numberDisplayed: 1,
		filterPlaceholder: '查询',
		onChange: function(option, checked, select) {
			if(checked) {
				selectedRaritie = $(option).val();
			} else {
				selectedRaritie = "";
			}
		}
	});

	$("#jobSelect").multiselect({
		maxHeight: 500,
		includeSelectAllOption: false,
		selectAllText: ' 全选',
		nonSelectedText: '全部', //没有值的时候button显示值  
		nSelectedText: '个被选中', //有n个值的时候显示n个被选中 
		allSelectedText: '全选', //所有被选中的时候 全选（n）
		enableFiltering: false,
		numberDisplayed: 1,
		filterPlaceholder: '查询',
		onChange: function(option, checked, select) {
			if(checked) {
				selectedJob = $(option).val();
			} else {
				selectedJob = "";
			}
		}
	});

	if(localStorage["nation"]) {
		var data = JSON.parse(localStorage["nation"]);
		var select = $('#nationSelect');
		data.forEach(function(item, i) {
			option = $("<option value='" + item.code + "' icon='" + item.icon + "' name='" + item.chname + "'>" + item.chname + "</option>");
			option.appendTo(select);
		});

		select.multiselect({
			maxHeight: 500,
			includeSelectAllOption: false,
			enableFiltering: true,
			filterPlaceholder: '查询',
			nonSelectedText: '请选择...',
			onChange: function(option, checked, select) {
				if(checked) {
					selectedNation = $(option).val();
				} else {
					selectedNation = "";
				}
			}
		});
	} else {
		ajax.get('nation/list', function(result) {
			if(result.data && typeof(result.data) != undefined) {
				localStorage.setItem("nation", JSON.stringify(result.data));
			}
			var select = $('#nationSelect');
			result.data.forEach(function(item, i) {
				option = $("<option value='" + item.code + "' icon='" + item.icon + "' name='" + item.chname + "'>" + item.chname + "</option>");
				option.appendTo(select);
			});

			select.multiselect({
				maxHeight: 500,
				includeSelectAllOption: false,
				enableFiltering: true,
				filterPlaceholder: '查询',
				nonSelectedText: '请选择...',
				onChange: function(option, checked, select) {
					if(checked) {
						selectedNation = $(option).val();
					} else {
						selectedNation = "";
					}
				}
			});
		});
	}

	//localStorage.removeItem("league")
	if(localStorage["league"]) {
		var data = JSON.parse(localStorage["league"]);
		var select = $('#leagueSelect');
		data.forEach(function(item, i) {
			var option = $("<option value='" + item.code + "'>" + item.chname + "</option>");
			option.appendTo(select);
		});

		select.multiselect({
			maxHeight: 500,
			includeSelectAllOption: false,
			enableFiltering: true,
			filterPlaceholder: '查询',
			onChange: function(option, checked, select) {
				if(checked) {
					selectedLeague = $(option).val();
				} else {
					selectedLeague = "";
				}

				selectedClub = "";
				bindClub($(option).val());
			}
		});

		bindClub('');
	} else {
		ajax.get('league/list', function(result) {
			if(result.data && typeof(result.data) != undefined) {
				localStorage.setItem("league", JSON.stringify(result.data));
			}
			var select = $('#leagueSelect');
			result.data.forEach(function(item, i) {
				var option = $("<option value='" + item.code + "'>" + item.chname + "</option>");
				option.appendTo(select);
			});

			select.multiselect({
				maxHeight: 500,
				includeSelectAllOption: false,
				enableFiltering: true,
				filterPlaceholder: '查询',
				onChange: function(option, checked, select) {
					if(checked) {
						selectedLeague = $(option).val();
					} else {
						selectedLeague = "";
					}

					selectedClub = "";
					bindClub($(option).val());
				}
			});

			bindClub('');
		});
	}
	
	localStorage.removeItem("program")
	if(localStorage["program"]) {
		var data = JSON.parse(localStorage["program"]);
		var select = $('#programSelect');
		programs = data;
		programs.forEach(function(item, i) {
			if(item.isShow) {
				if(item.isShow == "1") {
					var option = $("<option value='" + item.chname + "'>" + item.chname + "</option>");
					option.appendTo(select);
				}
			}
		});

		select.multiselect({
			maxHeight: 500,
			includeSelectAllOption: false,
			enableFiltering: true,
			filterPlaceholder: '查询',
			nonSelectedText: '请选择...',
			onChange: function(option, checked, select) {
				if(checked) {
					selectedProgram = $(option).val();
					programs.forEach(function(program, index) {
						if(program.chname == selectedProgram) {
							if(program.childs) {
								if(program.childs.length > 0) {
									bindProgramChild(program.childs);
									$("#programChildDiv").show();
								} else {
									selectedProgramChild = "";
									$("#programChildDiv").hide();
								}
							} else {
								selectedProgramChild = "";
								$("#programChildDiv").hide();
							}
						}
					});
				} else {
					selectedProgram = "";
				}
			}
		});
	} else {
		ajax.get('program/list?gameCode=fifamobile', function(result) {
			if(result.data && typeof(result.data) != undefined) {
				localStorage.setItem("program", JSON.stringify(result.data));
			}
			var select = $('#programSelect');
			programs = result.data;
			programs.forEach(function(item, i) {
				if(item.isShow) {
					if(item.isShow == "1") {
						var option = $("<option value='" + item.chname + "'>" + item.chname + "</option>");
						option.appendTo(select);
					}
				}
			});

			select.multiselect({
				maxHeight: 500,
				includeSelectAllOption: false,
				enableFiltering: true,
				filterPlaceholder: '查询',
				nonSelectedText: '请选择...',
				onChange: function(option, checked, select) {
					if(checked) {
						selectedProgram = $(option).val();
						programs.forEach(function(program, index) {
							if(program.chname == selectedProgram) {
								if(program.childs) {
									if(program.childs.length > 0) {
										bindProgramChild(program.childs);
										$("#programChildDiv").show();
									} else {
										selectedProgramChild = "";
										$("#programChildDiv").hide();
									}
								} else {
									selectedProgramChild = "";
									$("#programChildDiv").hide();
								}
							}
						});
					} else {
						selectedProgram = "";
					}
				}
			});
		});
	}

	//localStorage.removeItem("skill")
	if(localStorage["skill"]) {
		var data = JSON.parse(localStorage["skill"]);
		var select = $('#skillSelect');
		data.forEach(function(item, i) {
			var option = $("<option value='" + item.code + "'>" + item.name + "</option>");
			option.appendTo(select);
		});

		select.multiselect({
			maxHeight: 500,
			includeSelectAllOption: false,
			enableFiltering: true,
			filterPlaceholder: '查询',
			nonSelectedText: '请选择...',
			onChange: function(option, checked, select) {
				if(checked) {
					selectedSkill = $(option).val();
				} else {
					selectedSkill = "";
				}
			}
		});
	} else {
		ajax.get('skill/list?gameCode=fifamobile', function(result) {
			if(result.data && typeof(result.data) != undefined) {
				localStorage.setItem("skill", JSON.stringify(result.data));
			}
			var select = $('#skillSelect');
			result.data.forEach(function(item, i) {
				var option = $("<option value='" + item.code + "'>" + item.name + "</option>");
				option.appendTo(select);
			});

			select.multiselect({
				maxHeight: 500,
				includeSelectAllOption: false,
				enableFiltering: true,
				filterPlaceholder: '查询',
				nonSelectedText: '请选择...',
				onChange: function(option, checked, select) {
					if(checked) {
						selectedSkill = $(option).val();
					} else {
						selectedSkill = "";
					}
				}
			});
		});
	}

	$("#sortSelect").multiselect({
		maxHeight: 500,
		includeSelectAllOption: false,
		selectAllText: ' 全选',
		nonSelectedText: '全部', //没有值的时候button显示值  
		nSelectedText: '个被选中', //有n个值的时候显示n个被选中 
		allSelectedText: '全选', //所有被选中的时候 全选（n）
		enableFiltering: false,
		numberDisplayed: 1,
		filterPlaceholder: '查询',
		onChange: function(option, checked, select) {
			if(checked) {
				if($(option).val()) {
					dataTable.order([parseInt($(option).val()), "desc"]).draw();
				}
			}
		}
	});

	//bindData();

	$('#playerList tbody').on('click', 'tr', function() {
		var data = dataTable.row(this).data();
		buildInfo(data.code);
		$('#playerSelect').modal('hide');
	});
}

function bindClub(lcode) {
	//localStorage.removeItem("club")
	if(localStorage["club"] && lcode == '') {
		var data = JSON.parse(localStorage["club"]);
		var select = $('#clubSelect');
		select.empty();
		var option = $("<option value=''>全部</option>");
		option.appendTo(select);
		data.forEach(function(item, i) {
			var option = $("<option value='" + item.code + "'>" + item.chname + "</option>");
			option.appendTo(select);
		});

		select.multiselect('destroy').multiselect({
			maxHeight: 500,
			includeSelectAllOption: false,
			enableFiltering: true,
			filterPlaceholder: '查询',
			nonSelectedText: '请选择...',
			onChange: function(option, checked, select) {
				if(checked) {
					selectedClub = $(option).val();
				} else {
					selectedClub = "";
				}
			}
		});
	} else {
		ajax.get('club/list?lcode=' + lcode, function(result) {
			if(result.data && typeof(result.data) != undefined && lcode == '') {
				localStorage.setItem("club", JSON.stringify(result.data));
			}
			var select = $('#clubSelect');
			select.empty();
			var option = $("<option value=''>全部</option>");
			option.appendTo(select);
			result.data.forEach(function(item, i) {
				var option = $("<option value='" + item.code + "'>" + item.chname + "</option>");
				option.appendTo(select);
			});

			select.multiselect('destroy').multiselect({
				maxHeight: 500,
				includeSelectAllOption: false,
				enableFiltering: true,
				filterPlaceholder: '查询',
				nonSelectedText: '请选择...',
				onChange: function(option, checked, select) {
					if(checked) {
						selectedClub = $(option).val();
					} else {
						selectedClub = "";
					}
				}
			});
		});
	}
}

function bindProgramChild(childs) {
	var select = $('#programChildSelect');
	select.empty();
	var option = $("<option value=''>全部</option>");
	option.appendTo(select);
	childs.forEach(function(item, i) {
		var option = $("<option value='" + item.chname + "'>" + item.chname + "</option>");
		option.appendTo(select);
	});

	select.multiselect('destroy').multiselect({
		maxHeight: 500,
		includeSelectAllOption: false,
		enableFiltering: true,
		filterPlaceholder: '查询',
		nonSelectedText: '请选择...',
		onChange: function(option, checked, select) {
			if(checked) {
				selectedProgramChild = $(option).val();
			} else {
				selectedProgramChild = "";
			}
		}
	});
}

function bindData() {
	$("#selectFilter").hide();
	$("#wailt").show();
	$("#playerList").hide();

	var args = "";

	var name = $("#name").val();
	if(name) {
		args += '&n=' + encodeURI(name);
	}

	if(selectedRaritie) {
		args += '&r=' + selectedRaritie;
	}

	if(selectedJob) {
		args += '&j=' + selectedJob;
	}

	if(selectedNation) {
		args += '&nc=' + selectedNation;
	}

	if(selectedLeague) {
		args += '&lc=' + selectedLeague;
	}

	if(selectedClub) {
		args += '&cc=' + selectedClub;
	}

	if(selectedProgram) {
		var program = selectedProgram;
		if(selectedProgramChild) {
			program = selectedProgram + "-" + selectedProgramChild;
		}
		args += '&pc=' + encodeURI(program);
	}

	if(selectedSkill) {
		args += '&b=' + selectedSkill;
	}

	var foot = $("#footSelect").val();
	if(foot) {
		args += '&f=' + encodeURI(foot);
	}

	var height = $("#height").val();
	if(height) {
		args += '&h=' + h;
	}

	var scoreMin = $("#scoreMin").val();
	var scoreMax = $("#scoreMax").val();
	if(scoreMin || scoreMax) {
		if(scoreMin) {
			args += '&mi=' + scoreMin;
		}

		if(scoreMax) {
			args += '&ma=' + scoreMax;
		}
	}

	ajax.get('fifa/list2?1=1' + args, function(result) {
		cards = result.data;

		$("#wailt").hide();
		$("#playerList").show();

		buildCardList(cards)
	});
}

function buildInfo(code) {
	var max = 5;
	if(!IsPC()) {
		max = 3;
	}
	if(players.length < max) {
		ajax.get('fifamobile/card/detail?code=' + code, function(data) {
			ajax.get('levelup/list?gameCode=fifamobile&type=1&code=' + data.basicInfo.jobCode + '&level=' + data.basicInfo.score, function(result) {
				data.train = {};
				result.data.forEach(function(item) {
					data.train[item.level] = {};
					data.train[item.level].values = item.capabilityValues;
				})

				ajax.get('levelup/list?gameCode=fifamobile&type=2&code=' + data.skills.code + '&level=0', function(result) {
					data.boost = {};
					result.data.forEach(function(item) {
						data.boost[item.level] = {};
						data.boost[item.level].values = item.capabilityValues;
					})
					data.values = [];
					for(var i = 0; i < 20; i++) {
						data.values.push(data.capabilityValues.extend[i]);
					}
					data.selectTrain = data.basicInfo.score;
					data.selectBoost = 0;
					players.push(data);
					compare();
				});
			});
		});
	}
}

function deletePlayer(i) {
	players.splice(i, 1);
	compare();
}

function compare() {
	if(players.length == 0) {
		$("#msg").show();
		$("#compare").hide();
	} else {
		$("#msg").hide();
		$("#compare").show();
	}

	$("div[type]").show();
	for(var i = 0; i < 28; i++) {
		maxValue[i] = 0;
	}
	var heads = $("#heads");
	var infos = $("#infos");

	playerHead.forEach(function(item, i) {
		item.remove();
	});

	playerInfo.forEach(function(item, i) {
		item.remove();
	});

	players.forEach(function(player, i) {
		valueRefresh(player.code);
	})

	players.forEach(function(player, i) {
		var headBox = $('<div class="col-sm-2 col-xs-3 compare-column"></div>');
		var c = 'compare';
		if(!IsPC()) {
			c = 'mcompare'
		}
		var item = $("<div class='fm-card-img " + c + "'><img id='bg_" + player.code + "' class='background' width='100%' src='" +
			getBackground(player.basicInfo.programInfo.name, player.rarityValue, parseInt(player.selectTrain) + parseInt(player.selectBoost), player.basicInfo.programInfo.havebackground, player.basicInfo.bg) +
			"'><img id='head_" + player.code + "' class='player-img' width='100%' src='" +
			getHead(player.basicInfo.programInfo.name, player.basicInfo.no, parseInt(player.selectTrain) + parseInt(player.selectBoost), player.basicInfo.headcalcscore, player.basicInfo.head, player.basicInfo.headcount, player.basicInfo.havaas) + "'></div>");
		item.appendTo(headBox);

		item = $('<h5>' + player.name + '</h5>');
		item.appendTo(headBox);

		item = $('<button type="button" class="btn red btn-xs margin-bottom-10" onclick="deletePlayer(' + i + ')">删除球员</button>');
		item.appendTo(headBox);

		var levelSelect = '<select id="train_' + player.code + '" class="form-control">';
		for(var i = parseInt(player.basicInfo.score); i <= 100; i++) {
			levelSelect += '<option value="' + i + '">' + i + '</option>';
		}
		levelSelect += '</select>';
		item = $('<div class="compare-row compare-label">' + levelSelect + '</div>');
		item.appendTo(headBox)

		var skillSelect = '<select id="boost_' + player.code + '" class="form-control">';
		for(var i = 0; i <= 20; i++) {
			skillSelect += '<option value="' + i + '">' + i + '</option>';
		}
		skillSelect += '</select>';
		item = $('<div class="compare-row compare-label">' + skillSelect + '</div>');
		item.appendTo(headBox)

		headBox.appendTo(heads);
		playerHead.push(headBox);

		var infoBox = $('<div class="col-sm-2 col-xs-3 compare-column"></div>');

		item = $('<div class="compare-row compare-label"></div>');
		item.appendTo(infoBox)

		item = $('<div id="score_' + player.code + '" type="info" class="compare-row compare-label">' + (parseInt(player.selectTrain) + parseInt(player.selectBoost)) + '</div>');
		item.appendTo(infoBox)

		item = $('<div type="info" class="compare-row compare-label">' + player.basicInfo.job + '</div>');
		item.appendTo(infoBox)

		item = $('<div type="info" class="compare-row compare-label">' + (player.basicInfo.height ? player.basicInfo.height + 'cm' : '-') + '</div>');
		item.appendTo(infoBox)

		item = $('<div type="info" class="compare-row compare-label">' + (player.basicInfo.foot ? player.basicInfo.foot : '-') + '</div>');
		item.appendTo(infoBox)

		item = $('<div type="info" class="compare-row compare-label">' + player.skills.name + '</div>');
		item.appendTo(infoBox)

		item = $('<div type="info" class="compare-row compare-label">' + (player.basicInfo.traits ? player.basicInfo.traits : '') + '</div>');
		item.appendTo(infoBox)

		item = $('<div class="compare-row compare-label"><div></div></div>');
		item.appendTo(infoBox)

		var total = 0;
		values = getBasicValues(player.basicInfo.jobCode, player.values)
		for(var i = 0; i < 6; i++) {
			total += parseInt(values[i]);
			item = $('<div id="value' + i + '_' + player.code + '" type="basic" class="compare-row compare-label" index="' + i + '" data="' + values[i] + '">' + values[i] + '</div>');
			if(maxValue[i] < parseInt(values[i])) {
				maxValue[i] = parseInt(values[i]);
			}
			item.appendTo(infoBox);
		}

		item = $('<div id="value6_' + player.code + '" type="basic" class="compare-row compare-label" index="6" data="' + total + '">' + total + '</div>');
		if(maxValue[6] < total) {
			maxValue[6] = total;
		}
		item.appendTo(infoBox);

		item = $('<div class="compare-row compare-label"></div>');
		item.appendTo(infoBox);

		total = 0;
		for(var i = 0; i < 20; i++) {
			total += parseInt(player.values[i]);
			item = $('<div id="value' + (i + 7) + '_' + player.code + '" type="extend" class="compare-row compare-label" index="' + (i + 7) + '" data="' + player.values[i] + '">' + player.values[i] + '</div>');
			if(maxValue[i + 7] < parseInt(player.values[i])) {
				maxValue[i + 7] = parseInt(player.values[i]);
			}
			item.appendTo(infoBox)
		}

		item = $('<div id="value27_' + player.code + '" type="extend" class="compare-row compare-label" index="27" data="' + total + '">' + total + '</div>');
		if(maxValue[27] < total) {
			maxValue[27] = total;
		}
		item.appendTo(infoBox)

		infoBox.appendTo(infos);
		playerInfo.push(infoBox);

		$("#train_" + player.code).val(player.selectTrain);
		$("#train_" + player.code).bind('change', function() {
			player.selectTrain = $("#train_" + player.code).val();
			playerInfoChange(player.code);
		});

		$("#boost_" + player.code).val(player.selectBoost);
		$("#boost_" + player.code).bind('change', function() {
			player.selectBoost = $("#boost_" + player.code).val();
			playerInfoChange(player.code);
		});
	});

	$(".compare-label[index]").addClass("font-grey-salt");
	for(var i = 0; i < 28; i++) {
		$(".compare-label[index='" + i + "'][data='" + maxValue[i] + "']").addClass("font-red bold");
	}
}

function playerInfoChange(code) {
	compare();
}

function valueRefresh(code) {
	players.forEach(function(player, i) {
		if(player.code == code) {
			player.values = [];
			for(var i = 0; i < 20; i++) {
				player.values.push(player.capabilityValues.extend[i]);
			}

			for(var i = parseInt(player.basicInfo.score) + 1; i <= parseInt(player.selectTrain); i++) {
				for(var j = 0; j < 20; j++) {
					if(parseInt(player.values[j]) + parseInt(player.train[i].values[j]) > 120) {
						player.values[j] = 120;
					} else {
						player.values[j] = parseInt(player.values[j]) + parseInt(player.train[i].values[j]);
					}
				}
			}

			if(parseInt(player.selectBoost) > 0) {
				for(var i = 0; i < 20; i++) {
					if(parseInt(player.boost[parseInt(player.selectBoost)].values[i]) > 0) {
						var value = parseInt(player.values[i]);
						value = value + Math.round(parseInt(player.values[i]) * parseInt(player.boost[parseInt(player.selectBoost)].values[i]) / 100);
						if(value > 140) {
							player.values[i] = 140;
						} else {
							player.values[i] = value;
						}
					}
				}
			}
		}
	});

}

function buildCardList(cards) {
	if(dataTable) {
		dataTable.clear();
		dataTable.destroy();
	}

	cards.forEach(function(card, i) {
		var values = getBasicValues(card.basicInfo.jobCode, card.capabilityValues.extend);
		card.values = values;
	});

	dataTable = $('#playerList').DataTable({
		"data": cards,
		"deferRender": true,
		"destroy": true,
		columnDefs: [{
			targets: 0,
			orderable: false,
			width: "10%",
			render: function(data, type, row, meta) {
				return "<div class='fm-card-img'><img class='background' height='60' src='" +
					getBackground(row.basicInfo.programInfo.name, row.rarityValue, row.basicInfo.score, row.basicInfo.programInfo.havebackground, row.basicInfo.bg) +
					"'><img class='player-img' height='60' src='" +
					getHead(row.basicInfo.programInfo.name, row.basicInfo.no, row.basicInfo.score, row.basicInfo.headcalcscore, row.basicInfo.head, row.basicInfo.headcount, row.basicInfo.havaas) + "'></div>";
			}
		}, {
			targets: 1,
			width: "10%",
			render: function(data, type, row, meta) {
				return "<span class='bold'>" + row.basicInfo.score + "</span>";
			}
		}, {
			targets: 2,
			width: "50%",
			render: function(data, type, row, meta) {
				var html = "<span style='font-size:16px;' class='bold'>" + row.name + "</span>";
				html += "</br><span>" + row.basicInfo.job + "</span>";
				if(row.basicInfo.nationInfo) {
					html += " | <img style='width: 24px' title='" + row.basicInfo.nationInfo.name + "' src='" + row.basicInfo.nationInfo.icon + "'>";
				}

				if(row.basicInfo.leagueInfo) {
					html += " | <img style='width: 24px' title='" + row.basicInfo.leagueInfo.name + "' src='" + row.basicInfo.leagueInfo.icon + "'>";
				}

				if(row.basicInfo.clubInfo) {
					html += " | <img style='width: 24px' title='" + row.basicInfo.clubInfo.name + "' src='" + row.basicInfo.clubInfo.icon + "'>";
				}
				html += "</br><span>" + (row.basicInfo.programInfo.code == 'basic' ? '基本球员' : (row.basicInfo.programInfo.code == 'wc' ? '世界杯球员' : row.basicInfo.programInfo.name)) + "</span>";
				return html;
			}
		}, {
			targets: 3,
			width: "15%",
			render: function(data, type, row, meta) {
				return "<span class='bold'>" + (parseInt(row.values[0]) + parseInt(row.values[1]) +
					parseInt(row.values[2]) + parseInt(row.values[3]) + parseInt(row.values[4]) +
					parseInt(row.values[5])) + "</span>";
			}
		}, {
			targets: 4,
			width: "15%",
			render: function(data, type, row, meta) {
				var value = 0;
				for(var i = 0; i < row.capabilityValues.extend.length; i++) {
					value += parseInt(row.capabilityValues.extend[i]);
				}
				return "<span class='bold'>" + value.toString() + "</span>";
			}
		}, {
			targets: 5,
			className: "hidden",
			render: function(data, type, row, meta) {
				return "<span class='bold'>" + row.values[0] + "</span>";
			}
		}, {
			targets: 6,
			className: "hidden",
			render: function(data, type, row, meta) {
				return "<span class='bold'>" + row.values[1] + "</span>";
			}
		}, {
			targets: 7,
			className: "hidden",
			render: function(data, type, row, meta) {
				return "<span class='bold'>" + row.values[2] + "</span>";
			}
		}, {
			targets: 8,
			className: "hidden",
			render: function(data, type, row, meta) {
				return "<span class='bold'>" + row.values[3] + "</span>";
			}
		}, {
			targets: 9,
			className: "hidden",
			render: function(data, type, row, meta) {
				return "<span class='bold'>" + row.values[4] + "</span>";
			}
		}, {
			targets: 10,
			className: "hidden",
			render: function(data, type, row, meta) {
				return "<span class='bold'>" + row.values[5] + "</span>";
			}
		}, {
			targets: 11,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[0];
			}
		}, {
			targets: 12,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[1];
			}
		}, {
			targets: 13,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[2];
			}
		}, {
			targets: 14,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[3];
			}
		}, {
			targets: 15,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[4];
			}
		}, {
			targets: 16,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[5];
			}
		}, {
			targets: 17,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[6];
			}
		}, {
			targets: 18,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[7];
			}
		}, {
			targets: 19,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[8];
			}
		}, {
			targets: 20,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[9];
			}
		}, {
			targets: 21,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[10];
			}
		}, {
			targets: 22,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[11];
			}
		}, {
			targets: 23,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[12];
			}
		}, {
			targets: 24,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[13];
			}
		}, {
			targets: 25,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[14];
			}
		}, {
			targets: 26,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[15];
			}
		}, {
			targets: 27,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[16];
			}
		}, {
			targets: 28,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[17];
			}
		}, {
			targets: 29,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[18];
			}
		}, {
			targets: 30,
			className: "hidden",
			render: function(data, type, row, meta) {
				return row.capabilityValues.extend[19];
			}
		}],
		"bRetrieve": true,
		"searching": false,
		"lengthChange": false,
		"pageLength": 10,
		"deferRender": true,
		"language": {
			"lengthMenu": "显示 _MENU_ 条记录",
			"loadingRecords": "请等待，数据正在加载中......",
			"infoEmpty": "没有记录可以显示",
			"emptyTable": "无可用数据",
			"info": "",
			"paginate": {
				"first": "<<",
				"last": ">>",
				"next": ">",
				"previous": "<"
			}
		}
	});

	setTimeout(function() {
		$("#dataTables_paginate").parent().removeClass("col-md-7");
	}, 5000)
}

function clearFilter() {
	$("#name").val('');
	$("#height").val('');
	$("#foot").val('');

	$("#scoreMin").val('');
	$("#scoreMax").val('');

	$("#nationSelect").multiselect("deselect", selectedNation);
	selectedNation = "";

	$("#raritySelect").multiselect("deselect", selectedRaritie);
	selectedRaritie = "";

	$("#jobSelect").multiselect("deselect", selectedJob);
	selectedJob = "";

	$("#leagueSelect").multiselect("deselect", selectedLeague);
	selectedLeague = "";

	$("#clubSelect").multiselect("deselect", selectedClub);
	selectedClub = "";

	$("#programSelect").multiselect("deselect", selectedProgram);
	selectedProgram = "";
	selectedProgramChild = "";
	$("#programChildDiv").hide();

	$("#skillSelect").multiselect("deselect", selectedSkill);
	selectedSkill = "";
}<file_sep>/qingstorHandler.py
# -*- coding:utf-8 -*-

from qingstor.sdk.service.qingstor import QingStor
from qingstor.sdk.config import Config
import requests
import tempfile

# 初始化QingStor对象
config = Config('EBZAULNLJTMJJCZJWCRG', '02MLUQZA5wZPwTrOmVWUajPhNUSFI8c5VKu2Wf0u')
qingstor = QingStor(config)

# 获取bucket列表
# output = qingstor.list_buckets()
# print(output.status_code)
# print(output['buckets'])

# 获取指定bucket对象
bucket = qingstor.Bucket('fifa-helper-bucket', 'sh1a')

def getFileByKey(key):
    resp = bucket.get_object(key)
    with tempfile.NamedTemporaryFile() as f:
        for chunk in resp.iter_content():
            f.write(chunk)
    return f


def getRespByKey(key):
    resp = bucket.get_object(key)
    return resp


# 上传本地文件，图片使用'rb'格式，文档使用'r'
# with open('1625_IC1.png', 'rb') as f:
#     output = bucket.put_object(
#         'test-key', body=f
#     )
# print(output.status_code)

# 上传网络文件，图片使用'rb'格式，文档使用'r'
# r = requests.get('http://img.wantuole.com/resources/backgrouds/VIP2.png')
# output = bucket.put_object(
#     'test-key-2.png', body=r
# )
# print('结果：', output.status_code)

# 获取bucket文件列表
# output = bucket.list_objects()
# print(output.status_code)
# print("文件列表：", output['keys'])
#
# resp = bucket.head_object('test-key-2.png')
# print("文件状态：", resp.status_code)


# 根据key获取具体文件
# resp = bucket.get_object('test-key-2.png')
# with tempfile.NamedTemporaryFile() as f:
#     for chunk in resp.iter_content():
#         f.write(chunk)


# 根据key删除文件
# resp = bucket.delete('test-key-2.png')
# print("删除状态：", resp.status_code)<file_sep>/esHandler.py
# -*- coding: utf-8 -*-
import requests
import json
from elasticsearch import Elasticsearch

"""球员列表url"""
base_list_url = 'http://api.wantuole.com/api/fifa/list2?1=1&mi=%d&ma=%d'
base_list_url_with_job = 'http://api.wantuole.com/api/fifa/list2?1=1&j=%s&mi=%d&ma=%d'
"""国家列表url"""
nation_list_url = 'http://api.wantuole.com/api/nation/list'
"""联赛列表url"""
league_list_url = 'http://api.wantuole.com/api/league/list'
"""俱乐部列表url"""
club_list_url = 'http://api.wantuole.com/api/club/list?lcode='
"""天赋列表url"""
skill_list_url = 'http://api.wantuole.com/api/skill/list?gameCode=fifamobile'
"""天赋等级提升（单位：百分比）url"""
skill_level_capability_url = 'http://api.wantuole.com/api/levelup/list?gameCode=fifamobile&type=2&level=0&code='
"""位置等级提升url"""
job_level_capability_url = 'http://api.wantuole.com/api/levelup/list?gameCode=fifamobile&type=1&level=60&code='
"""活动列表url"""
program_list_url = 'http://api.wantuole.com/api/program/list?gameCode=fifamobile'
"""球员位置: 前锋 左边锋 右边锋 左内锋 中锋 右内锋 前腰 左前卫 中前卫 右前卫 后腰 左翼卫 左后卫 中后卫 右后卫 右翼卫 门将"""
job_list = ["ST", "LW", "RW", "LF", "CF", "RF", "CAM", "LM", "CM", "RM", "CDM", "LWB", "LB", "CB", "RB", "RWB", "GK"]
"""es连接"""
#TODO 设置最大连接数
es = Elasticsearch(['http://127.0.0.1:9200'])
"""球员索引"""
fifa_player_index = "fifa-player-index"
"""球员type"""
fifa_player_type = "fifa-player-type"
"""国家索引"""
fifa_nation_index = "fifa-nation-index"
"""国家type"""
fifa_nation_type = "fifa-nation-type"
"""联赛索引"""
fifa_league_index = "fifa-league-index"
"""联赛type"""
fifa_league_type = "fifa-league-type"
"""俱乐部索引"""
fifa_club_index = "fifa-club-index"
"""俱乐部type"""
fifa_club_type = "fifa-club-type"
"""天赋索引"""
fifa_skill_index = "fifa-skill-index"
"""天赋type"""
fifa_skill_type = "fifa-skill-type"
"""活动索引"""
fifa_program_index = "fifa-program-index"
"""活动type"""
fifa_program_type = "fifa-program-type"
"""天赋等级提升索引"""
fifa_skill_level_capability_index = 'fifa_skill_level_capability_index'
"""天赋等级提升type"""
fifa_skill_level_capability_type = 'fifa_skill_level_capability_type'
"""位置等级提升索引"""
fifa_job_level_capability_index = 'fifa_job_level_capability_index'
"""位置等级提升type"""
fifa_job_level_capability_type = 'fifa_job_level_capability_type'
"""默认取回200条数据"""
default_search_body = {"from": 0, "size": 200}

"""
从玩脱了爬取球员数据
"""
def downloadPlayersByURL(url):
    resp = requests.get(url)
    data = json.loads(resp.text)
    num = len(data['data'])
    print(url, ' ===》 数量：', num)
    p = {}
    for player in data['data']:
        setValue(p, player, 'code', 'code', None)
        setValue(p, player, 'name', 'name', None)
        setValue(p, player, 'rarityValue', 'rarityValue', None)
        setValue(p, player, 'rarity', 'rarity', None)
        """basicInfo"""
        setValue(p, player, 'no', 'basicInfo', 'no')
        setValue(p, player, 'enname', 'basicInfo', 'enname')
        setValue(p, player, 'score', 'basicInfo', 'score')
        setValue(p, player, 'jobCode', 'basicInfo', 'jobCode')
        setValue(p, player, 'job', 'basicInfo', 'job')
        p['nation'] = player['basicInfo']['nationInfo']['name']
        p['league'] = player['basicInfo']['leagueInfo']['name']
        p['club'] = player['basicInfo']['clubInfo']['name']
        p['program'] = player['basicInfo']['programInfo']['name']
        setValue(p, player, 'bg', 'basicInfo', 'bg')
        setValue(p, player, 'programicon', 'basicInfo', 'programicon')
        setValue(p, player, 'head', 'basicInfo', 'head')
        setValue(p, player, 'headcount', 'basicInfo', 'headcount')
        setValue(p, player, 'headcalcscore', 'basicInfo', 'headcalcscore')
        setValue(p, player, 'havaas', 'basicInfo', 'havaas')
        setValue(p, player, 'height', 'basicInfo', 'height')
        setValue(p, player, 'foot', 'basicInfo', 'foot')
        setValue(p, player, 'basicdownstatus', 'basicInfo', 'basicdownstatus')
        setValue(p, player, 'traits', 'basicInfo', 'traits')
        setValue(p, player, 'downstatus', 'basicInfo', 'downstatus')
        """capabilityValues"""
        setValue(p, player, 'capabilityValues', 'capabilityValues', 'extend')
        """skills"""
        setValue(p, player, 'skill_code', 'skills', 'code')
        setValue(p, player, 'skill_name', 'skills', 'name')

        print(p)
        #存入es
        es.index(index=fifa_player_index, doc_type=fifa_player_type, id=p['code'], body=p)
        player['basicInfo']['nationInfo']['name']
        background_pic_filename = getBackground(player['basicInfo']['programInfo']['name'], player['rarityValue'], player['basicInfo']['score'],
                                       player['basicInfo']['programInfo']['havebackground'],player['basicInfo']['bg'])
        background_url = getBackgroundURL(player['basicInfo']['programInfo']['name'], background_pic_filename)
        head_pic_filename = getHead(player['basicInfo']['programInfo']['name'], player['basicInfo']['no'], player['basicInfo']['score'],
                                 player['basicInfo']['headcalcscore'], player['basicInfo']['head'],
                                 player['basicInfo']['headcount'], player['basicInfo']['havaas'])
        head_url = getHeadURL(player['basicInfo']['programInfo']['name'], head_pic_filename)
        print('背景：', background_pic_filename, ' -> ', background_url)
        print('头像：', head_pic_filename, ' -> ', head_url)


def setValue(p1, p2, p1_colume, p2_colume1, p2_colume2):
    if p2_colume2 is None:
        p1[p1_colume] = p2[p2_colume1]
    elif p2_colume2 in p2[p2_colume1]:
        p1[p1_colume] = p2[p2_colume1][p2_colume2]
    else:
        p1[p1_colume] = None


"""
初始化球员索引
"""
def initPlayerIndex(min_score, max_score, split_score):
    # 删除原有索引
    es.indices.delete(index=fifa_player_index, ignore=[400, 404])
    # 重新创建索引
    es.indices.create(index=fifa_player_index, ignore=400)
    # 启用fielddata，关闭analyzed
    body = {
        "properties": {
            "score": {
                "type": "text",
                "fielddata": True
            }, "nation": {
                "type": "keyword"
            }, "league": {
                "type": "keyword"
            }, "club": {
                "type": "keyword"
            }, "job": {
                "type": "keyword"
            }, "skill": {
                "type": "keyword"
            }, "program": {
                "type": "keyword"
            }
        }
    }
    es.indices.put_mapping(index=fifa_player_index, doc_type=fifa_player_type, body=body)
    # 抓取球员数据
    downloadPlayers(min_score, max_score, split_score)


"""
爬取球员数据
"""
def downloadPlayers(min_score, max_score, split_score):
    i = max_score
    while i >= min_score:
        if i > split_score:
            downloadPlayersByURL(base_list_url%(i,i))
        else:
            for job in job_list:
                downloadPlayersByURL(base_list_url_with_job % (job, i, i))
        i = i-1

"""
初始化国家索引
"""
def initNationIndex():
    # 删除原有索引
    es.indices.delete(index=fifa_nation_index, ignore=[400, 404])
    # 重新创建索引
    es.indices.create(index=fifa_nation_index, ignore=400)
    # 爬取国家列表
    print(nation_list_url)
    resp = requests.get(nation_list_url)
    data = json.loads(resp.text)
    print(data)
    n = {}
    for nation in data['data']:
        setValue(n, nation, 'code', 'code', None)
        setValue(n, nation, 'icon', 'icon', None)
        setValue(n, nation, 'chname', 'chname', None)
        setValue(n, nation, 'enname', 'enname', None)
        print(n)
        es.index(index=fifa_nation_index, doc_type=fifa_nation_type, id=n['code'], body=n)


"""
search国家
"""
def searchNation():
    resp = es.search(index=fifa_nation_index, doc_type=fifa_nation_type, body=default_search_body)
    data = tranferDictWithUTF8(resp["hits"])
    print(data)
    return data


"""
初始化联赛/俱乐部索引
"""
def initLeagueAndClubIndex():
    # 删除原有索引
    es.indices.delete(index=fifa_league_index, ignore=[400, 404])
    es.indices.delete(index=fifa_club_index, ignore=[400, 404])
    # 重新创建索引
    es.indices.create(index=fifa_league_index, ignore=400)
    es.indices.create(index=fifa_club_index, ignore=400)
    # 关闭俱乐部analyzed，以便可以按照联赛全匹配
    body = {
        "properties": {
            "leagueName": {
                "type": "keyword"
            }
        }
    }
    es.indices.put_mapping(index=fifa_club_index, doc_type=fifa_club_type, body=body)
    # 爬取联赛列表
    print(league_list_url)
    resp = requests.get(league_list_url)
    data = json.loads(resp.text)
    print(data)
    n = {}
    for league in data['data']:
        setValue(n, league, 'code', 'code', None)
        setValue(n, league, 'icon', 'icon', None)
        setValue(n, league, 'chname', 'chname', None)
        setValue(n, league, 'enname', 'enname', None)
        print(n)
        es.index(index=fifa_league_index, doc_type=fifa_league_type, id=n['code'], body=n)
        # 爬取俱乐部列表
        print(club_list_url)
        resp2 = requests.get(club_list_url + n['code'])
        data2 = json.loads(resp2.text)
        print(data2)
        c = {'leagueName': n['chname']}
        for club in data2['data']:
            setValue(c, club, 'code', 'code', None)
            setValue(c, club, 'icon', 'icon', None)
            setValue(c, club, 'chname', 'chname', None)
            setValue(c, club, 'enname', 'enname', None)
            print(c)
            es.index(index=fifa_club_index, doc_type=fifa_club_type, id=c['code'], body=c)


"""
search联赛
"""
def searchLeague():
    resp = es.search(index=fifa_league_index, doc_type=fifa_league_type, body=default_search_body)
    data = tranferDictWithUTF8(resp["hits"])
    print(data)
    return data


"""
search俱乐部
"""
def searchClub(leagueName):
    body = {"from": 0, "size":500}
    if leagueName is not None:
        body['query'] = {'term': {'leagueName': leagueName}}
    resp = es.search(index=fifa_club_index, doc_type=fifa_club_type, body=body)
    data = tranferDictWithUTF8(resp["hits"])
    print(data)
    return data


"""
初始化天赋索引
"""
def initSkillIndex():
    # 删除原有索引
    es.indices.delete(index=fifa_skill_index, ignore=[400, 404])
    es.indices.delete(index=fifa_skill_level_capability_index, ignore=[400, 404])
    # 重新创建索引
    es.indices.create(index=fifa_skill_index, ignore=400)
    es.indices.create(index=fifa_skill_level_capability_index, ignore=400)
    # 取消analyzed，以便全匹配搜索
    # body = {'properties': {'code': {'type': 'keyword'}}}
    # es.indices.put_mapping(index=fifa_skill_level_capability_index, doc_type=fifa_skill_level_capability_type, body=body)
    # 爬取天赋列表
    print(skill_list_url)
    resp = requests.get(skill_list_url)
    data = json.loads(resp.text)
    print(data)
    n = {}
    for skill in data['data']:
        # 天赋
        setValue(n, skill, 'code', 'code', None)
        setValue(n, skill, 'name', 'name', None)
        print(n)
        es.index(index=fifa_skill_index, doc_type=fifa_skill_type, id=n['code'], body=n)
        # 天赋等级提升
        url2 = skill_level_capability_url+skill['code'];
        resp2 = requests.get(url2)
        data2 = json.loads(resp2.text)
        s = {'code': skill['code'], 'upData': data2['data']}
        es.index(index=fifa_skill_level_capability_index, doc_type=fifa_skill_level_capability_type, id=skill['code'], body=s)

"""
search天赋
"""
def searchSkill():
    resp = es.search(index=fifa_skill_index, doc_type=fifa_skill_type, body=default_search_body)
    data = tranferDictWithUTF8(resp["hits"])
    print(data)
    return data


"""
search天赋等级提升
"""
def searchSkillLevelCapability(code):
    # body = {'query': {'term': {'code': code}}}
    # resp = es.search(index=fifa_skill_level_capability_index, doc_type=fifa_skill_level_capability_type, body=body)
    resp = es.get(index=fifa_skill_level_capability_index, doc_type=fifa_skill_level_capability_type, id=code)
    data = tranferDictWithUTF8(resp["_source"])
    print(data)
    return data


"""
初始化活动索引
"""
def initProgramIndex():
    # 删除原有索引
    es.indices.delete(index=fifa_program_index, ignore=[400, 404])
    # 重新创建索引
    es.indices.create(index=fifa_program_index, ignore=400)
    # 爬取活动列表
    print(program_list_url)
    resp = requests.get(program_list_url)
    data = json.loads(resp.text)
    print(data)
    n = {}
    for program in data['data']:
        if program['isShow'] == '1':
            setValue(n, program, 'code', 'code', None)
            setValue(n, program, 'icon', 'icon', None)
            setValue(n, program, 'chname', 'chname', None)
            setValue(n, program, 'enname', 'enname', None)
            print(n)
            es.index(index=fifa_program_index, doc_type=fifa_program_type, id=n['code'], body=n)


"""
search活动
"""
def searchProgram():
    resp = es.search(index=fifa_program_index, doc_type=fifa_program_type, body=default_search_body)
    data = tranferDictWithUTF8(resp["hits"])
    print(data)
    return data


"""
初始化位置等级提升索引
"""
def initJobLevelCapabilityIndex():
    # 删除原有索引
    es.indices.delete(index=fifa_job_level_capability_index, ignore=[400, 404])
    # 重新创建索引
    es.indices.create(index=fifa_job_level_capability_index, ignore=400)
    # 取消analyzed，以便全匹配搜索
    # body = {'properties': {'code': {'type': 'keyword'}}}
    # es.indices.put_mapping(index=fifa_job_level_capability_index, doc_type=fifa_job_level_capability_type, body=body)
    # 爬取位置等级提升数据
    for job in job_list:
        url = job_level_capability_url+job;
        print(url)
        resp = requests.get(url)
        data = json.loads(resp.text)
        j = {'code': job, 'upData': data['data']}
        print(j)
        es.index(index=fifa_job_level_capability_index, doc_type=fifa_job_level_capability_type, id=j['code'], body=j)


"""
search位置等级提升
"""
def searchJobLevelCapability(code):
    # body = {'query': {'term': {'code': code}}}
    # resp = es.search(index=fifa_job_level_capability_index, doc_type=fifa_job_level_capability_type, body=body)
    resp = es.get(index=fifa_job_level_capability_index, doc_type=fifa_job_level_capability_type, id=code)
    data = tranferDictWithUTF8(resp["_source"])
    print(data)
    return data


"""
count球员
"""
def countPlayers():
    resp = es.count(index=fifa_player_index, doc_type=fifa_player_type)
    return str(resp['count'])

"""
count所有信息，包括球员/联赛/俱乐部/天赋/活动
"""
def countAll():
    player_count = es.count(index=fifa_player_index, doc_type=fifa_player_type)['count']
    league_count = es.count(index=fifa_league_index, doc_type=fifa_league_type)['count']
    club_count = es.count(index=fifa_club_index, doc_type=fifa_club_type)['count']
    skill_count = es.count(index=fifa_skill_index, doc_type=fifa_skill_type)['count']
    program_count = es.count(index=fifa_program_index, doc_type=fifa_program_type)['count']
    skill_updata_count = es.count(index=fifa_skill_level_capability_index, doc_type=fifa_skill_level_capability_type)['count']
    job_updata_count = es.count(index=fifa_job_level_capability_index, doc_type=fifa_job_level_capability_type)['count']
    result = {
        'player_count': player_count,
        'league_count': league_count,
        'club_count': club_count,
        'skill_count': skill_count,
        'program_count': program_count,
        'skill_updata_count': skill_updata_count,
        'job_updata_count': job_updata_count
    }
    return tranferDictWithUTF8(result)

"""
search球员
"""
def searchPlayers(min_score, max_score, name, nation, league, club, job, skill, program):
    body = {
        "from": 0, "size": 100,
        "query": {
            "bool": {
                "must": [
                ]
            }
        },
        "sort": {
            "score": {
                "order": "desc"
            }
        }
    }
    if min_score is not None or max_score is not None:
        score_range = {"range": {"score": {}}}
        if min_score is not None:
            score_range["range"]["score"]["gte"] = int(min_score)
        if max_score is not None:
            score_range["range"]["score"]["lte"] = int(max_score)
        body["query"]["bool"]["must"].append(score_range)
    if name is not None:
        name_match = {"match": {"name": name}}
        body["query"]["bool"]["must"].append(name_match)
    if nation is not None:
        nation_match = {"term": {"nation": nation}}
        body["query"]["bool"]["must"].append(nation_match)
    if league is not None:
        league_match = {"term": {"league": league}}
        body["query"]["bool"]["must"].append(league_match)
    if club is not None:
        club_match = {"term": {"club": club}}
        body["query"]["bool"]["must"].append(club_match)
    if job is not None:
        job_match = {"term": {"job": job}}
        body["query"]["bool"]["must"].append(job_match)
    if skill is not None:
        skill_match = {"term": {"skill": skill}}
        body["query"]["bool"]["must"].append(skill_match)
    if program is not None:
        program_match = {"term": {"program": program}}
        body["query"]["bool"]["must"].append(program_match)
    print(body)
    resp = es.search(index=fifa_player_index, doc_type=fifa_player_type, body=body)
    result = tranferDictWithUTF8(resp["hits"])
    print(result)
    return result

"""
将字典转为UTF8字符串
"""
def tranferDictWithUTF8(dict):
    result = json.dumps(dict, ensure_ascii=False).encode('utf-8')
    # print(type(result))
    return result


# ==================================================获取球员照片=======================================================
"""
获取背景图片URL
"""
def getBackgroundURL(pn, picFilename):
    imgUrl = "http://img.wantuole.com/resources/backgrouds/"
    return imgUrl + picFilename

def getBackground(pn, r, score, hb, bg):
    num = 0
    imgName = ""
    if int(hb) > 0:
        num = int((int(score) - 70) / 10)
        if bg == "CGER" or bg == 'SC' or bg == 'TC' or bg == 'T' or bg == 'TDYX' or pn.find('剧情精英球员') >= 0 or bg == 'ZCBase':
            num = int((int(score) - 50) / 10)
        elif bg == 'JLBZ':
            num = int((int(score) - 60) / 10)
        if pn == '世界杯球员':
            if num > 4:
                num = 4
        imgName = bg + str(num) + ".png"
    else:
        num = int((int(score) - 50) / 10);
        if bg != "BASIC":
            imgName = bg + str(num) + ".png"
        else:
            r_int = int(r)
            if r_int == 1:
                imgName = ""
            elif r_int == 2:
                imgName = "MR"
            elif r_int == 3:
                imgName = "ER"
            elif r_int == 4:
                imgName = "GR"
            elif r_int == 5:
                imgName = "SR"
            elif r_int == 6:
                imgName = "BR"
            imgName = imgName + str(num) + ".png"
    return imgName

"""
获取球员照片URL
"""
def getHeadURL(pn, picFilename):
    imgUrl = "http://img.wantuole.com/FIFA足球世界/players/"
    if pn == '世界杯球员':
        imgUrl = "http://img.wantuole.com/FIFA足球世界/wcplayers/"
    return imgUrl + picFilename

def getHead(pn, no, score, calcscore, head, count, haveas):
    imgUrl = "http://img.wantuole.com/FIFA足球世界/players/"
    if pn == '世界杯球员':
        imgUrl = "http://img.wantuole.com/FIFA足球世界/wcplayers/"
    num = 0
    imgName = ""

    if haveas != "" and int(haveas) == 1:
        if int(score) >= 80:
            if calcscore is not None:
                imgName = no + "_AS" + calcscore + ".png"
            else:
                imgName = no + "_AS.png"
        else:
            imgName = no + ".png"
    else:
        if head == "TOTW":
            #TODO 可能有bug
            if score is not None and score != "":
                imgName = no + "_" + head + calcscore + ".png"
            else:
                imgName = no + "_" + head + ".png"
        else:
            if count != "" and int(count) > 1:
                num = int((int(score) - int(calcscore)) / 10)
                if head == "IC" or head == "PI":
                    if num == 0:
                        num = 1
                if num > int(count):
                    num = int(count)
                imgName = no + "_" + head + str(num) + ".png"
            else:
                if head is not None and head != "":
                    if int(score) >= 80:
                        imgName = no + "_" + head + ".png"
                        if head == 'MM':
                            if score >= 100:
                                imgName = no + "_L" + head + ".png"
                        elif head == 'LVL':
                            if score >= 100:
                                imgName = no + "_LVLM.png"
                    else:
                        if calcscore == -1:
                            imgName = no + "_" + head + ".png"
                        else:
                            imgName = no + ".png"
                else:
                    imgName = no + ".png"
    return imgName