import json
import os
import time

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 = '广西壮族自治区人民政府'
headers = {
    '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',
    'Content-Type': 'application/json',
}


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 getFjContent(url):
    ip = baseCore.get_proxy()
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    return req.content


def getTotal():
    ip = baseCore.get_proxy()
    url = 'http://www.gxzf.gov.cn/irs/front/search'
    data_post = {"code": "181aedaa542", "dataTypeId": "241", "configCode": "",
                 "sign": "9cc99c9d-94aa-44b4-aa79-41227a5385d7", "searchWord": "REITs", "orderBy": "related",
                 "searchBy": "all", "appendixType": "", "granularity": "ALL", "isSearchForced": "0", "filters": [],
                 "pageNo": 1, "pageSize": 10, "isAdvancedSearch": None, "isDefaultAdvanced": None,
                 "advancedFilters": None, "advancedFilters ": None, "historySearchWords": []}
    data_post = json.dumps(data_post)
    req = requests.post(url, headers=headers, data=data_post, proxies=ip)
    req.encoding = req.apparent_encoding
    return int(req.json()['data']['pager']['pageCount'])


def getDataJson(page):
    ip = baseCore.get_proxy()
    url = 'http://www.gxzf.gov.cn/irs/front/search'
    data_post = {"code": "181aedaa542", "dataTypeId": "241", "configCode": "",
                 "sign": "9cc99c9d-94aa-44b4-aa79-41227a5385d7", "searchWord": "REITs", "orderBy": "related",
                 "searchBy": "all", "appendixType": "", "granularity": "ALL", "isSearchForced": "0", "filters": [],
                 "pageNo": page, "pageSize": 10, "isAdvancedSearch": None, "isDefaultAdvanced": None,
                 "advancedFilters": None, "advancedFilters ": None, "historySearchWords": []}
    data_post = json.dumps(data_post)
    req = requests.post(url, headers=headers, data=data_post, proxies=ip)
    req.encoding = req.apparent_encoding
    return req.json()['data']['middle']['listAndBox']


def getContent(url, publishDate, num):
    id_list = []
    soup = getSoup(url)
    policy.paserUrl(soup, url)
    contentWithTag = soup.find('div', attrs={'id': 'articleFile'})
    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
    content = contentWithTag.text
    a_list = soup.find('div', class_='downloadfile').find_all('a')
    for a in a_list:
        fj_href = a.get('href')

        fj_title = a.text.lstrip().strip()
        category = os.path.splitext(fj_href)[1]
        if category not in fj_title:
            fj_title = fj_title + category

        att_id, full_path = policy.attuributefile(fj_title, fj_href, num, publishDate)
        if att_id:
            id_list.append(att_id)
            a['href'] = full_path

    return content, contentWithTag, id_list


def getData(data_, num):
    title = data_['data']['title']
    publishDate = data_['data']['time']
    origin = '广西壮族自治区人民政府'
    href = data_['data']['url']
    # 根据链接判重
    is_member = baseCore.r.sismember('REITs::' + webname, href)
    if is_member:
        return
    writtenDate = data_['data']['table-10']
    organ = data_['data']['source']
    pub_hao = data_['data']['table-5']
    summary = data_['data']['table-7']
    content, contentWithTag, id_list = getContent(href, publishDate, num)
    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,
        'checkStatus': 1,
        'id': '',
        'title': title,
        'publishDate': publishDate,
        'origin': origin,
        'sourceAddress': href,
        'writtenDate': writtenDate,
        'organ': organ,
        'topicClassification': '',
        'issuedNumber': pub_hao,
        'summary': summary,
        'createDate': time_now,
        'sid': '1729045187128119298'
    }
    try:
        baseCore.sendkafka(dic_info, topic)
        baseCore.r.sadd('REITs::' + webname, href)
        log.info(f'采集成功--{title}--{href}')
    except Exception as e:
        for att_id in id_list:
            baseCore.deliteATT(att_id)
    return


def doJob():
    num = 1
    total = getTotal()
    for page in range(1, total + 1):
        data_json = getDataJson(page)
        title_list = []
        for data_ in data_json:
            title = data_['data']['title']
            if title not in title_list:
                title_list.append(title)
                getData(data_, num)

                num += 1
                time.sleep(2)



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