# 根据信用代码获取天眼查id
import json
import random
import time

import pymysql
import requests

from base.BaseCore import BaseCore

baseCore = BaseCore()
log = baseCore.getLogger()
headers={
    'X-AUTH-TOKEN':'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMzY4MzgxNjk4NCIsImlhdCI6MTY5MDE3ODYyOCwiZXhwIjoxNjkyNzcwNjI4fQ.VV3Zoa4RM5nVN8UXBc0-81KMGqLzTOme6rButeETGfFQi7p5h4ydg8CFrEsizr_iFwB3_BVaKR2o2xR-M4ipbQ',
    'X-TYCID':'77e997401d5f11ee9e91d5a0fd3c0b83',
    'version':'TYC-Web',
    'Content-Type':'application/json;charset=UTF-8'
}
cnx = pymysql.connect(host='114.116.44.11', user='root', password='f7s0&7qqtK', db='dbScore', charset='utf8mb4')
cursor= cnx.cursor()

#根据信用代码获取天眼查id 企业名字等信息
def getTycIdByXYDM(xydm):
    retData={'state':False,'tycData':None}
    url=f"https://capi.tianyancha.com/cloud-tempest/search/suggest/v3?_={baseCore.getNowTime(3)}"
    ip = baseCore.get_proxy()
    paramJsonData = {'keyword':xydm}
    try:
        headers['User-Agent'] = baseCore.getRandomUserAgent()
        response = requests.post(url,json=paramJsonData,headers=headers,verify=False, proxies=ip)
        time.sleep(random.randint(3, 5))
        retJsonData =json.loads(response.content.decode('utf-8'))
        matchType=retJsonData['data'][0]['matchType']
        if matchType=='信用代码匹配':
            retData['state'] = True
            retData['tycData'] = retJsonData['data'][0]
            return retData
        else:
            log.error(f"{xydm}------{retJsonData}")
            return retData
    except Exception as e:
        log.error(f"{xydm}---exception---{e}")
        return retData
# 更新天眼查企业基本信息
def updateTycInfo(id,retData):
    state= retData['state']
    if state :
        data = retData['tycData']
        updateSql=f"update tyc_com_info set state=3,update_date=now(),tycid='{data['id']}', type='{data['type']}',comName='{data['comName']}',name='{data['name']}'" \
              f",alias='{data['alias']}',logo='{data['logo']}',claimLevel='{data['claimLevel']}',regStatus='{data['regStatus']}' where id={id}"
    else:
        updateSql = f"update tyc_com_info set state=4,update_date=now()  where id={id}"
    cursor.execute(updateSql)
    cnx.commit()

#采集工作
def beginWork():
    while True :
        start =time.time()
        selectSql="select id,xydm from tyc_com_info where state=1 order by update_date asc ,id asc limit 1"
        cursor.execute(selectSql)
        data = cursor.fetchone()
        if data:
            pass
        else:
            log.info("没有数据了，结束脚本")
            break
        data_list = list(data)
        id = data_list[0]
        xydm = data_list[1]
        retData = getTycIdByXYDM(xydm)
        updateTycInfo(id,retData)
        log.info(f"{id}---{xydm}----处理完成，耗时：{baseCore.getTimeCost(start,time.time())}")
    cursor.close()
    cnx.close()
    # 释放资源
    baseCore.close()

if __name__ == '__main__':
    beginWork()