import os
import time
from urllib.parse import urljoin

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


import BaseCore
baseCore = BaseCore.BaseCore()
log = baseCore.getLogger()

from reits import Policy
policy = Policy()
topic = 'research_center_fourth'
webname = '上海证券交易所REITs'
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, id_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
        # 上传附件至obs
        att_id, full_path = policy.attuributefile(fj_title, fj_href, num, publishDate)
        if att_id:
            id_list.append(att_id)
            a['href'] = full_path

    content = contentWithTag.text
    return pub_hao, content, id_list, contentWithTag


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:
            id_list = []
            title = li.find('a').text.lstrip().strip()
            href = li.find('a').get('href')
            # 根据链接判重
            is_member = baseCore.r.sismember('REITs::' + webname, href)
            if is_member:
                continue
            origin = '上海证券交易所'
            publishDate = li.find('i', class_='date').text.lstrip().strip()
            writtenDate = publishDate
            organ = '上海证券交易所'
            summary = ''
            pub_hao, content, id_list, contentWithTag = getContent(href, publishDate, num, id_list)
            time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            lang = baseCore.detect_language(content)
            dic_info = {
                'attachmentIds': id_list,
                'subjectId': '1729317767726682113',
                'lang': lang,
                'author': '',
                'content': content,
                'contentWithTag': str(contentWithTag),
                'deleteFlag': 0,
                'checkStatus': 1,
                'id': '1729317767726682113'+str(int(time.time())),
                'title': title,
                'publishDate': publishDate,
                'origin': origin,
                'sourceAddress': href,
                'writtenDate': writtenDate,
                'organ': organ,
                'topicClassification': '',
                'issuedNumber': pub_hao,
                'summary': summary,
                'createDate': time_now,
                'sid': '1729047166793469954',
            }
            try:
                baseCore.sendkafka(dic_info, topic)
                baseCore.r.sadd('REITs::' + webname, href)
                log.info(f'采集成功--{title}--{href}')
            except:
                for att_id in id_list:
                    baseCore.deliteATT(att_id)
            num += 1



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