# -*- encoding:utf-8 -*-
# !/usr/bin/python
from elasticsearch import Elasticsearch
from flask import Flask, render_template, request
import json
import pymysql



# esuser = "admines"
# espassword = "adminGSBes"
# esip = "172.16.18.120"
# esport = 9201
# esip1 = "172.16.18.10"
# esport1 = 9200
# es = Elasticsearch([esip], http_auth=(esuser, espassword), port=esport)
# es1 = Elasticsearch([esip1], http_auth=(esuser, espassword), port=esport1)
esip = "43.247.184.94"
esport = 9200
esuser = "admines"
espassword = "adminGSBes"
es = Elasticsearch([esip], http_auth=(esuser, espassword), port=esport)
esip1 = "43.247.184.94"
esport1 = 7200
es1 = Elasticsearch([esip], http_auth=(esuser, espassword), port=7200)


# conn = pymysql.connect(host='43.247.184.94', port=9187, user='nice', passwd='Niceee@2020#@', db='ent_data')
# connection = pymysql.connect(host='43.247.184.94', port=9187, user='nice', passwd='Niceee@2020#@', db='test')
connection = pymysql.connect(host='47.95.76.74', port=3306, user='root', passwd='Gongsibao2018', db='ent_data')
# conn = pymysql.connect(host='47.95.76.74', port=3306, user='root', passwd='Gongsibao2018', db='ent_data')




def strQ2B(ustring):
    """全角转半角"""
    rstring = ""
    for uchar in ustring:
        inside_code = ord(uchar)
        if inside_code == 12288:  # 全角空格直接转换
            inside_code = 32
        elif (inside_code >= 65281 and inside_code <= 65374):  # 全角字符（除空格）根据关系转化
            inside_code -= 65248
        rstring += chr(inside_code)
    return rstring

