import time

import requests
from bs4 import BeautifulSoup
import os
import BaseCore

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

from reits import Policy
policy = Policy()

topic = 'policy'
webname = '山东省人民政府'
headers = {
    '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',
    'Content-Type': 'application/x-www-form-urlencoded',
}


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


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


def getDataJson(page):
    ip = baseCore.get_proxy()
    url = 'http://www.shandong.gov.cn/jsearchfront/interfaces/cateSearch.do'
    data_post = {
        'websiteid': '370000000088000',
        'q': 'REITs',
        'p': f'{page}',
        'pg': '12',
        'cateid': '18002',
        'pos': '',
        'pq': '',
        'oq': '',
        'eq': '',
        'begin': '',
        'end': '',
        'tpl': '2204',
        'sortFields': "[{'name':'top','clause':1},{'name':'score','clause':1}]",
    }
    req = requests.post(url, headers=headers, data=data_post, proxies=ip)
    req.encoding = req.apparent_encoding
    return req.json()['result']


def getContent(url, publishDate, num):
    id_list = []
    soup = getSoup(url)
    policy.paserUrl(soup, url)
    contentWithTag = soup.find('div', class_='wip_art_con')
    a_list = contentWithTag.find_all('a')
    num_ = 1
    for a in a_list:
        fj_href = a.get('href')
        if 'http' not in fj_href:
            fj_href = 'http://www.shandong.gov.cn' + fj_href

        fj_title = a.text.lstrip().strip().replace(' ', '')
        if fj_title == '':
            fj_title = str(num_)
            num_ += 1
        category = os.path.splitext(fj_href)[1]
        if category not in fj_title:
            fj_title = fj_title + category
        att_id, full_path = policy.attuributefile(fj_title, fj_href, num, publishDate)
        if att_id:
            id_list.append(att_id)
            a['href'] = full_path
    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
    content = contentWithTag.text.lstrip().strip()
    return content, contentWithTag, id_list


def getData(soup, num):
    origin = '山东省人民政府'
    organ = ''
    writtenDate = None
    pub_hao = ''
    try:
        type = soup.find('span', class_='szf_lmmc').text
        title = soup.find('div', class_='szf_title').find('a').text.lstrip().strip()
        if '山东省政府文件库' in type:
            summary = soup.find('div', class_='szf_ms').text.lstrip().strip()
            organ = soup.find('table', class_='szf_xxgk').find_all('tr')[0].find_all('td')[1].text.lstrip().strip()
            writtenDate = soup.find('table', class_='szf_xxgk').find_all('tr')[0].find_all('td')[
                -1].text.lstrip().strip()
            pub_hao = soup.find('table', class_='szf_xxgk').find_all('tr')[1].find_all('td')[-1].text.lstrip().strip()
            href = soup.find('a', class_='szf_url').text.lstrip().strip()
            # 根据链接判重
            is_member = baseCore.r.sismember('REITs::' + webname, href)
            if is_member:
                return

            publishDate = soup.find('span', class_='szf_rq').text.lstrip().strip()
        else:
            summary = soup.find('div', class_='szf_ms').text.lstrip().strip()
            href = soup.find('a', class_='szf_url').text.lstrip().strip()
            publishDate = soup.find('span', class_='szf_rq').text.lstrip().strip()
    except:
        title = soup.find('div', class_='jcse-news-title').find('a').text.lstrip().strip()
        summary = soup.find('div', class_='jcse-news-abs-content').text.lstrip().strip()
        href = soup.find('div', class_='jcse-news-url').text.lstrip().strip()
        publishDate = soup.find('span', class_='jcse-news-date').text.lstrip().strip()
    content, contentWithTag, id_list = getContent(href, publishDate, num)

    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': href,
        'writtenDate': writtenDate,
        'organ': organ,
        'topicClassification': '',
        'issuedNumber': pub_hao,
        'summary': summary,
        'createDate': time_now,
        'sid': '1729043593615560705',
    }
    try:
        baseCore.sendkafka(dic_info, topic)
        baseCore.r.sadd('REITs::' + webname, href)
        log.info(f'采集成功--{title}--{href}')
    except Exception as e:
        for att_id in id_list:
            baseCore.deliteATT(att_id)
    return


def doJob():
    num = 1
    for page in range(1, 3):
        data_json = getDataJson(page)
        for data_ in data_json:
            data_ = data_.replace('\\', '')
            soup = BeautifulSoup(data_, 'lxml')
            getData(soup, num)
            num += 1


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