from dao.treasure_name_es import NameEs
from collections import Counter
from dao.literal_meaning_es import ExplainEs
from service import preference_selecter
import random
from dao.treasure_name_dao import NameDao
from dao.literal_meaning_dao import WordDao


all_size = 20
find_size = 15


def statistics(name_type_dict,name_size_dict,json_result):
    name_type_list = []
    name_size_list = []
    for like_name in json_result:
        name_type_list.append(name_type_dict[like_name])
        name_size_list.append(name_size_dict[like_name])
    return name_type_list,name_size_list,len(json_result)

def precent_get(num_list,all_len):
    size_result_dict = {}
    for name_size in num_list.keys():
        size_result_dict[name_size] = num_list[name_size] / float(all_len)
    return size_result_dict

def  name_create(json_result):
    name_type_dict ,name_size_dict = preference_selecter.preference_meaning(json_result['preference'])
    name_type_list, name_size_list, all_len = statistics(name_type_dict,name_size_dict,json_result['preference'])

    name_type_num_dict = Counter(name_type_list)
    name_size_num_list = Counter(name_size_list)

    name_size_num_list = precent_get(name_size_num_list,all_len)
    name_type_num_list = precent_get(name_type_num_dict,all_len)
    namees = NameEs()
    result = {}
    all_num = 0
    name_list = []
    name_five_result = {}
    for item in name_type_num_list:
        if item not in result:
            result[item] = {}
        for name in name_size_num_list:
            if name not in result[item]:
                result[item][name] = ""
            result[item][name] = round(name_type_num_list[item] * name_size_num_list[name] * find_size)
            all_num += result[item][name]
            #带行业及地区
            # name_search_result = namees.select_name(item, name,json_result['city'],json_result['cate'], result[item][name])
            name_search_result = namees.select_name(item, name, result[item][name])

            if name_search_result:
                for search_name in name_search_result["hits"]['hits']:
                    name_list.append(search_name["_source"]['company_name'])
                    if str(search_name["_source"]['five_elements_type']) == "None":
                        name_five_result[search_name["_source"]['company_name']] = random.choice(["金", "木", "水", "火", "土"])
                    else:
                        name_five_result[search_name["_source"]['company_name']] = search_name["_source"][
                            'five_elements_type']

    surplus_num = all_size - len(name_list)
    if surplus_num > 0:
        null_result = namees.select_null(surplus_num)
        if null_result:
            for search_name in null_result["hits"]['hits']:
                name_list.append(search_name["_source"]['company_name'])

                if str(search_name["_source"]['five_elements_type']) == "None":
                    name_five_result[search_name["_source"]['company_name']] = random.choice(["金","木","水","火","土"])
                else:
                    name_five_result[search_name["_source"]['company_name']] = search_name["_source"]['five_elements_type']

    return name_list,name_five_result

def word_explain(name_list,name_five_result,json_result):
    explaines = ExplainEs()
    result = []
    for name in name_list:
        name_dict = {"name":"","explain":[],"company_name":"","five_elements_type":""}
        name_dict["company_name"] = json_result['city'].replace("市","") + name + json_result['cate'] + "有限公司"
        name_dict['name'] = name
        name_dict['five_elements_type'] = name_five_result[name]
        for word in name:
            word_dict = {}

            explain_result = explaines.select_explain(word)
            if explain_result:
                if explain_result['hits']['hits']:

                    word_dict[word] = explain_result['hits']['hits'][0]['_source']['explain']

                if not explain_result['hits']['hits']:
                    word_dict[word] = "暂无释义"
                name_dict['explain'].append(word_dict)
        result.append(name_dict)
    return result


