import time
import os

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',
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Referer': 'https://www.fujian.gov.cn/ssp/main/index.html?key=REITs&siteId=ff808081624641aa0162476c0e0e0055&isMain='
}


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 getDataJson(data_post):
    url = f'https://www.fujian.gov.cn/ssp/search/api/search?time={int(time.time())}'
    ip = baseCore.get_proxy()
    req = requests.post(url, headers=headers, data=data_post, proxies=ip)
    req.encoding = req.apparent_encoding
    data_json = req.json()['datas']
    return data_json


def getContent(num, url, publishDate):
    id_list = []
    url_ = url.split('/')[-1]
    url_ = url.replace(url_, '')

    soup = getSoup(url)
    policy.paserUrl(soup, url)
    contentWithTag = soup.find('div', class_='TRS_Editor')
    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
    a_list = soup.find('div', class_='xl_list1').find_all('a')
    for a in a_list:
        fj_href = a.get('href')
        if fj_href:
            pass
        else:
            continue
        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

    content = contentWithTag.text.lstrip().strip()

    return content, contentWithTag, id_list


def doJob():

    data_posts = [{
        'isCollapse': '', 'siteType': '1', 'typeQueryJsonToMap': '', 'pubOrgType': '1', 'jiGuanList': '',
        'siteCode': '', 'zhuTiIdList': '', 'isCrdept': '', 'mainSiteId': 'ff808081624641aa0162476c0e0e0055',
        'siteId': 'ff808081624641aa0162476c0e0e0055', 'depSiteId': 'ff808081624641aa0162476c0e0e0055', 'type': '0',
        'page': '1', 'rows': '10', 'historyId': '8a289fe18ba97b6a018bd6aee981642d', 'sourceType': 'SSP_DOCUMENT_ZC',
        'isChange': '0', 'fullKey': 'N', 'wbServiceType': '13', 'fileType': '', 'feaTypeName': '', 'fileNo': '',
        'pubOrg': '', 'zfgbPubOrg': '', 'themeType': '', 'searchTime': '', 'startDate': '', 'endDate': '',
        'sortFiled': 'RELEVANCE', 'searchFiled': '', 'dirUseLevel': '', 'issueYear': '', 'publishYear': '',
        'issueMonth': '', 'allKey': '', 'fullWord': '', 'oneKey': '', 'notKey': '', 'totalIssue': '', 'chnlName': '',
        'zfgbTitle': '', 'zfgbContent': '', 'bsDeptId': '', 'siteName': '', 'keyWord': 'REITs', 'isProvince': '',
    }, {
        'isCollapse': '', 'siteType': '1', 'typeQueryJsonToMap': '', 'pubOrgType': '', 'jiGuanList': '',
        'siteCode': '', 'zhuTiIdList': '', 'isCrdept': '', 'mainSiteId': 'ff808081624641aa0162476c0e0e0055',
        'siteId': 'ff808081624641aa0162476c0e0e0055', 'depSiteId': 'ff808081624641aa0162476c0e0e0055', 'type': '0',
        'page': '1', 'rows': '10', 'historyId': '8a28289e8ba97b6b018bd6cee1c26aa7', 'sourceType': 'SSP_JDHY',
        'isChange': '0', 'fullKey': 'N', 'wbServiceType': '13', 'fileType': '', 'feaTypeName': '', 'fileNo': '',
        'pubOrg': '', 'zfgbPubOrg': '', 'themeType': '', 'searchTime': '', 'startDate': '', 'endDate': '',
        'sortFiled': 'RELEVANCE', 'searchFiled': '', 'dirUseLevel': '', 'issueYear': '', 'publishYear': '',
        'issueMonth': '', 'allKey': '', 'fullWord': '', 'oneKey': '', 'notKey': '', 'totalIssue': '', 'chnlName': '',
        'zfgbTitle': '', 'zfgbContent': '', 'bsDeptId': '', 'siteName': '', 'keyWord': 'REITs', 'isProvince': '',
    }]
    data_list = []
    num = 1
    for data_post in data_posts:
        data_json = getDataJson(data_post)
        for data_ in data_json:
            title = data_['_doctitle']
            publishDate = data_['crtime'].replace('.','-')
            origin = data_['docsourcename']
            href = data_['docpuburl']

            # 根据链接判重
            is_member = baseCore.r.sismember('REITs::' + webname, href)
            if is_member:
                continue
            try:
                writtenDate = data_['pubdate'].replace('.','-')
            except:
                writtenDate = None
            try:
                organ = data_['puborg']
            except:
                organ = ''
            try:
                pub_hao = data_['fileno']
            except:
                pub_hao = ''
            summary = data_['doccontent']
            summary = BeautifulSoup(summary, 'lxml').text.lstrip().strip()
            content, contentWithTag, id_list = getContent(num, href, publishDate[:10])
            time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            contentWithTag_str = str(contentWithTag)
            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': '1729043067106865154'
            }
            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)
            num += 1
            time.sleep(1)


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