import datetime
import difflib
import hashlib
import json
import time, os

import pymysql
import requests
from xpinyin import Pinyin
from elasticsearch_ic import Elastic

DB_HOST = ""
DB_PORT = ""
DB_USER = ""
DB_PWD = ""
QCC_APPKEY = ""
QCC_SECRETKEY = ""
ES_HOST = ""
ES_USER = ""
ES_PWD = ""
ES_PORT = ""
# dbdict = os.environ
environDict  = os.environ
# environDict = json.loads(dbdict.get('ZYF'))
# print('获取环境变量',environDict)
# if environDict:
#     print(environDict, "---------------------------")
#     DB_HOST = environDict.get('DB_HOST')
#     DB_PORT = environDict.get('DB_PORT')
#     DB_USER = environDict.get('DB_USER')
#     DB_PWD = environDict.get('DB_PWD')
#     QCC_APPKEY = environDict.get('QCC_APPKEY')
#     QCC_SECRETKEY = environDict.get('QCC_SECRETKEY')
#     ES_HOST = environDict.get('ES_HOST')
#     ES_USER = environDict.get('ES_USER')
#     ES_PWD = environDict.get('ES_PWD')
#     ES_PORT = environDict.get('ES_PORT')
DB_HOST = environDict.get('DB_HOST')
DB_PORT = environDict.get('DB_PORT')
DB_USER = environDict.get('DB_USER')
DB_PWD = environDict.get('DB_PWD')
QCC_APPKEY = environDict.get('QCC_APPKEY')
QCC_SECRETKEY = environDict.get('QCC_SECRETKEY')
ES_HOST = environDict.get('ES_HOST')
ES_USER = environDict.get('ES_USER')
ES_PWD = environDict.get('ES_PWD')
ES_PORT = environDict.get('ES_PORT')


print(DB_HOST,DB_HOST,DB_PORT,ES_PORT)
print(type(DB_PORT),type(ES_PORT))

def findByType():
    conn = pymysql.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PWD, db="brg-ic-name")
    sql = 'SELECT * FROM gsb_newcity'
    # 获取游标
    cursor = conn.cursor()
    # 执行sql语句
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result


def getSizeNameByCompanyName(val, cityList):
    # val = "河北大世界科技有限公司"
    if val.strip() == "" or val.strip() == None or len(val.strip()) == 0:
        return ""
    if val.find("集团") >= 0:
        count = val.index("集团")
        return val[0:count]
    if val.find("(") >= 0:
        return getFrountStrByStr(val, "(")
    if val.find("（") >= 0:
        return getFrountStrByStr(val, "（")

    # 地域 + 公司名 + 行业特征 + 有限公司
    # 北京汉唐科技有限公司
    citycount = -1
    btcount = -1
    btList = getBTList()
    for cityName in cityList:
        cityName = cityName.split("+")
        if val.find(cityName[0]) >= 0:
            if val.index(cityName[0]) > len(cityName[0]):
                citycount = 0
                break
            else:
                citycount = len(cityName[0])
                break
        elif val.find(cityName[1]) >= 0:
            if val.index(cityName[1]) > len(cityName[1]):
                citycount = 0
                break
            else:
                citycount = len(cityName[1])
                break
    for bt in btList:
        btcount = chaindex(val, bt)
        if btcount >= 0:
            break
    zihaoStr = val[citycount:btcount]
    return zihaoStr


def chaindex(val, str):
    try:
        i = val.index(str)
        return i
    except:
        i = -1
        return i


def getFrountStrByStr(val, str):
    if val.find(str):
        valarr = val.split(str)
        fountStr = valarr[0]
        btList = getBTList()
        fountStrCount = 0
        for bt in btList:
            fountStrCount = chaindex(fountStr, bt)
            if fountStrCount >= 0:
                break
            else:
                fountStrCount = chaindex(val, str)
        return val[0:fountStrCount]
    return ""


def getSensitiveByLike(title):
    conn = pymysql.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PWD, db="brg-ic-name")
    sql = 'SELECT * FROM gsb_sensitive WHERE INSTR(title,"{}") or INSTR("{}",title)'.format(title, title)
    # 获取游标
    cursor = conn.cursor()
    # 执行sql语句
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result


