import os
import time

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 = 'policy'
webname = '吉林市人民政府'
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, url, origin, publishDate, summary):
    id_list = []
    writtenDate = None
    pub_hao = ''
    organ = ''

    # ip = baseCore.get_proxy()
    req = requests.get(url, 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')

            category = os.path.splitext(href)[1]
            fj_title = 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:
        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')

            category = os.path.splitext(href)[1]
            fj_title = 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
            else:
                pass
    except:
        pass
    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())
    dic_info = {
        'attachmentIds': id_list,
        'author': '',
        'content': content,
        'contentWithTag': contentWithTag_str,
        'deleteFlag': 0,
        'id': '',
        'title': title,
        'publishDate': publishDate,
        'origin': origin,
        'sourceAddress': url,
        'writtenDate': writtenDate,
        'organ': organ,
        'topicClassification': '',
        'issuedNumber': pub_hao,
        'summary': summary,
        'createDate': time_now,
        'sid': '1729042375596158978',
    }
    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():

    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']
            # 根据链接判重
            is_member = baseCore.r.sismember('REITs::' + webname, href)
            if is_member:
                continue
            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

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