import os
import time
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, br',
    'Accept-Language': 'zh-CN,zh-TW;q=0.9,zh;q=0.8',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Host': 'www.nmg.gov.cn',
    'Pragma': 'no-cache',
    'Referer': 'https://www.nmg.gov.cn/nmg_search/',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    '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',
    'sec-ch-ua': '"Microsoft Edge";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
}

headers_ = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh-TW;q=0.9,zh;q=0.8',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    '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)
    if req.status_code != 200:
        return ''
    req.encoding = req.apparent_encoding
    soup = BeautifulSoup(req.text, 'lxml')
    return soup


def getPageSize():
    ip = baseCore.get_proxy()
    url = 'https://www.nmg.gov.cn/nmsearch/trssearch/searchAll.do?siteId=32&searchTag=zc&allKeywords=REITs&fullKeywords=&orKeywords=&notKeywords=&sort=&position=0&organization=&pageNum=1&pageSize=10&zcYear=&zcMonth=&docno=&cdesc=&publisher=&cityName=&isAlways=1&isSearchRmzfAndBgt=&isAccurate=1'
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    total = int(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'https://www.nmg.gov.cn/nmsearch/trssearch/searchAll.do?siteId=32&searchTag=zc&allKeywords=REITs&fullKeywords=&orKeywords=&notKeywords=&sort=&position=0&organization=&pageNum={page}&pageSize=10&zcYear=&zcMonth=&docno=&cdesc=&publisher=&cityName=&isAlways=1&isSearchRmzfAndBgt=&isAccurate=1'
    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']
    try:
        writtenDate = data['scrq']
    except:
        writtenDate = ''
    summary = BeautifulSoup(data['zc_doccontent'], 'html.parser').text.lstrip().strip()
    url = data['docpuburl']
    soup = getSoup(url)
    if soup == '':
        return ''
    url_ = url.split('/')[-1]
    soup = paserUrl(soup, url.replace(url_, ''))
    contentWithTag = soup.find('div', attrs={'id': 'pare'})
    if not contentWithTag:
        contentWithTag = soup.find('div', attrs={'id': 'zoom'})
        if not contentWithTag:
            contentWithTag = soup.find('div', attrs={'id': 'd_show'})
            if not contentWithTag:
                contentWithTag = soup.find('div', attrs={'class': 'zoomCon'})
                if not contentWithTag:
                    contentWithTag = soup.find('div', attrs={'id': 'pagecontent'})
    if writtenDate == '':
        try:
            tr_list = soup.find('table', class_='m-detailtb').find_all('tr')
            for tr in tr_list:
                if '成文日期' in tr.text:
                    writtenDate = tr.text.split('成文日期：')[1].split('发布日期：')[0].lstrip().strip()
        except:
            tr_list = soup.find('div', class_='main').find('table').find_all('tr')
            for tr in tr_list:
                if '成文时间' in tr.text:
                    writtenDate = tr.text.split('成文时间:')[1].lstrip().strip()
    try:
        contentWithTag.find('div', class_='clearfix').decompose()
    except:
        pass
    try:
        contentWithTag.find('div', class_='cc_shangxiaye').decompose()
    except:
        pass
    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
    try:
        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}===附件下载成功')
    except Exception as e:
        log.error(title, '=====', e)
    content = contentWithTag.text.lstrip().strip()
    data_ = [num, title, publishDate, origin, url, writtenDate, organ, pub_hao, summary, content, fjtitle_list,
             fjhref_list]
    return data_


def doJob():
    if not os.path.exists('./相关政策/内蒙古自治区人民政府/政策文件'):
        os.makedirs('./相关政策/内蒙古自治区人民政府/政策文件')
    data_list = []
    pageSize = getPageSize()
    num = 1
    for page in range(1, pageSize + 1):
        data_json = getJson(page)
        for data_ in data_json:
            if data_['chnldesc'] == '政策文件':
                data = getContent(num, data_)
                if data:
                    data_list.append(data)
                    num += 1
                    log.info(f'{data[1]}===采集成功')
    df = pd.DataFrame(np.array(data_list))
    df.columns = ['序号', '标题', '发布时间', '来源', '原文链接', '发文时间', '发文机构', '发文字号', '摘要', '正文', '附件名称', '附件连接']
    df.to_excel('./内蒙古自治区人民政府政策文件.xlsx', index=False)


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