import time

import requests
from bs4 import BeautifulSoup

import os
import pandas as pd
import numpy as np
import BaseCore

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

from reits import Policy
policy = Policy()


topic = 'research_center_fourth'
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():
    ip = baseCore.get_proxy()
    url = 'http://sousuo.jiangxi.gov.cn/jsearchfront/interfaces/cateSearch.do'
    data_post = {
        'websiteid': '360000000000000',
        'q': 'REITs',
        'p': '1',
        'pg': '20',
        'cateid': '1517',
        'pos': 'content',
        'pq': '',
        'oq': '',
        'eq': '',
        'begin': '',
        'end': '',
        'tpl': '49',
        'sortType': '',
    }
    req = requests.post(url, headers=headers, data=data_post, proxies=ip)
    req.encoding = req.apparent_encoding
    data_json = req.json()['result']
    return data_json


def getContent(url, num, publishDate):
    id_list = []
    soup = getSoup(url)
    policy.paserUrl(soup, url)
    contentWithTag = soup.find('div', attrs={'id': 'zoom'})
    img_list = contentWithTag.find_all('img')
    num_ = 1
    for img in img_list:
        fj_href = 'http://www.jiangxi.gov.cn' + img.get('src')

        fj_title = img.get('title')
        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)
            img['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 doJob():

    data_json = getDataJson()
    data_list = []
    num = 1
    for data_ in data_json:
        data_ = data_.replace('\\', '')
        soup = BeautifulSoup(data_, 'lxml')

        title = soup.select('body > div > div:nth-of-type(1) > span:nth-of-type(2) > a')[0].text.lstrip().strip()
        pub_hao = soup.find('table', class_='jcse-service-table').find_all('tr')[0].find_all('td')[
            -1].text.lstrip().strip()
        organ = soup.find('table', class_='jcse-service-table').find_all('tr')[1].find_all('td')[
            1].text.lstrip().strip()
        writtenDate = soup.find('table', class_='jcse-service-table').find_all('tr')[1].find_all('td')[
            -1].text.lstrip().strip()
        summary = soup.find('table', class_='jcse-service-table').find_all('tr')[2].text.lstrip().strip()
        href = soup.find('table', class_='jcse-service-table').find_all('tr')[3].find('a').get('href')
        # 根据链接判重
        is_member = baseCore.r.sismember('REITs::' + webname, href)
        if is_member:
            continue

        publishDate = writtenDate
        origin = '江西省人民政府'
        content, contentWithTag, id_list = getContent(href, num, publishDate)
        num += 1
        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': href,
            'writtenDate': writtenDate,
            'organ': organ,
            'topicClassification': '',
            'issuedNumber': pub_hao,
            'summary': summary,
            'createDate': time_now,
            'sid': '1729043445107838978'
        }
        # print(dic_info['id'])
        # print(publishDate)
        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)

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