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

import pymysql
import requests

from base.BaseCore import BaseCore
requests.adapters.DEFAULT_RETRIES = 5
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'
# }
headers = {
    'X-TYCID':'30c1289042f511ee9182cd1e1bcaa517',
    # 'X-AUTH-TOKEN': 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMzU5MjQ4MTgzOSIsImlhdCI6MTY5MjkzMzIxMiwiZXhwIjoxNjk1NTI1MjEyfQ.BKxDem8fpgeDHrIgm3qCoF76ueHtQSG1DggiTl4FAaoNKt4gem6NTX1XYndPXqVj9TXfl-8yp2kKE3jY66dyig',
    'version':'TYC-Web',
    'Content-Type':'application/json;charset=UTF-8'
}
cnx = pymysql.connect(host='114.116.44.11', user='caiji', 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()
        headers['X-AUTH-TOKEN'] = baseCore.GetTYCToken()
        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]
            response.close()
            return retData['tycData']
        else:
            log.error(f"{xydm}------{retJsonData}")
            response.close()
            return retData['tycData']
    except:
        log.error(f"---{xydm}--天眼查token失效---")
        return retData['tycData']


# 更新天眼查企业基本信息
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()