import os
import time
from datetime import datetime
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 = 'policy'
webname = '天津市人民政府'

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh-TW;q=0.9,zh;q=0.8',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Host': 'www.tj.gov.cn',
    'Pragma': 'no-cache',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    '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',
    'sec-ch-ua': '"Microsoft Edge";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
}


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 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 getTotal():
    ip = baseCore.get_proxy()
    url = 'https://www.tj.gov.cn/igs/front/search.jhtml?code=78778b9ded5140d4984030cf8f469303&pageNumber=1&pageSize=10&searchWord=REITs&siteId=34&sortByFocus=true&type=21515&type1=21519'
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    total = req.json()['page']['totalPages']
    return int(total)


def getJson(page):
    ip = baseCore.get_proxy()
    url = f'https://www.tj.gov.cn/igs/front/search.jhtml?code=78778b9ded5140d4984030cf8f469303&pageNumber={page}&pageSize=10&searchWord=REITs&siteId=34&sortByFocus=true&type=21515&type1=21519'
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    return req.json()['page']['content']


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


def getContent(num, title, pub_time, origin, organ, url, pub_hao, summary):
    id_list = []
    soup = getSoup(url)
    url_ = url.split('/')[-1]
    soup = paserUrl(soup, url.replace(url_, ''))
    contentWithTag = soup.find('div', class_='article_content')
    try:
        contentWithTag.find('div', class_='articlePlayer').decompose()
    except:
        pass
    try:
        scripts = contentWithTag.find_all('script')
        for script in scripts:
            script.decompose()
    except:
        pass
    try:
        styles = contentWithTag.find_all('style')
        for style in styles:
            style.decompose()
    except:
        pass
    try:
        a_list = contentWithTag.find('div', class_='qt-attachments').find_all('a')
        for a in a_list:
            href = a.get('href')

            category = os.path.splitext(href)[1]
            fj_title = a.text.lstrip().strip()
            if '<' in fj_title or '>' in fj_title:
                fj_title = fj_title.replace('<', '').replace('>', '')
            if category not in fj_title:
                fj_title = fj_title + category

            att_id, full_path = policy.attuributefile(fj_title, href, num, pub_time)
            if att_id:
                id_list.append(att_id)
                a['href'] = full_path
    except:
        pass
    # try:
    #     contentWithTag.find('div', class_='qt-attachments').decompose()
    # except:
    #     pass
    content = contentWithTag.text.lstrip().strip()
    contentWithTag_str = str(contentWithTag)
    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    dic_info = {
        'attachmentIds': id_list,
        'author': '',
        'content': content,
        'contentWithTag': contentWithTag_str,
        'deleteFlag': 0,
        'id': '',
        'title': title,
        'publishDate': pub_time,
        'origin': origin,
        'sourceAddress': url,
        'writtenDate': pub_time,
        'organ': organ,
        'topicClassification': '',
        'issuedNumber': pub_hao,
        'summary': summary,
        'createDate': time_now,
        'sid': '1729041400674045953',
    }
    try:
        baseCore.sendkafka(dic_info, topic)
        baseCore.r.sadd('REITs::' + webname, url)
        log.info(f'采集成功--{title}--{url}')
    except Exception as e:
        for att_id in id_list:
            baseCore.deliteATT(att_id)


def doJob():
    # if not os.path.exists('./相关政策/天津市人民政府/政策文件'):
    #     os.makedirs('./相关政策/天津市人民政府/政策文件')
    # data_list = []
    total = getTotal()
    num = 1
    for page in range(1, total + 1):
        data_json = getJson(page)
        for i in range(len(data_json)):
            title = data_json[i]['title']
            parsed_date = datetime.strptime(data_json[i]['trs_time'], '%Y-%m-%dT%H:%M:%S.%f%z')
            # 将解析后的datetime对象格式化为目标字符串格式
            pub_time = parsed_date.strftime('%Y-%m-%d %H:%M:%S')
            origin = data_json[i]['trs_site']
            organ = data_json[i]['department']
            href = data_json[i]['url']
            # 根据链接判重
            is_member = baseCore.r.sismember('REITs::' + webname, href)
            if is_member:
                continue
            pub_hao = data_json[i]['wh']
            summary = ''
            getContent(num, title, pub_time, origin, organ, href, pub_hao, summary)

            num += 1

    # df = pd.DataFrame(np.array(data_list))
    # df.columns = ['序号', '标题', '发布时间', '来源', '原文链接', '发文时间', '发文机构', '发文字号', '摘要', '正文', '附件名称', '附件连接']
    # df.to_excel('./天津市人民政府政策文件.xlsx', index=False)


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