import os
import time

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 = {
    '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',
    'X-Requested-With': 'XMLHttpRequest',
}


def getTotal(url):
    ip = baseCore.get_proxy()
    data_post = 'params=%7B%22word%22%3A%22REITs%22%2C%22page%22%3A1%2C%22size%22%3A20%2C%22stype%22%3A%223%22%2C%22area%22%3A%22220000%22%2C%22atype%22%3A%221%22%2C%22dept%22%3A%22%22%2C%22ttype%22%3A%220%22%2C%22start%22%3A%22%22%2C%22end%22%3A%22%22%2C%22itype%22%3A%22%22%2C%22mattType%22%3A%220%22%2C%22serverType%22%3A%220%22%2C%22sort%22%3A0%2C%22aword%22%3A%22%22%2C%22hword%22%3A%22%22%2C%22nword%22%3A%22%22%2C%22dtword%22%3A%22%22%2C%22scope%22%3A%221%22%2C%22selecttp%22%3A%220%22%2C%22filetype%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22fileyear%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22stypeChild%22%3A%220%22%2C%22hs%22%3A%220%22%2C%22flag%22%3A%22%22%2C%22satisfiedId%22%3A%224FD2493B0F0D447E955C4BB94F42228C634%22%7D'
    req = requests.post(url, headers=headers, data=data_post, proxies=ip)
    req.encoding = req.apparent_encoding
    total = req.json()['data']['data']['totalPage']
    return int(total)


def getDataJson(url, page):
    ip = baseCore.get_proxy()
    data_post = f'params=%7B%22word%22%3A%22REITs%22%2C%22page%22%3A{page}%2C%22size%22%3A20%2C%22stype%22%3A%223%22%2C%22area%22%3A%22220000%22%2C%22atype%22%3A%221%22%2C%22dept%22%3A%22%22%2C%22ttype%22%3A%220%22%2C%22start%22%3A%22%22%2C%22end%22%3A%22%22%2C%22itype%22%3A%22%22%2C%22mattType%22%3A%220%22%2C%22serverType%22%3A%220%22%2C%22sort%22%3A0%2C%22aword%22%3A%22%22%2C%22hword%22%3A%22%22%2C%22nword%22%3A%22%22%2C%22dtword%22%3A%22%22%2C%22scope%22%3A%221%22%2C%22selecttp%22%3A%220%22%2C%22filetype%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22fileyear%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22stypeChild%22%3A%220%22%2C%22hs%22%3A%220%22%2C%22flag%22%3A%22%22%2C%22satisfiedId%22%3A%224FD2493B0F0D447E955C4BB94F42228C634%22%7D'
    req = requests.post(url, headers=headers, data=data_post, proxies=ip)
    req.encoding = req.apparent_encoding
    data_json = req.json()['data']['data']['list']
    return data_json


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


def getData(num, title, href, origin, publishDate, summary):
    writtenDate = ''
    pub_hao = ''
    organ = ''
    fjhref_list = ''
    fjtitle_list = ''
    ip = baseCore.get_proxy()
    req = requests.get(href, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    soup = BeautifulSoup(req.text, 'html.parser')
    try:
        scripts = soup.find_all('script')
        for script in scripts:
            script.decompose()
    except:
        pass
    try:
        styles = soup.find_all('style')
        for style in styles:
            style.decompose()
    except:
        pass
    contentWithTag = soup.find('div', class_='contents_div')
    if not contentWithTag:
        contentWithTag = soup.find('div', class_='zlyxwz')
        if not contentWithTag:
            contentWithTag = soup.find('div', attrs={'id': 'zlyxwz'})
            if not contentWithTag:
                contentWithTag = soup.find('div', attrs={'id': 'Zoom'})
                if not contentWithTag:
                    contentWithTag = soup.find('div',class_='sycon_bg')
                    if not contentWithTag:
                        contentWithTag = soup.find('div', attrs={'id': 'zoom'})
    try:
        try:
            organ = soup.find('div', class_='xqy').text
            organ = organ.split('来源：')[1].split('字体：')[0].lstrip().strip()
        except:
            info = soup.find('div', class_='zlylb_dy').find('table').text
            organ = info.split('发文机关：')[1].split('成文日期：')[0].lstrip().strip()
            writtenDate = info.split('成文日期：')[1].split('标')[0].lstrip().strip().replace('年', '-').replace('月',
                                                                                                          '-').replace(
                '日', '')
            pub_hao = info.split('发文字号：')[1].split('发布日期：')[0].lstrip().strip()
    except:
        try:
            organ = soup.find('div', class_='mqj_jtyst_xxnry_top_title_left_box').text.split('来源：')[1].lstrip().strip()
        except:
            table_list = soup.find_all('table')
            for table in table_list:
                if '发文机关' in table.text:
                    info = table.text
                    organ = info.split('发文机关：')[1].split('成文日期：')[0].lstrip().strip()
                    writtenDate = info.split('成文日期：')[1].split('标')[0].lstrip().strip().replace('年', '-').replace('月',
                                                                                                                  '-').replace(
                        '日', '')
                    pub_hao = info.split('发文字号：')[1].split('发布日期：')[0].lstrip().strip()
                    continue
    if pub_hao == '无':
        pub_hao = ''
    try:
        a_list = contentWithTag.find_all('a')
        for a in a_list:
            if '.html' in a.get('href') or '.shtml' in a.get('href') or '.htm' in a.get('href'):
                continue
            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}===附件下载成功')
    except:
        pass
    try:
        a_list = soup.find('div', class_='wjfj-1026').find_all('a')
        for a in a_list:
            if '.html' in a.get('href') or '.shtml' in a.get('href') or '.htm' in a.get('href'):
                continue
            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}===附件下载成功')
    except:
        pass

    content = contentWithTag.text.lstrip().strip()
    data_ = [num, title, writtenDate, origin, href, publishDate, organ, pub_hao, summary, content, fjtitle_list,
             fjhref_list]
    return data_


def doJob():
    if not os.path.exists('./相关政策/吉林省人民政府/政策文件'):
        os.makedirs('./相关政策/吉林省人民政府/政策文件')
    data_list = []
    num = 1
    url = 'https://intellsearch.jl.gov.cn/api/data/list'
    total = getTotal(url)
    for page in range(1, total + 1):
        data_json = getDataJson(url, page)
        for data_ in data_json:
            title = data_['title']
            title = BeautifulSoup(title, 'lxml').find('p').text.lstrip().strip()
            href = data_['url']
            origin = data_['websiteName']
            publishDate = data_['pubtime'].replace('/', '-')
            summary = data_['content']
            summary = BeautifulSoup(summary, 'lxml').find('p').text.lstrip().strip()
            data = getData(num, title, href, origin, publishDate, summary)
            data_list.append(data)
            num += 1
    df = pd.DataFrame(np.array(data_list))
    df.columns = ['序号', '标题', '发布时间', '来源', '原文链接', '发文时间', '发文机构', '发文字号', '摘要', '正文', '附件名称', '附件连接']
    df.to_excel('./吉林省人民政府政策文件.xlsx', index=False)


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