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 = {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    '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',
}


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 = 'https://api.so-gov.cn/query/s'
    data_post = {
        'siteCode': '5100000062',
        'tab': 'zcwj',
        'qt': 'REITs',
        'keyPlace': '0',
        'sort': 'dateDesc',
        'fileType': '',
        'timeOption': '0',
        'locationCode': '510000000000',
        'page': '1',
        'pageSize': '20',
        'ie': 'c0e059a8-7a00-4fa9-9d70-873a5284d8a0',
    }
    req = requests.post(url, headers=headers, data=data_post, proxies=ip)
    req.encoding = req.apparent_encoding
    data_json = req.json()['resultDocs']
    return data_json


def getContent(url, publishDate, num):
    url_ = url.split('/')[-1]
    url_ = url.replace(url_, '')
    fjhref_list = ''
    fjtitle_list = ''
    soup = getSoup(url)
    try:
        writtenDate = \
        soup.select('#szfcontentwrap2022 > div.zfwjwzcontent > div.topbox > ul > li')[3].text.split('成文日期：')[
            1].lstrip().strip()
    except:
        writtenDate = ''
    try:
        contentWithTag = soup.select('.contText')[0]
    except:
        contentWithTag = soup.select('#cmsArticleContent')[0]
    img_list = contentWithTag.find_all('img')
    num_ = 1
    for img in img_list:
        fj_href = url_ + img.get('src')
        fjhref_list += fj_href + '\n'
        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}===附件下载成功')
    content = contentWithTag.text
    fjtitle_list = fjtitle_list.lstrip().strip()
    fjhref_list = fjhref_list.lstrip().strip()
    return writtenDate, content, fjtitle_list, fjhref_list


def getData(data_, num):
    title = data_['data']['title']
    publishDate = data_['data']['docDate']
    origin = data_['data']['siteLabel']['value']
    href = data_['data']['url']
    organ = data_['data']['myValues']['DOCPUBNAME']
    pub_hao = data_['data']['myValues']['DOCNOVAL']
    summary = ''
    if '.pdf' in href or '.PDF' in href:
        content = ''
        writtenDate = ''
        fjtitle_list = title + '.pdf'
        fjhref_list = href
        fjcontent = getFjContent(href)
        file = f'./相关政策/四川省人民政府/政策文件/{title}.pdf'
        with open(file, 'wb') as f:
            f.write(fjcontent)
        log.info(f'{title}===附件下载成功')
    else:
        writtenDate, 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
    data_json = getDataJson()
    for data_ in data_json:
        data = getData(data_, num)
        data_list.append(data)
        log.info(f'{data[1]}===采集成功')
        num += 1
    df = pd.DataFrame(np.array(data_list))
    df.columns = ['序号', '标题', '发布时间', '来源', '原文链接', '发文时间', '发文机构', '发文字号', '摘要', '正文', '附件名称', '附件连接']
    df.to_excel('./相关政策/四川省人民政府/四川省人民政府政策文件.xlsx', index=False)


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