def moneyTest(mycompanyname):
    connection = pymysql.connect(host='47.95.76.74', port=3306, user='root', passwd='Gongsibao2018', db='ent_data')
    cur = connection.cursor()
    result={}
    result["data"]=[]
    result["total"]=0
    # 工商接口
    resjq = es.search(index="bigdata_ic_gsb_company_op",
                      body={"query": {"term": {"company_name.raw": mycompanyname}}})
    if resjq["hits"]["hits"]:
        mycompanyinfo = resjq["hits"]["hits"][0]["_source"]
        # 所属行业
        global gsb_company_cate_1
        gsb_company_cate_1="未公开"
        if mycompanyinfo["gsb_company_cate_1"]:
            gsb_company_cate_1 = str(mycompanyinfo["gsb_company_cate_1"])
    # 商标接口
    resjq = es1.search(index="bigdata_middle_gsb_tm_info_9",
                       body={"size": 1000, "query": {"term": {"applicant_cn": mycompanyname}}})
    mytminfo = resjq["hits"]["hits"]
    yx = 0
    sqz = 0
    wx = 0
    ot = 0
    sb_num=0
    sb_money = 0
    if mytminfo:
        # 获得所需数组
        for i in mytminfo:
            if i["_source"]["status"] == 1:
                sqz += 1
            elif i["_source"]["status"] == 2 or i["_source"]["status"] == 3:
                yx += 1
            elif i["_source"]["status"] == 4:
                wx += 1
            else:
                ot += 1
        sb_now_num = yx
        #计算不同行业的商机
        sb_ql_select='select trademark_num from business where gsb_company_cate_1 = "%s"'%gsb_company_cate_1
        connection.ping(reconnect=True)
        cur.execute(sb_ql_select)
        data=cur.fetchone()
        data=max(data)
        if data != None:
            if sb_now_num < data:
                sb_num=data-sb_now_num
        sb_money = 899*sb_num

    if sb_num != 0:
        sb_dist={}
        sb_dist["name"]="商标"
        sb_dist["money"]=sb_money
        sb_dist["num"]=sb_num
        result["data"].append(sb_dist)


    # 作品著作权
    index_name = "bigdata_works_copyright_20200115"
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "works_author.raw": mycompanyname
                        }
                    }
                ]
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    zz_now_num=0
    if searched["hits"]["hits"]:
        zz_now_num=searched["hits"]["total"]

    #软件著作权
    index_name = "bigdata_software_copyright_20200115"
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "author_nationality.author_name.raw": mycompanyname
                        }
                    }
                ]
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    if searched["hits"]["hits"]:
        zz_now_num += searched["hits"]["total"]
    #  专利接口
    index_name = "bigdata_patent_bib"
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    }
                ]
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    fm_pub_count = searched["hits"]["total"]  # 发明公开量
    xx_pub_count = searched["hits"]["total"]  # 新型公开量
    wg_pub_count = searched["hits"]["total"]  # 新型公开量
    zl_now_num = 0
    if fm_pub_count + xx_pub_count + wg_pub_count>0:
        zl_now_num=fm_pub_count + xx_pub_count + wg_pub_count
    #专利潜在商机
    zl_money = 0
    zl_num=0
    zl_sql_select='select patent_num from business where gsb_company_cate_1 = "%s"'%gsb_company_cate_1
    connection.ping(reconnect=True)
    cur.execute(zl_sql_select)
    data1=cur.fetchone()
    data1=max(data1)
    if (fm_pub_count + xx_pub_count + wg_pub_count) < data1:
        zl_num=data1-zl_now_num
    if zl_num >0:
        zl_money = 5560*zl_num

    if zl_num!=0:
        zl_dist={}
        zl_dist["name"]="专利"
        zl_dist["money"]=zl_money
        zl_dist["num"]=zl_num
        result["data"].append(zl_dist)

    # 证照接口
    index_name = "enterprise_chain_license"
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "companyName.raw": mycompanyname
                        }
                    }
                ]
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    ICP_status = "未办理"
    EDI_status = "未办理"
    IDC_status = "未办理"
    web_status = "未办理"
    game_pub_status = "未办理"
    game_do_status = "未办理"


    for aggs in searched["hits"]["hits"]:

        if "licence" in aggs["_source"].keys():
            if aggs["_source"]["licence"] == "IDC许可证":
                ICP_status = "已办理"
            if aggs["_source"]["licence"] == "EDI许可证":
                EDI_status = "已办理"
            if aggs["_source"]["licence"] == "IDC许可证":
                IDC_status = "已办理"
            if aggs["_source"]["licence"] == "网络文化经营许可证":
                web_status = "已办理"
    # 游戏运营
    index_name = "enterprise_chain_game"
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "operation_unit.raw": mycompanyname
                        }
                    }
                ]
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    for aggs in searched["hits"]["hits"]:
        if "licence" in aggs["_source"].keys():
            if aggs["_source"]["licence"] == "IDC许可证":
                game_do_status = "已办理"

    # 游戏出版
    index_name = "enterprise_chain_game"
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "publishing_unit.raw": mycompanyname
                        }
                    }
                ]
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    for aggs in searched["hits"]["hits"]:
        if "licence" in aggs["_source"].keys():
            if aggs["_source"]["licence"] == "网络游戏出版备案":
                game_pub_status = "已办理"

    qs_status = "未办理"
    sc_status = "未办理"
    # 高新认证
    index_name = "enterprise_chain_gxgy"
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "companyName.raw": mycompanyname
                        }
                    }
                ]
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    gxqy_status = "未办理"
    if searched["hits"]["hits"]:
        mycompanyinfo = searched["hits"]["hits"][0]["_source"]

        if mycompanyinfo["techType"] == "国家高新":
            gxqy_status = "已办理"

    #潜在业务数量
    zz_num = 0
    icp_num = 0
    edi_num = 0
    idc_num = 0
    web_num = 0
    gm_pub_num = 0
    gm_do_num = 0
    qs_num = 0
    sc_num = 0
    gxqy_num = 0
    tax_num = 0
    #潜在业务金额
    zz_money = 0
    icp_money = 0
    edi_money = 0
    idc_money = 0
    web_money = 0
    gm_pub_money = 0
    gm_do_money = 0
    qs_money = 0
    sc_money = 0
    gxqy_money = 0
    tax_money = 0


    if ICP_status =="未办理":
        product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%IDC%",mycompanyname)
        connection.ping(reconnect=True)
        cur.execute(product_sql)
        data=cur.fetchone()
        if data:
            icp_num=1
            icp_money=2000
    if icp_num!=0:
        icp_dist={}
        icp_dist["name"]="ICP"
        icp_dist["money"]=icp_money
        icp_dist["num"]=icp_num
        result["data"].append(icp_dist)

    if EDI_status =="未办理":
        product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%EDI%",mycompanyname)
        connection.ping(reconnect=True)
        cur.execute(product_sql)
        data=cur.fetchone()
        if data:
            edi_num=1
            edi_money=8500
    if edi_num!=0:
        edi_dist={}
        edi_dist["name"]="EDI"
        edi_dist["money"]=edi_money
        edi_dist["num"]=edi_num
        result["data"].append(edi_dist)


    if IDC_status =="未办理":
        product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%IDC%",mycompanyname)
        connection.ping(reconnect=True)
        cur.execute(product_sql)
        data=cur.fetchone()
        if data:
            idc_num=1
            idc_money=50000
    if idc_num!=0:
        idc_dist={}
        idc_dist["name"]="IDC"
        idc_dist["money"]=idc_money
        idc_dist["num"]=idc_num
        result["data"].append(idc_dist)


    if web_status =="未办理":
        product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%网络文化经营许可证%",mycompanyname)
        connection.ping(reconnect=True)
        cur.execute(product_sql)
        data=cur.fetchone()
        if data:
            web_num=1
            web_money=20000
    if web_num!=0:
        web_dist={}
        web_dist["name"]="网络文化经营许可证"
        web_dist["money"]=web_money
        web_dist["num"]=web_num
        result["data"].append(web_dist)


    if game_pub_status =="未办理":
        product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%网络游戏出版备案%",mycompanyname)
        connection.ping(reconnect=True)
        cur.execute(product_sql)
        data=cur.fetchone()
        if data:
            gm_pub_num=1
            gm_pub_money=20000
    if gm_pub_num!=0:
        gm_pub_dist={}
        gm_pub_dist["name"]="网络游戏出版备案"
        gm_pub_dist["money"]=gm_pub_money
        gm_pub_dist["num"]=gm_pub_num
        result["data"].append(gm_pub_dist)


    if game_do_status =="未办理":
        product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%网络游戏运营备案%",mycompanyname)
        connection.ping(reconnect=True)
        cur.execute(product_sql)
        data=cur.fetchone()
        if data:
            gm_do_num=1
            gm_do_money=2000
    if gm_do_num!=0:
        gm_do_dist={}
        gm_do_dist["name"]="网络游戏运营备案"
        gm_do_dist["money"]=gm_do_money
        gm_do_dist["num"]=gm_do_num
        result["data"].append(gm_do_dist)

    if zz_now_num > 0:
        zz_importance="1"
    else:
        product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%作品著作权%",mycompanyname)
        connection.ping(reconnect=True)
        cur.execute(product_sql)
        data=cur.fetchone()
        if data:
            zz_num=1+zz_num
            zz_type="办理"
            zz_money=799+zz_money
        product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%软件著作权%",mycompanyname)
        connection.ping(reconnect=True)
        cur.execute(product_sql)
        data=cur.fetchone()
        if data:
            zz_num=zz_num+1
            zz_type="办理"
            zz_money=zz_money+599

    if zz_num!=0:
        zz_dist={}
        zz_dist["name"]="著作权"
        zz_dist["money"]=zz_money
        zz_dist["num"]=zz_num
        result["data"].append(zz_dist)


    if qs_status =="未办理":
        product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%食品生产许可证%",mycompanyname)
        connection.ping(reconnect=True)
        cur.execute(product_sql)
        data=cur.fetchone()
        if data:
            qs_num=1
            qs_money=3000
    if qs_num!=0:
        qs_dist={}
        qs_dist["name"]="食品生产许可证（QS）"
        qs_dist["money"]=qs_money
        qs_dist["num"]=qs_num
        result["data"].append(qs_dist)



    if sc_status =="未办理":
        product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%食品生产许可证%",mycompanyname)
        connection.ping(reconnect=True)
        cur.execute(product_sql)
        data=cur.fetchone()
        if data:
            sc_num=1
            sc_money=8000
    if sc_num!=0:
        sc_dist={}
        sc_dist["name"]="食品生产许可证（SC）"
        sc_dist["money"]=sc_money
        sc_dist["num"]=sc_num
        result["data"].append(sc_dist)

    if gxqy_status =="未办理":
        product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%高新企业认证%",mycompanyname)
        connection.ping(reconnect=True)
        cur.execute(product_sql)
        data=cur.fetchone()
        if data:
            gxqy_num=1
            gxqy_money=20000
    if gxqy_num!=0:
        gxqy_dist={}
        gxqy_dist["name"]="高新企业认证"
        gxqy_dist["money"]=gxqy_money
        gxqy_dist["num"]=gxqy_num
        result["data"].append(gxqy_dist)

    #税务筹划
    product_sql='SELECT * FROM tj_product_result_copy1_test_0317 where product_result like "%s" and companyname="%s"'%("%税收筹划%",mycompanyname)
    connection.ping(reconnect=True)
    cur.execute(product_sql)
    data=cur.fetchone()
    if data:
        tax_num=1
        tax_money=20000
    if tax_num!=0:
        tax_dist={}
        tax_dist["name"]="税收筹划"
        tax_dist["money"]=tax_money
        tax_dist["num"]=tax_num
        result["data"].append(tax_dist)
    sum_sj_money=sb_money+zl_money+zz_money+icp_money+edi_money+idc_money\
                 +web_money+gm_pub_money+gm_do_money\
                 +qs_money+sc_money+gxqy_money+tax_money

    result["total"]=sum_sj_money
    cur.close()
    connection.close()
    # print(result)
    return result




def moneyAPI(server):
    @server.route("/api/moneyAPI",methods = ['POST'])
    def APImoney():
        try:
            mycompanyname = request.get_json().get("mycompanyname")  # 得到问题
            r_1 = moneyTest(strQ2B(mycompanyname))
            if r_1:
                return r_1

            else:
                return json.dumps({"status": -1, "msg":"失败","data": 0}, ensure_ascii=False)
        except:
            return json.dumps({"status": -1, "msg":"调用服务出错","data": {}}, ensure_ascii=False)


# if __name__ == '__main__':
#     app.run(host='127.0.0.1', port=5000, debug=True)
    # app.run(host='172.16.18.120', port=9500, debug=True)
