import requests
from bs4 import BeautifulSoup
from base import BaseCore
import os
import pandas as pd
import numpy as np

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',
}


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():
    ip = baseCore.get_proxy()
    url = 'http://sousuo.jiangxi.gov.cn/jsearchfront/interfaces/cateSearch.do'
    data_post = {
        'websiteid': '360000000000000',
        'q': 'REITs',
        'p': '1',
        'pg': '20',
        'cateid': '1517',
        'pos': 'content',
        'pq': '',
        'oq': '',
        'eq': '',
        'begin': '',
        'end': '',
        'tpl': '49',
        'sortType': '',
    }
    req = requests.post(url, headers=headers, data=data_post, proxies=ip)
    req.encoding = req.apparent_encoding
    data_json = req.json()['result']
    return data_json


def getContent(url, num, publishDate):
    fjhref_list = ''
    fjtitle_list = ''
    soup = getSoup(url)
    contentWithTag = soup.find('div', attrs={'id': 'zoom'})
    img_list = contentWithTag.find_all('img')
    num_ = 1
    for img in img_list:
        fj_href = 'http://www.jiangxi.gov.cn' + img.get('src')
        fjhref_list += fj_href + '\n'
        fj_title = img.get('title')
        if fj_title == '':
            fj_title = str(num_)
            num_ += 1
        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}===附件下载成功')
    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.lstrip().strip()
    return content, fjtitle_list, fjhref_list


def doJob():
    if not os.path.exists('./相关政策/江西省人民政府/政策文件'):
        os.makedirs('./相关政策/江西省人民政府/政策文件')
    data_json = getDataJson()
    data_list = []
    num = 1
    for data_ in data_json:
        data_ = data_.replace('\\', '')
        soup = BeautifulSoup(data_, 'lxml')
        title = soup.select('body > div > div:nth-of-type(1) > span:nth-of-type(2) > a')[0].text.lstrip().strip()
        pub_hao = soup.find('table', class_='jcse-service-table').find_all('tr')[0].find_all('td')[
            -1].text.lstrip().strip()
        organ = soup.find('table', class_='jcse-service-table').find_all('tr')[1].find_all('td')[
            1].text.lstrip().strip()
        writtenDate = soup.find('table', class_='jcse-service-table').find_all('tr')[1].find_all('td')[
            -1].text.lstrip().strip()
        summary = soup.find('table', class_='jcse-service-table').find_all('tr')[2].text.lstrip().strip()
        href = soup.find('table', class_='jcse-service-table').find_all('tr')[3].find('a').get('href')
        publishDate = writtenDate
        origin = '江西省人民政府'
        content, fjtitle_list, fjhref_list = getContent(href, num, publishDate)
        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
    df = pd.DataFrame(np.array(data_list))
    df.columns = ['序号', '标题', '发布时间', '来源', '原文链接', '发文时间', '发文机构', '发文字号', '摘要', '正文', '附件名称', '附件连接']
    df.to_excel('./相关政策/江西省人民政府/江西省人民政府政策文件.xlsx', index=False)


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