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

import pymysql
import requests

from base.BaseCore import BaseCore
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
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()
cnx_ = baseCore.cnx
cursor_ = baseCore.cursor
taskType = '天眼查企业id/天眼查'
#根据信用代码获取天眼查id 企业名字等信息
def getTycIdByXYDM(xydm):
    retData={'state':False,'tycData':None,'reput':True}
    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'))
        if retJsonData['data'] and retJsonData['state']== 'ok':
            pass
        else:
            log.error(f"---{xydm}-未查询到该企业---")
            retData['reput'] = False
            return retData
        matchType=retJsonData['data'][0]['matchType']
        if matchType=='信用代码匹配':
            retData['state'] = True
            retData['tycData'] = retJsonData['data'][0]
            response.close()
            return retData
        else:
            log.error(f"{xydm}------{retJsonData}")
            response.close()
            return retData
    except:
        log.error(f"---{xydm}--天眼查token失效---")
        return retData


# 更新天眼查企业基本信息
def updateTycInfo():
    while True:
        # 根据从Redis中拿到的社会信用代码,在数据库中获取对应基本信息
        social_code = baseCore.redicPullData('NewsEnterprise:gnqy_socialCode')
        # social_code = '9111000066990444XF'
        # 判断 如果Redis中已经没有数据，则等待
        if social_code == None:
            time.sleep(20)
            continue
        start = time.time()

        data = baseCore.getInfomation(social_code)
        if len(data) != 0:
            pass
        else:
            # 数据重新塞入redis
            baseCore.rePutIntoR('NewsEnterprise:gnqy_socialCode', social_code)
            continue

        xydm = data[2]
        tycid = data[11]
        if tycid == None or tycid == '':
            try:
                retData = getTycIdByXYDM(xydm)
                if retData['tycData'] and retData['reput']:
                    tycid = retData['id']
                    # todo:写入数据库
                    updateSql = f"update EnterpriseInfo set TYCID = '{tycid}' where SocialCode = '{xydm}'"
                    cursor_.execute(updateSql)
                    cnx_.commit()
                elif not retData['tycData'] and retData['reput']:
                    state = 0
                    takeTime = baseCore.getTimeCost(start, time.time())
                    baseCore.recordLog(social_code, taskType, state, takeTime, '', '获取天眼查id失败')
                    log.info(f'======={social_code}====重新放入redis====')
                    baseCore.rePutIntoR('NewsEnterprise:gnqy_socialCode', social_code)
                    continue
                elif not retData['reput'] and not retData['tycData']:
                    continue
            except Exception as e:
                log.error(e)
                state = 0
                takeTime = baseCore.getTimeCost(start, time.time())
                baseCore.recordLog(social_code, taskType, state, takeTime, '', '获取天眼查id失败')
                baseCore.rePutIntoR('NewsEnterprise:gnqy_socialCode', social_code)
                continue

if __name__ == '__main__':
    updateTycInfo()