import os
from urllib.parse import urljoin

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 = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh-TW;q=0.9,zh;q=0.8',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Host': 'www.shanxi.gov.cn',
    'Pragma': 'no-cache',
    'Referer': 'http://www.shanxi.gov.cn/',
    '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 paserUrl(html, listurl):
    # 获取所有的<a>标签和<img>标签
    if isinstance(html, str):
        html = BeautifulSoup(html, 'html.parser')

    links = html.find_all(['a', 'img'])
    # 遍历标签，将相对地址转换为绝对地址
    for link in links:
        if 'href' in link.attrs:
            link['href'] = urljoin(listurl, link['href'])
        elif 'src' in link.attrs:
            link['src'] = urljoin(listurl, link['src'])
    return html


def getSoup(url):
    ip = baseCore.get_proxy()
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    soup = BeautifulSoup(req.text, 'lxml')
    return soup


def getPageSize():
    ip = baseCore.get_proxy()
    url = 'http://www.shanxi.gov.cn/trs-search/trssearch/v2/searchAll.do?siteId=110&searchTag=zc&allKeywords=REITs&fullKeywords=&orKeywords=&notKeywords=&sort=&position=0&organization=&pageNum=1&pageSize=10&zcYear=&zcMonth=&docno=&cdesc=&publisher=&cityName=&isAlways=1&isSearchRmzfAndBgt='
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    total = req.json()['data']['total']
    if total % 10 == 0:
        pageSize = int(total / 10)
    else:
        pageSize = int(total / 10) + 1
    return pageSize


def getJson(page):
    ip = baseCore.get_proxy()
    url = f'http://www.shanxi.gov.cn/trs-search/trssearch/v2/searchAll.do?siteId=110&searchTag=zc&allKeywords=REITs&fullKeywords=&orKeywords=&notKeywords=&sort=&position=0&organization=&pageNum={page}&pageSize=10&zcYear=&zcMonth=&docno=&cdesc=&publisher=&cityName=&isAlways=1&isSearchRmzfAndBgt='
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    return req.json()['data']['data']


def getFjContent(url):
    ip = baseCore.get_proxy()
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    return req.content


def getContent(num, data):
    fjhref_list = ''
    fjtitle_list = ''
    title = data['title']
    pub_hao = data['docno']
    origin = data['sitedesc']
    organ = data['publisher']
    publishDate = data['docpubtime']
    writtenDate = data['scrq']
    summary = BeautifulSoup(data['zc_doccontent'], 'html.parser').text.lstrip().strip()
    url = data['docpuburl']
    url_ = url.split('/')[-1]
    soup = getSoup(url)
    soup = paserUrl(soup, url.replace(url_, ''))
    contentWithTag = soup.find('dt', class_='fl_pc')
    if not contentWithTag:
        contentWithTag = soup.find('div', class_='sxgzk-detail-con')
    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:
        href = a.get('href')
        fjhref_list += href + '\n'
        category = os.path.splitext(href)[1]
        fj_title = f'{num}-{publishDate}-{a.text.lstrip().strip()}'
        if '<' in fj_title or '>' in fj_title:
            fj_title = fj_title.replace('<', '').replace('>', '')
        if category not in fj_title:
            fj_title = fj_title + category
        fjtitle_list += fj_title + '\n'
        fjcontent = getFjContent(href)
        file = f'./相关政策/山西省人民政府/政策文件/{fj_title}'
        with open(file, 'wb') as f:
            f.write(fjcontent)
        log.info(f'{fj_title}===附件下载成功')
    content = contentWithTag.text.lstrip().strip()
    data_ = [num, title, writtenDate, origin, url, publishDate, organ, pub_hao, summary, content, fjtitle_list, fjhref_list]
    return data_


def doJob():
    if not os.path.exists('./相关政策/山西省人民政府/政策文件'):
        os.makedirs('./相关政策/山西省人民政府/政策文件')
    num = 1
    data_list = []
    pageSize = getPageSize()
    for page in range(1, pageSize + 1):
        data_json = getJson(page)
        for i in range(len(data_json)):
            if data_json[i]['chnldesc'] == '政策文件':
                data = getContent(num, data_json[i])
                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()
