import pymysql,json
from flask import request
from DBUtils.PooledDB import PooledDB

MYSQL_HOST = '47.95.76.74'  # 外网地址
PORT = 3306  # 外网端口
USER = 'root'
PASSWORD = 'Gongsibao2018'
DB = 'ent_data'
pool = PooledDB(pymysql,8, host=MYSQL_HOST, user=USER, passwd=PASSWORD, db=DB, port=PORT)


# 根据公司名称获取企业自设订的行业
def industry_select(companyName):
    company_industry = ''
    conn = pool.connection()
    cursor = conn.cursor()
    sql = 'SELECT * FROM `tj_standard_order` WHERE standard_company_name = "%s" limit 1' % companyName
    cursor.execute(sql)
    standard_order_info = cursor.fetchall()
    for row in standard_order_info:
        company_industry = row[5]
        if company_industry:
            company_industry =company_industry
        else:
            company_industry = ''
    return company_industry
# print(industry_select('云选家网络科技(广东)有限公司'))
# 根据公司名称获取产品标签两个。知识产权信息；3个（商标、著作权、专利）；资产标签2个及分公司情况
def hx_30s(companyName):
    conn = pool.connection()
    cursor = conn.cursor()
    sql = 'SELECT * FROM `tj_label_depth` WHERE company_name = "%s"' % companyName
    cursor.execute(sql)
    company_hx_info = cursor.fetchall()
    hx_info_dict ={}
    for row in company_hx_info:
        hx_info_dict['company_base']  = row[1]
        hx_info_dict['knowledge_info'] =  row[3]
        hx_info_dict['product'] = row[5]
    return hx_info_dict

# 组装成输出的样子
'''
{
  "code": 200,
  "data": [
    {
      "lable_data": [
        "大型企业",
        "有限责任公司",
        "青年公司",
        "华北地区",
        "一枝独秀"
      ],
      "lable_type": "基本标签"
    }
  ],
  "message": "操作成功"
}
'''
def final_hx (company_industry,hx_info_dict):
    data = []
    productData_dict ={}
    industryData_dict ={}
    knowledgeData_dict ={}
    branchLable_dict ={}

    company_industry_list =[]
    company_industry_list.append(company_industry)
    industryData_dict['label_data'] = company_industry_list
    industryData_dict['label_type'] = '行业标签'
    data.append(industryData_dict)

    productData = hx_info_dict['product'].replace('[','').replace(']','').replace("'",'').replace(" ",'').split(',')
    if len(productData)>2:
        lable_data =  productData[0:2]
    else:
        lable_data = productData
    productData_dict['label_data'] = lable_data
    productData_dict['label_type'] = '产品标签'
    data.append(productData_dict)

    knowledgeData = hx_info_dict['knowledge_info'].replace('[','').replace(']','').replace("'",'').replace(" ",'').split(',')
    print(knowledgeData,"knowledgeData=====")
    knowledgeData_list =[]
    for knowledgeItem in knowledgeData:
        knowledgeItem = eval(knowledgeItem)
        for k,v in knowledgeItem.items():
            knowledgeData_list.append(v)
    knowledgeData_dict['label_data'] = knowledgeData_list
    knowledgeData_dict['label_type'] = '资产标签'
    data.append(knowledgeData_dict)

    baseData = hx_info_dict['company_base'].replace('[', '').replace(']', '').replace("'", '').replace(" ",'').split(',')
    branchData_list = []
    for base_item in baseData:
        base_item = eval(base_item)
        if '分公司数量' in base_item.keys():
            branch_info = base_item['分公司数量']
            branchData_list.append(branch_info)
    branchLable_dict['label_data'] = branchData_list
    branchLable_dict['label_type'] = '分公司标签'
    data.append(branchLable_dict)
    return data





# 获取公司名称及获取30s画像
def tj_30s_hx(server):
    @server.route('/gsb/api/company_hx', methods=['POST'])
    def company_30s_main():
        if request.method == 'POST':
            try:
                requestdata = request.json
                print(requestdata)
                companyName = requestdata.get('company_name')
                industryLable = industry_select(companyName)
                hx_info_dict = hx_30s(companyName)
                print(hx_info_dict, "hx_info_dict===")
                data = final_hx(industryLable, hx_info_dict)
                hx_30s_result = {"status": 0, "msg": "成功", "data": data}
            except  Exception as error:
                hx_30s_result = {"status": -1, "msg": "失败", "data": error}
            return hx_30s_result