# 天眼查商标申请数量
# 接口 https://capi.tianyancha.com/cloud-intellectual-property/intellectualProperty/trademarkList?_=1703216298337
# 请求方式 POST
import requests,time,re,random
from base import BaseCore
import pandas as pd
from bs4 import BeautifulSoup as bs
from comData.Tyc.getTycId import getTycIdByXYDM
baseCore = BaseCore.BaseCore()
cnx = baseCore.cnx
cursor = baseCore.cursor
log = baseCore.getLogger()
taskType = '天眼查商标/国内上市'

header = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        '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/120.0.0.0 Safari/537.36',
        'X-AUTH-TOKEN': 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxODcwMzc1MjYwMCIsImlhdCI6MTcwMjcxMjg4MywiZXhwIjoxNzA1MzA0ODgzfQ.mVTR6Wz7W_IBjf4rLYhKacG9CRxGTzIGKmlqrR9jN-_t0Z4vUYVYwOTMzo7vT9IClJELruhl4d31KBHX0bZ1NQ',
        'X-TYCID': '6f6298905d3011ee96146793e725899d',
        'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'version': 'TYC-Web'
    }

if __name__ == "__main__":
    while True:
        start_time = time.time()
        # 根据从Redis中拿到的社会信用代码,在数据库中获取对应基本信息
        # social_code = baseCore.redicPullData('ShangBiao:gnshSocial_code')
        social_code = '91130629MA0CG2DL51'
        # 判断 如果Redis中已经没有数据，则等待
        if social_code == None:
            # time.sleep(20)
            break
        start = time.time()
        try:
            data = baseCore.getInfomation(social_code)
            if len(data) != 0:
                pass
            else:
                # 数据重新塞入redis
                baseCore.rePutIntoR('ShangBiao:gnshSocial_code', social_code)
                continue
            id = data[0]
            com_name = data[1]
            xydm = data[2]
            tycid = data[11]
            if tycid == None or tycid == '':
                try:
                    retData = getTycIdByXYDM(xydm)
                    if retData['tycData'] and retData['reput']:
                        tycid = retData['tycData']['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('ShangBiao:gnshSocial_code', social_code)
                        continue
                    elif not retData['reput'] and not retData['tycData']:
                        continue
                except:
                    state = 0
                    takeTime = baseCore.getTimeCost(start, time.time())
                    baseCore.recordLog(social_code, taskType, state, takeTime, '', '获取天眼查id失败')
                    baseCore.rePutIntoR('ShangBiao:gnshSocial_code', social_code)
                    continue
            # count = data[17]
            log.info(f"{id}---{xydm}----{tycid}----开始处理")
            t = int(time.time()*1000)
            # url = f'https://capi.tianyancha.com/cloud-intellectual-property/intellectualProperty/trademarkList?_={t}'
            url = f'https://capi.tianyancha.com/cloud-intellectual-property/trademark/statistics?_={t}&cgid={tycid}'
            # tycid = '209252214'
            # payload = {"id": tycid, "ps": 10, "pn": 1, "int_cls": "-100", "status": "-100", "app_year": "-100",
            #            "regYear": "-100", "searchType": "-100", "category": "-100", "fullSearchText": "", "sortField": "",
            #            "sortType": "-100"}
            request = requests.get(url=url, headers=header, verify=False)
            # request = requests.post(url=url, headers=header, data=payload)
            # print(request.text)
            data_json = request.json()
            # print(data_json)
            try:
                all_data = data_json['data']['applyYearGraph']['statisticGraphData']
            except:
                dic_info = {
                    '企业名称': com_name,
                    '统一信用代码': social_code,
                }
                selectSql = f"select count(1) from shangbiao_sh_tyc where social_code='{xydm}' "
                cursor.execute(selectSql)
                count = cursor.fetchone()[0]
                if count > 0:
                    log.info(f"{com_name}----已经存在---无商标数据")
                    continue
                else:
                    values_tuple = tuple(dic_info.values())
                    # log.info(f"{gpdm}-------{companyname}---新增")
                    insertSql = f"insert into shangbiao_sh_tyc(com_name,social_code) values (%s,%s)"
                    cursor.execute(insertSql, values_tuple)
                    cnx.commit()
                    log.info(f"{com_name}-----新增---无商标数据")
                continue
            for info in all_data:
                year = info['desc']
                num = info['num']  # 申请商标数量
                dic_info = {
                    '企业名称': com_name,
                    '统一信用代码': social_code,
                    '年份': year,
                    '数量': num
                }
                selectSql = f"select count(1) from shangbiao_sh_tyc where social_code='{xydm}' and year='{year}' "
                cursor.execute(selectSql)
                count = cursor.fetchone()[0]
                if count > 0:
                    log.info(f"{com_name}-------{year}---已经存在")
                    continue
                else:
                    values_tuple = tuple(dic_info.values())
                    # log.info(f"{gpdm}-------{companyname}---新增")
                    insertSql = f"insert into shangbiao_sh_tyc(com_name,social_code,year,num) values (%s,%s,%s,%s)"
                    cursor.execute(insertSql, values_tuple)
                    cnx.commit()
                    log.info(f"{com_name}-------{year}---新增")
                time.sleep(2)
                # list_all_info.append(dic_info)
            log.info(f"【{xydm}】-----------end,耗时{baseCore.getTimeCost(start_time, time.time())}")
        except Exception as e:
            log.info(f'==={social_code}=====获取企业信息失败==={e}=')
            # 重新塞入redis
            baseCore.rePutIntoR('ShangBiao:gnshSocial_code', social_code)
            state = 0
            takeTime = baseCore.getTimeCost(start, time.time())
            baseCore.recordLog(social_code, taskType, state, takeTime, '', f'获取企业信息失败--{e}')
            time.sleep(5)

        break