def gsbSensitiveMnggetList(type, pinyin, title):
    conn = pymysql.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PWD, db="brg-ic-name")
    sql = "SELECT * FROM gsb_sensitive WHERE 1 = 1"
    if type != None and type != "":
        sql += " and type ={}".format(type)
    if pinyin != None and pinyin != "":
        sql += " and pinyin ='{}'".format(pinyin)
    if title != None and title != "":
        sql += " and title ='{}'".format(title)
    # 获取游标
    cursor = conn.cursor()
    # 执行sql语句
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result


def getBrandByLike(title):
    conn = pymysql.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PWD, db="brg-ic-name")
    sql = 'SELECT * FROM gsb_brand WHERE 1 = 1'
    if title != None and title != "":
        sql += " and '{}' like CONCAT('%',title,'%')".format(title)
    # 获取游标
    cursor = conn.cursor()
    # 执行sql语句
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result


def comNameForBidMnggetList(keyword):
    conn = pymysql.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PWD, db="brg-ic-name")
    sql = 'SELECT * FROM gsb_comnameforbid WHERE 1 = 1'
    if keyword != None and keyword != "":
        sql += " and keyword = '{}'".format(keyword)
    # 获取游标
    cursor = conn.cursor()
    # 执行sql语句
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result


def getCityByLike(title, type):
    conn = pymysql.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PWD, db="brg-ic-name")
    sql = 'SELECT * FROM gsb_newcity WHERE 1 = 1'
    if type != None and type != "":
        sql += " and LevelType ={}".format(type)
    if title != None and title != "":
        sql += " and '{}' like CONCAT('%',ShortName,'%')".format(title)
    # 获取游标
    cursor = conn.cursor()
    # 执行sql语句
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result


def getCitys(type, pinyin, title):
    conn = pymysql.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PWD, db="brg-ic-name")
    sql = 'SELECT * FROM gsb_newcity WHERE 1 = 1'
    if type != None and type != "":
        sql += " and LevelType ={}".format(type)
    if pinyin != None and pinyin != "":
        sql += " and Pinyin ='{}'".format(pinyin)
    if title != None and title != "":
        sql += " and ShortName ='{}'".format(title)
    # 获取游标
    cursor = conn.cursor()
    # 执行sql语句
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result


def getBTList():
    reslist = []
    reslist.append("文化")
    reslist.append("科技")
    reslist.append("管理")
    reslist.append("咨询")
    reslist.append("服务")
    reslist.append("传播")
    reslist.append("传媒")
    reslist.append("信息")
    reslist.append("企业")
    reslist.append("国际")
    reslist.append("影业")
    reslist.append("电子商务")
    reslist.append("网络")
    reslist.append("品牌")
    reslist.append("商贸")
    reslist.append("商务")
    reslist.append("科贸")
    reslist.append("贸易")
    reslist.append("广告")
    reslist.append("教育")
    reslist.append("体育")
    reslist.append("设计")
    reslist.append("生物")
    reslist.append("图文")
    reslist.append("建筑")
    reslist.append("规划")
    reslist.append("餐饮")
    reslist.append("翻译")
    reslist.append("医疗")
    reslist.append("安全")
    reslist.append("动画")
    reslist.append("健康")
    reslist.append("保险")
    reslist.append("环境")
    # reslist.append("环境科技")
    return reslist


def getBusinessTypeByName(name):
    res = ""
    name = name.strip()
    btList = getBTList()
    for bt in btList:
        if bt in name:
            res = bt
            break
    return res


def similarJudg(keyword, sizeName):
    # //判断相同
    if keyword == sizeName:
        return 2
    if sizeName in keyword:
        if len(keyword) > 4:
            n = int(difflib.SequenceMatcher(None, sizeName, keyword).quick_ratio() * 100)
            if n > 70:
                return 2
            else:
                return 1
        return
    # //判断相似
    if len(keyword) == len(sizeName):
        count = 0
        chars1 = list(keyword)
        chars2 = list(sizeName)
        for i in range(len(chars1)):
            if chars1[i] == chars2[i]:
                count += 1

        len1 = len(keyword)
        if len1 > 3:
            n = len1 - 2
        else:
            n = len1 - 1

        if count >= n:
            return 1

    else:
        if keyword in sizeName or sizeName in keyword:
            return 11
    return 0


