import pandas as pd
import requests

headers = {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Host': 'datacenter.eastmoney.com',
        'Origin': 'https://emweb.securities.eastmoney.com',
        'Referer': 'https://emweb.securities.eastmoney.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/119.0.0.0 Safari/537.36',
        'sec-ch-ua': '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"'
    }

df_1 = pd.read_excel('./需要补全的数据.xlsx', dtype=str)
for j in range(len(df_1)):
    code = df_1['A股代码'][j]
    code1 = str(code)
    while True:
        if len(code1)<6:
            code1 = '0'+code1
        else:
            break
    if code1[0] == '0' or code1[0] == '3':
        com_code = 'SZ'+code1
    elif code1[0] == '6':
        com_code = 'SH'+code1
    elif code1[0] == '8' or code1[0] == '4':
        com_code = 'BJ'+code1

    url = f'https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_F10_EH_RELATION&columns=SECUCODE%2CSECURITY_CODE%2CHOLDER_NAME%2CHOLD_RATIO&quoteColumns=&filter=(SECUCODE%3D%22{code1}.{com_code[:2]}%22)(RELATED_RELATION%3D%22%E5%AE%9E%E9%99%85%E6%8E%A7%E5%88%B6%E4%BA%BA%22)&pageNumber=1&pageSize=&sortTypes=&sortColumns=&source=HSF10&client=PC&v=05061020920974106'

    request = requests.get(url=url,headers=headers)
    json_data = request.json()
    controlling_person = []
    dic_info = {}
    try:
        info_list = json_data['result']['data']
    except:
        continue
    for info in info_list:
        holder_name = info['HOLDER_NAME']
        holde_ratio = info['HOLD_RATIO']
        dic_info['totalratio'] = holde_ratio
        try:
            controlling_person = holder_name.split(',')
            for name in controlling_person:
                dic_info[name] = ''
        except:
            continue
    print(dic_info)

    holders = []
    url_1 = f'https://datacenter.eastmoney.com/securities/api/data/v1/get?reportName=RPT_F10_EH_HOLDERS&columns=SECUCODE%2CSECURITY_CODE%2CEND_DATE%2CHOLDER_RANK%2CHOLDER_NAME%2CSHARES_TYPE%2CHOLD_NUM%2CHOLD_NUM_RATIO%2CHOLD_NUM_CHANGE%2CCHANGE_RATIO&quoteColumns=&filter=(SECUCODE%3D%22{code1}.{com_code[:2]}%22)(END_DATE%3D%272023-09-30%27)&pageNumber=1&pageSize=&sortTypes=1&sortColumns=HOLDER_RANK&source=HSF10&client=PC&v=09613150754547122'
    request = requests.get(url=url_1, headers=headers)
    json_data_1 = request.json()
    try:
        top_holders = json_data_1['result']['data']
    except:
        continue
    for holder in top_holders:
        holder_name_1 = holder['HOLDER_NAME']
        holde_ratio_1 = holder['HOLD_NUM_RATIO']
        for name in controlling_person:
            if name == holder_name_1:
                holders.append(f'{holder_name_1}({holde_ratio_1}%)')
                dic_info[name] = holde_ratio_1
    print(dic_info)
    if dic_info['totalratio']:
        ratio = sum(value for value in dic_info.values() if value)
        for key, value in dic_info.items():
            if value == "" or value is None:
                dic_info[key] = dic_info['totalratio'] - ratio
                holders.append(f'{key}({dic_info[key]}%)')
    else:
        del dic_info['totalratio']
        for key, value in dic_info.items():
            holders.append(f'{key}')
    print(holders)
    result = ','.join(holders)
    print(result)
    df_1['实控人'][j] = str(result)
    df_1.to_excel('./需要补全的数据.xlsx', index=False)
