import time
import os

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 = {
    '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):
    url_ = url.split('/')[-1]
    url_ = url.replace(url_, '')
    fjhref_list = ''
    fjtitle_list = ''
    soup = getSoup(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 = contentWithTag.find_all('a')
    for a in a_list:
        fj_href = a.get('href').replace('./', url_)
        fjhref_list += fj_href + '\n'
        fj_title = a.text.lstrip().strip()
        category = os.path.splitext(fj_href)[1]
        if category not in fj_title:
            fj_title = fj_title + category
        fj_title = f'{num}-{publishDate}-{fj_title}'
        fjtitle_list += fj_title + '\n'
        fjcontent = getFjContent(fj_href)
        file = f'./相关政策/福建省人民政府/政策文件/{fj_title}'
        with open(file, 'wb') as f:
            f.write(fjcontent)
        log.info(f'{fj_title}===附件下载成功')
    fjtitle_list = fjtitle_list.lstrip().strip()
    fjhref_list = fjhref_list.lstrip().strip()
    content = contentWithTag.text.lstrip().strip()
    return content, fjtitle_list, fjhref_list


def doJob():
    if not os.path.exists('./相关政策/福建省人民政府/政策文件'):
        os.makedirs('./相关政策/福建省人民政府/政策文件')
    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']
            try:
                writtenDate = data_['pubdate'].replace('.','-')
            except:
                writtenDate = ''
            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, fjtitle_list, fjhref_list = getContent(num, href, publishDate[:10])
            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
            time.sleep(1)
    df = pd.DataFrame(np.array(data_list))
    df.columns = ['序号', '标题', '发布时间', '来源', '原文链接', '发文时间', '发文机构', '发文字号', '摘要', '正文', '附件名称', '附件连接']
    df.to_excel('./相关政策/福建省人民政府/福建省人民政府政策文件.xlsx', index=False)


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