import os
from urllib.parse import urljoin

import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
from base import BaseCore

baseCore = BaseCore.BaseCore()
log = baseCore.getLogger()
headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh-TW;q=0.9,zh;q=0.8',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Host': 'www.sse.com.cn',
    'Pragma': 'no-cache',
    'Referer': 'http://www.sse.com.cn/reits/regulation/rules/',
    'Upgrade-Insecure-Requests': '1',
    '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 Edg/119.0.0.0',
}


def paserUrl(html, listurl):
    # 获取所有的<a>标签和<img>标签
    if isinstance(html, str):
        html = BeautifulSoup(html, 'html.parser')

    links = html.find_all(['a', 'img'])
    # 遍历标签，将相对地址转换为绝对地址
    for link in links:
        if 'href' in link.attrs:
            link['href'] = urljoin(listurl, link['href'])
        elif 'src' in link.attrs:
            link['src'] = urljoin(listurl, link['src'])
    return html


def getFjContent(url):
    ip = baseCore.get_proxy()
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    return req.content


def getSoup(url):
    ip = baseCore.get_proxy()
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    soup = BeautifulSoup(req.text, 'html.parser')
    return soup


def getContent(url, publishDate, num):
    fjhref_list = ''
    fjtitle_list = ''
    soup = getSoup(url)
    soup = paserUrl(soup, 'http://www.sse.com.cn/')
    contentWithTag = soup.find('div', class_='allZoom')
    pub_hao = contentWithTag.find('p').text.lstrip().strip()
    a_list = contentWithTag.find_all('a')
    # 上传附件
    for a in a_list:
        fj_href = a.get('href')
        fj_title = a.get('title')
        category = os.path.splitext(fj_href)[1]
        if '.' not in category or '.cn' in category:
            continue
        if category not in fj_title:
            fj_title = fj_title + category
        fj_title = f'{num}-{publishDate}-{fj_title}'
        fjtitle_list += fj_title + '\n'
        fjhref_list += fj_href + '\n'
        fjcontent = getFjContent(fj_href)
        file = f'./相关政策/上海证券交易所/政策文件/{fj_title}'
        with open(file, 'wb') as f:
            f.write(fjcontent)
        log.info(f'{fj_title}===附件下载成功')
    content = contentWithTag.text
    return pub_hao, content,fjtitle_list,fjhref_list


def doJob():
    if not os.path.exists('./相关政策/上海证券交易所/政策文件'):
        os.makedirs('./相关政策/上海证券交易所/政策文件')
    data_list = []
    urls = ['http://www.sse.com.cn/reits/regulation/rules/', 'http://www.sse.com.cn/reits/regulation/guide/']
    num = 1
    for url in urls:
        soup = getSoup(url)
        soup = paserUrl(soup, 'http://www.sse.com.cn/')
        li_list = soup.find('ul', class_='list').find_all('li')
        for li in li_list:
            title = li.find('a').text.lstrip().strip()
            href = li.find('a').get('href')
            origin = '上海证券交易所'
            publishDate = li.find('i', class_='date').text.lstrip().strip()
            writtenDate = publishDate
            organ = '上海证券交易所'
            summary = ''
            pub_hao, content, fjtitle_list, fjhref_list = getContent(href, publishDate, num)
            data = [num, title, publishDate, origin, href, writtenDate, organ, pub_hao, summary, content, fjtitle_list,
                    fjhref_list]
            data_list.append(data)
            log.info(f'{title}===采集成功')
            num += 1
    df = pd.DataFrame(np.array(data_list))
    df.columns = ['序号', '标题', '发布时间', '来源', '原文链接', '发文时间', '发文机构', '发文字号', '摘要', '正文', '附件名称', '附件连接']
    df.to_excel('./相关政策/上海证券交易所/上海证券交易所政策文件.xlsx', index=False)


if __name__ == '__main__':
    doJob()
    baseCore.close()