def getPoint(i):
    if i == 0:
        return 0
    elif i == 1:
        return 1
    elif i == 32:
        return 50
    elif i == 53:
        return 50
    elif i == 54:
        return 50
    elif i == 55:
        return 50
    else:
        return 100


def pingyinJudg(str, strlist):
    if len(strlist) > 0:
        for s in strlist:
            if str == s:
                return None
            else:
                return str
    else:
        return str
    return str


def similarityJudg(str1, str2):
    s1 = list(str1)
    s2 = list(str2)
    len1 = len(s2)
    count = 0
    for i in range(len(s1)):
        for j in range(len(s2)):
            if s1[i] == s2[j]:
                count += 1
                continue
    b = round(count / len1, 2) * 100
    return int(b)


# def foursimilarityJudg(cityname,keyword,btname,name):
#     cchars = list(cityname)
#     kchars = list(keyword)
#     bchars = list(btname)
#     nchars = list(name)
#     len2 = len(nchars)
#     count = 0
#     for i in range(len(cchars)):
#         for j in range(len(nchars)):
#             if cchars[i] == nchars[j]:
#                 count += 1
#                 continue
#     b1 = round(count / len2, 4)
#     count = 0
#     for i in range(len(kchars)):
#         for j in range(len(nchars)):
#             if kchars[i] == nchars[j]:
#                 count += 1
#                 continue
#     b2 = round(count / len2, 4)
#     count = 0
#     for i in range(len(bchars)):
#         for j in range(len(nchars)):
#             if bchars[i] == nchars[j]:
#                 count += 1
#                 continue
#     b3 = round(count / len2, 4)
#     b = round((b1+b2+b3)*100,0)
#     return int(b)

def foursimilarityJudg(keywords, name):
    s1 = keywords
    s2 = name
    if "(" in s2:
        s2.replace("(", "")
        s2.replace(")", "")
    if "（" in s2:
        s2.replace("（", "")
        s2.replace("）", "")
    n = int(difflib.SequenceMatcher(None, s1, s2).quick_ratio() * 100)
    return n


def getLevel(i):
    if i < 50:
        return "高"
    elif i < 99:
        return "中"
    else:
        return "低"


def getLeveltwo(j):
    if j in range(1, 30):
        return "低"
    elif j in range(30, 70):
        return "中"
    elif j >= 70:
        return "高"
    else:
        return ""


def qccdb(seltime, cityname, keyword, btname, orgname, qccjson):
    conn = pymysql.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PWD, db="brg-ic-name")
    sql = 'INSERT INTO qcclog(seltime,cityname,keyword,btname,orgname,qccjson) VALUES ("%s","%s","%s","%s","%s","%s")' % (
        seltime, cityname, keyword, btname, orgname, qccjson)
    cursor = conn.cursor()
    # 执行sql语句
    conn.ping(reconnect=True)
    cursor.execute(sql)
    conn.commit()
    cursor.close()
    conn.close()
    return True


