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

import time
from urllib.parse import quote
import requests
import urllib3
from 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,'
#     }
headers = {
        'Host': 'xcx.qcc.com',
        'Connection': 'keep-alive',
        'x-request-device-type': 'Android',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF XWEB/8391',
        'Content-Type': 'application/json',
        'Qcc-Version': '1.0.0',
        'authMini': 'Bearer f51dae1a2fcb109fa9ec58bd4a85e5c5',
        'xweb_xhr': '1',
        'xcx-version': '2023.09.27',
        'Qcc-Platform': 'mp-weixin',
        'Qcc-CurrentPage': '/company-subpackages/business/index',
        'Qcc-Timestamp': '1696661787803',
        'Qcc-RefPage': '/company-subpackages/detail/index',
        'Accept': '*/*',
        'Sec-Fetch-Site': 'cross-site',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty',
        'Referer': 'https://servicewechat.com/wx395200814fcd7599/307/page-frame.html',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh'
}
# 通过企业名称或信用代码获取企查查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 Exception as e:
            print(f'{e}-------------重试')
            time.sleep(5)
            continue
    time.sleep(2)
    #{'status': 40101, 'message': '无效的sessionToken!'} {'status': 401, 'message': '您的账号访问超频，请升级小程序版本'}
    if resp_dict['status']==40101:
        KeyNo = False
        log.info(f'====token失效====时间{baseCore.getTimeCost(start, time.time())}')
        return KeyNo
    if resp_dict['status']==401:
        KeyNo = False
        log.info(f'=======您的账号访问超频，请升级小程序版本=====时间{baseCore.getTimeCost(start, time.time())}')
        return KeyNo
    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 = 'null'
        else:
            KeyNo = 'null'
    except:
        KeyNo = False
        log.info(f'====token失效====时间{baseCore.getTimeCost(start,time.time())}')
        return KeyNo

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