import pymysql,ast
from flask import request
from DBUtils.PooledDB import PooledDB
from common.crm_change_standard import getStandardName


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()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    # sql = 'SELECT * FROM `tj_standard_order` WHERE standard_company_name = "%s" limit 1' % companyName
    sql = 'SELECT * FROM `tj_label_depth_all` WHERE company_name = "%s" limit 1' % companyName
    cursor.execute(sql)
    standard_order_info = cursor.fetchall()
    for row in standard_order_info:
        management_label = row['management_label']
        management_label_list = ast.literal_eval(management_label)
        for management_label_item in management_label_list:
            if "经营行业" in management_label_item:
                company_industry =management_label_item["经营行业"]
            else:
                company_industry = ''
    # print('company_industry',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_all` 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[8]
        hx_info_dict['product'] = row[6]
    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(',')
    print('productData',productData)
    print(type(productData))
    if productData and productData != ['']:
        if len(productData)>2:
            lable_data = productData[0:2]
        else:
            lable_data = productData
    else:
        lable_data = []
    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')
                standard_company_name = getStandardName(companyName)
                industryLable = industry_select(standard_company_name)
                hx_info_dict = hx_30s(standard_company_name)
                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