import time

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(page):
    ip = baseCore.get_proxy()
    url = 'http://www.shandong.gov.cn/jsearchfront/interfaces/cateSearch.do'
    data_post = {
        'websiteid': '370000000088000',
        'q': 'REITs',
        'p': f'{page}',
        'pg': '12',
        'cateid': '18002',
        'pos': '',
        'pq': '',
        'oq': '',
        'eq': '',
        'begin': '',
        'end': '',
        'tpl': '2204',
        'sortFields': "[{'name':'top','clause':1},{'name':'score','clause':1}]",
    }
    req = requests.post(url, headers=headers, data=data_post, proxies=ip)
    req.encoding = req.apparent_encoding
    return req.json()['result']


def getContent(url, publishDate, num):
    fjhref_list = ''
    fjtitle_list = ''
    soup = getSoup(url)
    contentWithTag = soup.find('div', class_='wip_art_con')
    a_list = contentWithTag.find_all('a')
    num_ = 1
    for a in a_list:
        fj_href = a.get('href')
        if 'http' not in fj_href:
            fj_href = 'http://www.shandong.gov.cn' + fj_href
        fjhref_list += fj_href + '\n'
        fj_title = a.text.lstrip().strip().replace(' ', '')
        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 getData(soup, num):
    origin = '山东省人民政府'
    organ = ''
    writtenDate = ''
    pub_hao = ''
    try:
        type = soup.find('span', class_='szf_lmmc').text
        title = soup.find('div', class_='szf_title').find('a').text.lstrip().strip()
        if '山东省政府文件库' in type:
            summary = soup.find('div', class_='szf_ms').text.lstrip().strip()
            organ = soup.find('table', class_='szf_xxgk').find_all('tr')[0].find_all('td')[1].text.lstrip().strip()
            writtenDate = soup.find('table', class_='szf_xxgk').find_all('tr')[0].find_all('td')[
                -1].text.lstrip().strip()
            pub_hao = soup.find('table', class_='szf_xxgk').find_all('tr')[1].find_all('td')[-1].text.lstrip().strip()
            href = soup.find('a', class_='szf_url').text.lstrip().strip()
            publishDate = soup.find('span', class_='szf_rq').text.lstrip().strip()
        else:
            summary = soup.find('div', class_='szf_ms').text.lstrip().strip()
            href = soup.find('a', class_='szf_url').text.lstrip().strip()
            publishDate = soup.find('span', class_='szf_rq').text.lstrip().strip()
    except:
        title = soup.find('div', class_='jcse-news-title').find('a').text.lstrip().strip()
        summary = soup.find('div', class_='jcse-news-abs-content').text.lstrip().strip()
        href = soup.find('div', class_='jcse-news-url').text.lstrip().strip()
        publishDate = soup.find('span', class_='jcse-news-date').text.lstrip().strip()
    content, fjtitle_list, fjhref_list = getContent(href, publishDate, num)
    data = [num, title, publishDate, origin, href, writtenDate, organ, pub_hao, summary, content, fjtitle_list,
            fjhref_list]
    return data


def doJob():
    if not os.path.exists('./相关政策/山东省人民政府/政策文件'):
        os.makedirs('./相关政策/山东省人民政府/政策文件')
    data_list = []
    num = 1
    for page in range(1, 3):
        data_json = getDataJson(page)
        for data_ in data_json:
            data_ = data_.replace('\\', '')
            soup = BeautifulSoup(data_, 'lxml')
            data = getData(soup, num)
            data_list.append(data)
            log.info(f'{data[1]}===采集成功')
            num += 1
            time.sleep(3)
    df = pd.DataFrame(np.array(data_list))
    df.columns = ['序号', '标题', '发布时间', '来源', '原文链接', '发文时间', '发文机构', '发文字号', '摘要', '正文', '附件名称', '附件连接']
    df.to_excel('./相关政策/山东省人民政府/山东省人民政府政策文件.xlsx', index=False)


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