
# -*- coding: utf-8 -*-

import time
from urllib.parse import quote
import requests
import urllib3
from base.BaseCore import BaseCore

baseCore = BaseCore()
log = baseCore.getLogger()
headers = {
        'Host': 'xcx.qcc.com',
        'Connection': 'keep-alive',
        'Qcc-Platform': 'mp-weixin',
        'Qcc-Timestamp': '',
        'Qcc-Version': '1.0.0',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
        'content-type': 'application/json',
        'Referer': 'https://servicewechat.com/wx395200814fcd7599/166/page-frame.html',
        'Accept-Encoding': 'gzip, deflate, br,'
    }
# 通过企业名称或信用代码获取企查查id
def find_id_by_name(start,token,name):
    urllib3.disable_warnings()

    qcc_key = name
    t = str(int(time.time()) * 1000)
    headers['Qcc-Timestamp'] = t
    url = f"https://xcx.qcc.com/mp-weixin/forwardApp/v3/base/advancedSearch?token={token}&t={t}&pageIndex=1&needGroup=yes&insuredCntStart=&insuredCntEnd=&startDateBegin=&startDateEnd=&registCapiBegin=&registCapiEnd=&countyCode=&province=&sortField=&isSortAsc=&searchKey={quote(qcc_key)}&searchIndex=default&industryV3="
    for lll in range(1, 6):
        try:
            resp_dict = requests.get(url=url, headers=headers, verify=False).json()
            break
        except:
            print('重试')
            time.sleep(5)
            continue
    time.sleep(2)
    try:
        if resp_dict['result']['Result']:
            result_dict = resp_dict['result']['Result'][0]
            KeyNo = result_dict['KeyNo']
            Name = result_dict['Name'].replace('<em>', '').replace('</em>', '').strip()
            if Name == '':
                KeyNo = ''
        else:
            KeyNo = ''
    except:
        KeyNo = False
        log.info(f'====token失效====时间{baseCore.getTimeCost(start,time.time())}')
        return KeyNo

    print("{}，企业代码为:{}".format(qcc_key, KeyNo))
    return KeyNo