import os
import time
from urllib.parse import urljoin

import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
import BaseCore

baseCore = BaseCore.BaseCore()
log = baseCore.getLogger()

from reits import Policy
policy = Policy()


topic = 'research_center_fourth'
webname = '内蒙古自治区人民政府'
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():

    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)
    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)
    req.encoding = req.apparent_encoding
    return req.json()['data']['data']


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


def getContent(num, data):
    id_list = []
    title = data['title']
    pub_hao = data['docno']
    origin = data['sitedesc']
    organ = data['publisher']
    publishDate = data['docpubtime']
    try:
        writtenDate = data['scrq']
    except:
        writtenDate = None
    summary = BeautifulSoup(data['zc_doccontent'], 'html.parser').text.lstrip().strip()
    url = data['docpuburl']
    # 根据链接判重
    is_member = baseCore.r.sismember('REITs::' + webname, url)
    if is_member:
        return
    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 not contentWithTag:
                    contentWithTag = soup.find('div', id="docContent")
    if not 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')

            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
            # 附件
            att_id, full_path = policy.attuributefile(fj_title, href, num, publishDate)
            if att_id:
                id_list.append(att_id)
                a['href'] = full_path

    except Exception as e:
        log.error(title, '=====', e)
    try:
        content = contentWithTag.text.lstrip().strip()
    except:
        log.info(url)
        return
    contentWithTag_str = str(contentWithTag)
    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    lang = baseCore.detect_language(content)
    dic_info = {
        'attachmentIds': id_list,
        'subjectId': '1729315113088765953',
        'lang': lang,
        'author': '',
        'content': content,
        'contentWithTag': contentWithTag_str,
        'deleteFlag': 0,
        'checkStatus': 1,
        'id': '1729315113088765953'+str(int(time.time())),
        'title': title,
        'publishDate': publishDate,
        'origin': origin,
        'sourceAddress': url,
        'writtenDate': writtenDate,
        'organ': organ,
        'topicClassification': '',
        'issuedNumber': pub_hao,
        'summary': summary,
        'createDate': time_now,
        'sid': '1729041959772860417'
    }
    try:
        baseCore.sendkafka(dic_info, topic)
        baseCore.r.sadd('REITs::' + webname, url)
        log.info(f'采集成功--{title}--{url}')
    except Exception as e:
        for att_id in id_list:
            baseCore.deliteATT(att_id)

    return


def doJob():


    pageSize = getPageSize()
    num = 1
    for page in range(1, pageSize + 1):
        data_json = getJson(page)
        for data_ in data_json:
            if data_['chnldesc'] == '政策文件':
                getContent(num, data_)
                num += 1

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