def reserve(final_result_continue,name_list_final,json_result):
    already_name_dict = {"文雅":[["meili",""],["meili1",""],["meili2",""],["meili3",""],["meili",""],["meili1",""],["meili2",""],["meili3",""]],
                    "吉祥":[["meilsi",""],["meisali1",""],["meili2",""],["meili3",""],["meili",""],["meili1",""],["meili2",""],["meili3",""]],
                    "通俗":[["meilsai",""],["meili1",""],["meili2",""],["meili3",""],["meili",""],["meili1",""],["meili2",""],["meili3",""]]}
    already_word_dict = {"m":"zhihda","e":"dafhk"}

    name_type_dict, name_size_dict = preference_selecter.preference_meaning(json_result['preference'])
    name_type_list, name_size_list, all_len = statistics(name_type_dict, name_size_dict, json_result['preference'])

    name_type_num_dict = Counter(name_type_list)
    name_type_num_list = precent_get(name_type_num_dict, all_len)
    result = {}
    name_list = []
    name_five_result = {}


    for item in name_type_num_list:
        if item not in result:
            result[item] = {}

        result[item] = round(name_type_num_list[item] * 20)
        for name_data in already_name_dict[item][:result[item]]:
            name_list.append(name_data[0])
            if name_data[1] == "":
                name_five_result[name_data[0]] = random.choice(["金","木","水","火","土"])
            else:
                name_five_result[name_data[0]] = name_data[1]

    for name in name_list:
        if name not in name_list_final:
            name_dict = {"name": "", "explain": [], "company_name": "", "five_elements_type": ""}
            name_dict["name"] = name
            name_dict["company_name"] = json_result['city'].replace("市","") + name + json_result['cate'] + "有限公司"
            name_dict['five_elements_type'] = name_five_result[name]
            for word in name:
                word_dict = {}
                if word in already_word_dict:
                    word_dict[word] = already_word_dict[word]
                if word not in already_word_dict:
                    word_dict[word] = "暂无释义"
                name_dict['explain'].append(word_dict)
            final_result_continue.append(name_dict)
        if len(final_result_continue) == 20:
            break



    return final_result_continue


def mysql_reserve(final_name_list,json_result):
    name_type_dict ,name_size_dict = preference_selecter.preference_meaning(json_result['preference'])
    name_type_list, name_size_list, all_len = statistics(name_type_dict,name_size_dict,json_result['preference'])

    name_type_num_dict = Counter(name_type_list)
    name_size_num_list = Counter(name_size_list)

    name_size_num_list = precent_get(name_size_num_list,all_len)
    name_type_num_list = precent_get(name_type_num_dict,all_len)
    namedao = NameDao()
    result = {}
    all_num = 0
    name_five_result = {}
    for item in name_type_num_list:
        if item not in result:
            result[item] = {}
        for name in name_size_num_list:
            if name not in result[item]:
                result[item][name] = ""
            result[item][name] = round(name_type_num_list[item] * name_size_num_list[name] * find_size)
            all_num += result[item][name]
            # name_search_result = namedao.select_name_dao(item, name, json_result['city'], json_result['cate'],result[item][name])
            name_search_result = namedao.select_name_dao(item, name, result[item][name])

            if name_search_result:
                for search_name in name_search_result:
                    if len(final_name_list) < 20:
                        if search_name['company_name'] not in final_name_list:
                            final_name_list.append(search_name['company_name'])
                    if str(search_name['five_elements_type']) == None:
                        name_five_result[search_name['company_name']] = random.choice(
                            ["金", "木", "水", "火", "土"])
                    else:
                        name_five_result[search_name['company_name']] = search_name['five_elements_type']

    surplus_num = all_size - len(final_name_list)
    if surplus_num > 0:
        null_result = namedao.select_null_dao(surplus_num)
        if null_result:
            for search_name in null_result:
                if search_name['company_name'] not in final_name_list:
                    final_name_list.append(search_name['company_name'])

                if str(search_name['five_elements_type']) == "None":
                    name_five_result[search_name['company_name']] = random.choice(
                        ["金", "木", "水", "火", "土"])
                else:
                    name_five_result[search_name['company_name']] = search_name[
                        'five_elements_type']

    return final_name_list, name_five_result


def mysql_explain(name_list,name_five_result,json_result):
    worddao = WordDao()
    result = []
    for name in name_list:
        name_dict = {"name": "", "explain": [], "company_name": "", "five_elements_type": ""}
        name_dict["company_name"] = json_result['city'].replace("市", "") + name + json_result['cate'] + "有限公司"
        name_dict['name'] = name
        name_dict['five_elements_type'] = name_five_result[name]
        for word in name:
            word_dict = {}
            explain_result = worddao.select_explain_dao(word)

            if explain_result:
                word_dict[word] = explain_result[0]['explain']

            if not explain_result:
                word_dict[word] = "暂无释义"
            name_dict['explain'].append(word_dict)
        result.append(name_dict)
    return result



def company_name_explain(json_result):
    result_dict = {}
    name_list,name_five_result = name_create(json_result)
    if len(name_list) < 20:
        final_name_list, name_five_result = mysql_reserve(name_list,json_result)
        result = mysql_explain(final_name_list, name_five_result, json_result)
    else:
        result = word_explain(name_list,name_five_result,json_result)




    result_dict["orderId"]=json_result['orderId']
    result_dict["result_name"] = result
    return result_dict