def getqccJSON(cityname, keyword, btname, url, orgname, keywords, AppKey, SecretKey, cityList, brandList, sensitiveList,
               similarCityList, identicalCityList):
    point = 0
    # time1 = time.time()
    url = url + "&keyword=" + keywords
    Timespan = int(time.time())
    apptimekeystr = AppKey + repr(Timespan) + SecretKey
    md5 = hashlib.md5()
    md5.update(apptimekeystr.encode())
    Token = md5.hexdigest()
    Token = Token.upper()
    headers = {
        "Timespan": repr(Timespan),
        "Token": Token
    }
    session = requests.Session()
    r = session.get(url=url, headers=headers)
    res = json.loads(r.text)
    writetime = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
    # writetime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
    # print(writetime)
    # log = open("qcclog.txt","w+",encoding="utf-8")
    # log.write(writetime+"\n"+"cityname:"+cityname+","+"keyword:"+keyword+","+"btname:"+btname+","+"orgname:"+orgname+"\n"+"企查查结果:"+str(res)+"\n")
    qccdb(writetime, cityname, keyword, btname, orgname, repr(res))
    count = -1
    jonamelist = []
    if len(res) == 0:
        print("code", "500", "message", "数据无响应")
        jsondata = {
            "code": "200",
            "level": getLevel(point),
            "point": point,
            "cityList": cityList,
            "brandList": brandList,
            "sensitiveList": sensitiveList,
            "similarCityList": similarCityList,
            "identicalCityList": identicalCityList,
            "msg": "查询完成"
        }
        jsondata = json.dumps(jsondata, ensure_ascii=False)
        return jsondata
    else:
        status = res["Status"]
        Paging = res["Paging"]
        count = 0
        if status == '201':
            # if Paging != None:
            #     if len(Paging) == 0:
            #         count = -1
            # else:
            count = -1
            jsondata = {
                "code": "200",
                "level": getLevel(point),
                "point": point,
                "cityList": cityList,
                "brandList": brandList,
                "sensitiveList": sensitiveList,
                "similarCityList": similarCityList,
                "identicalCityList": identicalCityList,
                "msg": "查询完成"
            }
            jsondata = json.dumps(jsondata, ensure_ascii=False)
            return jsondata
        elif status == '200':
            if len(Paging) != 0:
                count = Paging["TotalRecords"]
                print("企查查查询数量：" + repr(count))
                # 判断相似相同
                jsonArray = res["Result"]
                for jo in jsonArray:
                    name = jo["Name"]
                    if name not in jonamelist:
                        jonamelist.append(name)
        else:
            jsondata = {
                "code": "200",
                "level": getLevel(point),
                "point": point,
                "cityList": cityList,
                "brandList": brandList,
                "sensitiveList": sensitiveList,
                "similarCityList": similarCityList,
                "identicalCityList": identicalCityList,
                "msg": "查询完成"
            }
            jsondata = json.dumps(jsondata, ensure_ascii=False)
            return jsondata

    # 查询未知
    bdDicts = findByType()
    cityNameList = []
    for bdDict in bdDicts:
        strlong = bdDict[2]
        strshort = bdDict[3]
        strinfo = strlong + "+" + strshort
        cityNameList.append(strinfo)
    joi = 0
    if count > -1:
        # time8 = time.time()
        for name in jonamelist:
            if joi < 20 and len(similarCityList) < 10:
                name = name.strip()
                joi += 1
                # businessType = getBusinessTypeByName(name)
                # if len(businessType) == 0 or businessType == None or (
                #         btname not in businessType and businessType not in btname):
                #     continue
                sizeName = getSizeNameByCompanyName(name, cityNameList)
                # 判断相似
                n = similarJudg(keyword, sizeName)
                # 计算相似度
                sim = foursimilarityJudg(keywords, name)

                city = dict(id=0, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = name.replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = sim
                city["levels"] = getLeveltwo(city["per"])
                if n == 1:
                    similarCityList.append(city)
                elif n == 2 and len(identicalCityList) < 3:
                    identicalCityList.append(city)
                elif n == 11:
                    similarCityList.append(city)

                point += getPoint(n)
        # time9=time.time()
        # print("for name 循环时间"+repr(time9-time8))
        res = getJSON(keyword, point, cityList, brandList, sensitiveList, similarCityList, identicalCityList)
        return res


def getgsbJSON(cityname, keyword, btname, orgname, setcity, keywords, cityList, brandList, sensitiveList,
               similarCityList, identicalCityList):
    # time2=time.time()
    params = {
        "cityname": cityname,
        "keyword": keyword,
        "btname": btname,
        "orgname": orgname,
        "setcity": setcity
    }
    point = 0
    count = -1
    es = Elastic(ES_HOST,ES_USER,ES_PWD,ES_PORT)
    jes = es.es_search(params)
    status = jes["Status"]
    if status == 400:
        jsondata = {
            "code": "200",
            "level": getLevel(point),
            "point": point,
            "cityList": cityList,
            "brandList": brandList,
            "sensitiveList": sensitiveList,
            "similarCityList": similarCityList,
            "identicalCityList": identicalCityList,
            "msg": "查询完成"
        }
        jsondata = json.dumps(jsondata, ensure_ascii=False)
        return jsondata
    elif status == 200:
        Paging = jes["Paging"]
        count = 0
        if len(Paging) != 0:
            count = Paging["TotalRecords"]
            print("公司宝查询数量：" + repr(count))

    jsonArray = jes["Result"]
    jonamelist = []
    for jo in jsonArray:
        name = jo["Name"]
        if name not in jonamelist:
            jonamelist.append(name)
    # time3 = time.time()
    # print("企查查时间"+repr(time2-time1))
    # print(time3-time2)
    # print(time3-time1)
    # 判断相似相同
    # 查询未知
    bdDicts = findByType()
    cityNameList = []
    for bdDict in bdDicts:
        strlong = bdDict[2]
        strshort = bdDict[3]
        strinfo = strlong + "+" + strshort
        cityNameList.append(strinfo)
    joi = 0
    if count > -1:
        # time8 = time.time()
        for name in jonamelist:
            if joi < 20 and len(similarCityList) < 10:
                name = name.strip()
                joi += 1
                # businessType = getBusinessTypeByName(name)
                # if len(businessType) == 0 or businessType == None or (
                #         btname not in businessType and businessType not in btname):
                #     continue

                sizeName = getSizeNameByCompanyName(name, cityNameList)

                # 判断相似
                n = similarJudg(keyword, sizeName)
                # 计算相似度
                sim = foursimilarityJudg(keywords, name)

                city = dict(id=0, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = name.replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = sim
                city["levels"] = getLeveltwo(city["per"])
                if n == 1:
                    similarCityList.append(city)
                elif n == 2 and len(identicalCityList) < 3:
                    identicalCityList.append(city)
                elif n == 11:
                    similarCityList.append(city)

                point += getPoint(n)
        # time9=time.time()
        # print("for name 循环时间"+repr(time9-time8))
        res = getJSON(keyword, point, cityList, brandList, sensitiveList, similarCityList, identicalCityList)
        return res


def getgsbqccJSON(cityname, keyword, btname, url, orgname, setcity, keywords, AppKey, SecretKey, cityList, brandList,
                  sensitiveList, similarCityList, identicalCityList):
    point = 0
    # time1 = time.time()
    url = url + "&keyword=" + keywords
    Timespan = int(time.time())
    apptimekeystr = AppKey + repr(Timespan) + SecretKey
    md5 = hashlib.md5()
    md5.update(apptimekeystr.encode())
    Token = md5.hexdigest()
    Token = Token.upper()
    headers = {
        "Timespan": repr(Timespan),
        "Token": Token
    }
    session = requests.Session()
    r = session.get(url=url, headers=headers)
    res = json.loads(r.text)
    writetime = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
    # writetime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
    # print(writetime)
    # log = open("qcclog.txt","w+",encoding="utf-8")
    # log.write(writetime+"\n"+"cityname:"+cityname+","+"keyword:"+keyword+","+"btname:"+btname+","+"orgname:"+orgname+"\n"+"企查查结果:"+str(res)+"\n")
    qccdb(writetime, cityname, keyword, btname, orgname, repr(res))
    # 优先使用企查查数据
    jsonArray = []
    total = 0
    if len(res) == 0:
        print("code", "500", "message", "数据无响应")
    else:
        status = res["Status"]
        Paging = res["Paging"]
        count = 0
        if status == '200':
            if len(Paging) != 0:
                count = Paging["TotalRecords"]
                jsonArray = res["Result"]
                print("企查查查询数量：" + repr(count))
        total += count
    # time2=time.time()

    # 公司宝数据查询
    params = {
        "cityname": cityname,
        "keyword": keyword,
        "btname": btname,
        "orgname": orgname,
        "setcity": setcity
    }
    es = Elastic(ES_HOST,ES_USER,ES_PWD,ES_PORT)
    jes = es.es_search(params)
    status = jes["Status"]
    if status == 200:
        Paging = jes["Paging"]
        count = 0
        if len(Paging) != 0:
            count = Paging["TotalRecords"]
            # 追加gsb数据
            jsonArray += jes["Result"]
            print("公司宝查询数量：" + repr(count))
        total += count

    if total > 0:
        jonamelist = []
        for jo in jsonArray:
            name = jo["Name"]
            if name not in jonamelist:
                jonamelist.append(name)
        # time3 = time.time()
        # print("企查查时间"+repr(time2-time1))
        # print(time3-time2)
        # print(time3-time1)
        # 判断相似相同
        # 查询未知
        bdDicts = findByType()
        cityNameList = []
        for bdDict in bdDicts:
            strlong = bdDict[2]
            strshort = bdDict[3]
            strinfo = strlong + "+" + strshort
            cityNameList.append(strinfo)
        joi = 0
        # time8 = time.time()
        for name in jonamelist:
            if joi < 20 and len(similarCityList) < 10:
                name = name.strip()
                joi += 1
                # businessType = getBusinessTypeByName(name)
                # if len(businessType) == 0 or businessType == None or (
                #         btname not in businessType and businessType not in btname):
                #     continue

                sizeName = getSizeNameByCompanyName(name, cityNameList)

                # 判断相似
                n = similarJudg(keyword, sizeName)
                # 计算相似度
                sim = foursimilarityJudg(keywords, name)

                city = dict(id=0, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = name.replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = sim
                city["levels"] = getLeveltwo(city["per"])
                if n == 1:
                    similarCityList.append(city)
                elif n == 2 and len(identicalCityList) < 3:
                    identicalCityList.append(city)
                elif n == 11:
                    similarCityList.append(city)

                point += getPoint(n)
        # time9=time.time()
        # print("for name 循环时间"+repr(time9-time8))
        res = getJSON(keyword, point, cityList, brandList, sensitiveList, similarCityList, identicalCityList)
        return res
    else:
        jsondata = {
            "code": "200",
            "level": getLevel(point),
            "point": point,
            "cityList": cityList,
            "brandList": brandList,
            "sensitiveList": sensitiveList,
            "similarCityList": similarCityList,
            "identicalCityList": identicalCityList,
            "msg": "查询完成"
        }
        jsondata = json.dumps(jsondata, ensure_ascii=False)
        return jsondata


def getJSON(keyword, point, cityList, brandList, sensitiveList, similarCityList, identicalCityList):
    clist = []
    # 判断敏感词
    # time10 = time.time()
    sp = 0
    senlist = getSensitiveByLike(keyword)
    if len(senlist) > 0:
        sp = 31
        for s in senlist:
            str = pingyinJudg(s[1], clist)
            if str != None:
                city = dict(id=1, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = s[1].replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = similarityJudg(keyword, s[1])
                city["levels"] = getLeveltwo(city["per"])
                city["pinyin"] = s[3]
                if len(sensitiveList) < 10:
                    sensitiveList.append(city)
                clist.append(s[1])

        point += getPoint(sp)
    Pin = Pinyin()
    list1 = gsbSensitiveMnggetList("", Pin.get_pinyin(keyword, splitter=" "), "")
    if len(list1) > 0:
        sp = 32
        for s in list1:
            str = pingyinJudg(s[1], clist)
            if str != None:
                city = dict(id=1, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = s[1].replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = 50
                city["levels"] = getLeveltwo(city["per"])
                city["pinyin"] = s[3]
                if len(sensitiveList) < 10:
                    sensitiveList.append(city)
                clist.append(s[1])

        point += getPoint(sp)
    # time11 = time.time()
    # print("判断敏感词时间"+repr(time11-time10))
    # 判断驰名商标
    # time12 = time.time()
    bp = 0
    list2 = getBrandByLike(keyword)
    if len(list2) > 0:
        bp = 4
        for b in list2:
            city = dict(id=1, name="", title="", pinyin="", per="", type="", levels="")
            city["name"] = b[1]
            city["title"] = b[2]
            city["per"] = similarityJudg(keyword, b[1])
            city["levels"] = getLeveltwo(city["per"])
            city["pinyin"] = Pin.get_pinyin(b[1], splitter=" ")
            if len(brandList) < 10:
                brandList.append(city)

        point += getPoint(bp)

    cList = comNameForBidMnggetList(keyword)
    if len(cList) != 0:
        point += 200
        city = dict(id=1, name="", title="", pinyin="", per="", type="", levels="")
        city["name"] = "<em>{}</em>".format(keyword)
        city["title"] = "禁用字号"
        city["per"] = 100
        city["levels"] = getLeveltwo(city["per"])
        if len(brandList) < 10:
            brandList.append(city)
    # time13 = time.time()
    # print("判断驰名商标"+repr(time13-time12))
    # 判断城市
    # time14 = time.time()
    cp = 0
    list3 = getCityByLike(keyword, "1")
    if len(list3) > 0:
        cp = 51
        for g in list3:
            str = pingyinJudg(g[3], clist)
            if str != None:
                city = dict(id=1, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = g[3].replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = similarityJudg(keyword, g[3])
                city["levels"] = getLeveltwo(city["per"])
                if len(cityList) < 10:
                    cityList.append(city)
                clist.append(g[3])
        point += getPoint(cp)

    list4 = getCityByLike(keyword, "2")
    if len(list4) > 0:
        cp = 51
        for g in list4:
            str = pingyinJudg(g[3], clist)
            if str != None:
                city = dict(id=1, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = g[3].replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = similarityJudg(keyword, g[3])
                city["levels"] = getLeveltwo(city["per"])
                if len(cityList) < 10:
                    cityList.append(city)
                clist.append(g[3])

        point += getPoint(cp)
    list5 = getCitys("3", "", keyword)
    if len(list5) > 0:
        cp = 52
        for g in list5:
            str = pingyinJudg(g[3], clist)
            if str != None:
                city = dict(id=1, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = g[3].replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = similarityJudg(keyword, g[3])
                city["levels"] = getLeveltwo(city["per"])
                if len(cityList) < 10:
                    cityList.append(city)
                clist.append(g[3])

        point += getPoint(cp)
    list6 = getCityByLike(keyword, "3")
    if len(list6) > 0:
        cp = 53
        for g in list6:
            str = pingyinJudg(g[3], clist)
            if str != None:
                city = dict(id=1, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = g[3].replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = similarityJudg(keyword, g[3])
                city["levels"] = getLeveltwo(city["per"])
                if len(cityList) < 10:
                    cityList.append(city)
                clist.append(g[3])

        point += getPoint(cp)
    list7 = getCitys("1", Pin.get_pinyin(keyword, splitter=" "), "")
    if len(list7) > 0:
        cp = 54
        for g in list7:
            str = pingyinJudg(g[3], clist)
            if str != None:
                city = dict(id=1, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = g[3].replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = 50
                city["levels"] = getLeveltwo(city["per"])
                if len(cityList) < 10:
                    cityList.append(city)
                clist.append(g[3])

        point += getPoint(cp)
    list8 = getCitys("2", Pin.get_pinyin(keyword, splitter=" "), "")
    if len(list8) > 0:
        cp = 55
        for g in list8:
            str = pingyinJudg(g[3], clist)
            if str != None:
                city = dict(id=1, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = g[3].replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = 50
                city["levels"] = getLeveltwo(city["per"])
                if len(cityList) < 10:
                    cityList.append(city)
                clist.append(g[3])

        point += getPoint(cp)
    list9 = getCitys("3", Pin.get_pinyin(keyword, splitter=" "), "")
    if len(list9) > 0:
        cp = 55
        for g in list9:
            str = pingyinJudg(g[3], clist)
            if str != None:
                city = dict(id=1, name="", title="", pinyin="", per="", type="", levels="")
                city["name"] = g[3].replace(keyword, "<em>{}</em>".format(keyword))
                city["per"] = 50
                city["levels"] = getLeveltwo(city["per"])
                if len(cityList) < 10:
                    cityList.append(city)
                clist.append(g[3])

        point += getPoint(cp)
    # time15 = time.time()
    # print("判断城市时间"+repr(time15-time14))
    jsondata = {
        # "企查查时间" : repr(time2 - time1),
        # "for name 循环时间" : repr(time9 - time8),
        # "判断敏感词时间" : repr(time11 - time10),
        # "判断驰名商标" : repr(time13 - time12),
        # "判断城市时间" : repr(time15 - time14),
        "code": "200",
        "level": getLevel(point),
        "point": point,
        "cityList": cityList,
        "brandList": brandList,
        "sensitiveList": sensitiveList,
        "similarCityList": similarCityList,
        "identicalCityList": identicalCityList,
        "msg": "查询完成"
    }
    # else:
    #     jsondata = {
    #         "code": status,
    #         "message": "数据库无数据",
    #         "data": {}
    #     }
    # jsondata = json.dumps(jsondata, ensure_ascii=False)
    return jsondata


def inputinfo(cityname, keyword, btname, url, orgname, setcity, appkey, AppKey, SecretKey):
    cityname = cityname
    # 北京，地区
    keyword = keyword
    # 汉唐，字号
    btname = btname
    # 科技，行业类型
    orgname = orgname
    # 有限公司，公司类型，默认：有限公司，可能有股份有限公司，集团公司等等，需要王驰给与建议
    if setcity == 2:
        keywords = keyword + "（" + cityname + "）" + btname + orgname
    elif setcity == 3:
        keywords = keyword + btname + "（" + cityname + "）" + orgname
    else:
        keywords = cityname + keyword + btname + orgname
    # 地区在字号中的位置
    senlist = getSensitiveByLike(keyword)
    Brandlist = getBrandByLike(keyword)
    citylist = getCityByLike(keyword, "")
    cList = comNameForBidMnggetList(keyword)
    cityList = []
    brandList = []
    sensitiveList = []
    similarCityList = []
    identicalCityList = []
    if len(senlist) + len(Brandlist) + len(citylist) + len(cList) == 0:
        # 去查询es
        res = getqccJSON(cityname, keyword, btname, url, orgname, setcity, keywords, AppKey, SecretKey, appkey,
                         cityList, brandList, sensitiveList, similarCityList, identicalCityList)
    else:
        point = 0
        similarCityList = []
        identicalCityList = []
        res = getJSON(keyword, point, cityList, brandList, sensitiveList, similarCityList, identicalCityList)
    return res


def heming(eventdict):
    print(eventdict)
    # 查询数据方式，1:公司宝，2：企查查，3：混合模式
    search_type = eventdict['search_type']
    # search_type = 1
    cityname = eventdict["cityname"]  # 北京，地区
    keyword = eventdict["keyword"]  # 汉唐，字号
    btname = eventdict["btname"]  # 科技，行业类型
    orgname = eventdict["orgname"]  # 有限公司，公司类型，默认：有限公司，可能有股份有限公司，集团公司等等，需要王驰给与建议
    sitcity = eventdict["sitcity"]
    print(type(sitcity),sitcity,'------------------------------')

    # 有限公司，公司类型，默认：有限公司，可能有股份有限公司，集团公司等等，需要王驰给与建议
    try:
        if sitcity == 2:
            print('222222222222222222222222')

            keywords = keyword + "（" + cityname + "）" + btname + orgname
        elif sitcity == 3:
            keywords = keyword + btname + "（" + cityname + "）" + orgname
        else:
            print('11111111111111111111111')
            keywords = cityname + keyword + btname + orgname
    except Exception as e:
        print('qqqqqqqqqqqqqqqqqqqqqqqqqq')

    # 地区在字号中的位置
    senlist = getSensitiveByLike(keyword)
    Brandlist = getBrandByLike(keyword)
    citylist = getCityByLike(keyword, "")
    cList = comNameForBidMnggetList(keyword)
    cityList = []
    brandList = []
    sensitiveList = []
    similarCityList = []
    identicalCityList = []
    AppKey = QCC_APPKEY
    SecretKey = QCC_SECRETKEY
    if len(senlist) + len(Brandlist) + len(citylist) + len(cList) == 0:
        if search_type == 1:  # 按照检索方式去查询es
            res = getgsbJSON(cityname, keyword, btname, orgname, sitcity, keywords, cityList, brandList, sensitiveList,
                             similarCityList, identicalCityList)
        elif search_type == 2:  # 请求qcc数据接口
            # 企查查数据接口Appkey，查询数据库
            url = "http://api.qichacha.com/ECIV4/Search?key=" + AppKey + "&pageSize=20"
            res = getqccJSON(cityname, keyword, btname, url, orgname, keywords, AppKey, SecretKey, cityList, brandList,
                             sensitiveList, similarCityList, identicalCityList)
        elif search_type == 3:  # 混合请求数据
            # 企查查数据接口Appkey，查询数据库
            url = "http://api.qichacha.com/ECIV4/Search?key=" + AppKey + "&pageSize=20"
            res = getgsbqccJSON(cityname, keyword, btname, url, orgname, sitcity, keywords, AppKey, SecretKey, cityList,
                                brandList, sensitiveList, similarCityList, identicalCityList)
    else:
        point = 0
        similarCityList = []
        identicalCityList = []
        res = getJSON(keyword, point, cityList, brandList, sensitiveList, similarCityList, identicalCityList)

    print("---------------------------",res)
    return res
