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

import pymysql
import requests

sys.path.append('D:\\kkwork\\zzsn_spider\\base')
import BaseCore
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
requests.adapters.DEFAULT_RETRIES = 5
baseCore = BaseCore.BaseCore()
log = baseCore.getLogger()
headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Content-Length': '32',
        'Content-Type': 'application/json',
        'Host': 'capi.tianyancha.com',
        'Origin': 'https://www.tianyancha.com',
        'Referer': 'https://www.tianyancha.com/',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-site',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
        'X-AUTH-TOKEN': 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxODcwMzc1MjYwMCIsImlhdCI6MTY5NzE5MDMwMywiZXhwIjoxNjk5NzgyMzAzfQ.awXuS-59RzK35r0aUJq4Rj83JzyAOvsdUfL_ojp66CVQMjlLv_ZDD9g5gCoZKE21LN1JYRMLNZhuWsHhxapROw',
        'X-TYCID': '6f6298905d3011ee96146793e725899d',
        'sec-ch-ua': '"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'version': 'TYC-Web'
}
# 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()