import json
import os
import time

import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By

import BaseCore

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

from reits import Policy
policy = Policy()


topic = 'policy'
webname = '上海市人民政府'
headers = {
    'Accept': '*/*',
    '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',
    'Content-Type': 'text/plain',
    'Host': 'ss.shanghai.gov.cn',
    'Origin': 'https://www.shanghai.gov.cn',
    'Pragma': 'no-cache',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-site',
    '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"',
}


def getDataJson():
    ip = baseCore.get_proxy()
    url = 'https://ss.shanghai.gov.cn/manda-app/api/app/search/v1/1drao49/search'
    data_post = {"cid": "lyHojYviSD3dOfgVFV4aGIu8Ytk7zEWy", "uid": "lyHojYviSD3dOfgVFV4aGIu8Ytk7zEWy", "query": "REITs",
                 "current": 1, "size": 20, "disable_correction": False,
                 "facets": {"fwjg": [{"type": "value", "name": "fwjg", "sort": {"count": "desc"}, "size": 100}]},
                 "input_type": "Input"}
    data_post = json.dumps(data_post)
    req = requests.post(url, headers=headers, data=data_post, proxies=ip)
    req.encoding = req.apparent_encoding
    data_json = req.json()['result']['items']
    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(data_, driver, num):
    id_list = []
    title = data_['title']['raw']
    publishDate = data_['date']['raw']
    origin = '上海市人民政府'
    href = data_['url']['raw']
    # 根据链接判重
    is_member = baseCore.r.sismember('REITs::' + webname, href)
    if is_member:
        return
    organ = data_['fwjg']['raw']
    pub_hao = data_['wh']['raw']
    summary = data_['content']['snippet']
    driver.get(href)
    time.sleep(1)
    contentWithTag = driver.find_element(By.CLASS_NAME, 'Article_content')
    content = driver.find_element(By.CLASS_NAME, 'Article_content').text.lstrip().strip()
    timeTag = driver.find_element(By.CLASS_NAME, 'PBtime').text
    try:
        try:
            try:
                writtenDate = timeTag.split('印发日期：')[1].split('发布日期')[0].lstrip().strip()
            except:
                writtenDate = timeTag.split('印发日期：')[1].split(f'{pub_hao}')[0].lstrip().strip()
        except:
            writtenDate = timeTag.split('印发日期：')[1].lstrip().strip()
    except:
        writtenDate = None
    try:
        a_list = driver.find_element(By.CLASS_NAME, 'gaoj-list').find_elements(By.TAG_NAME, 'a')
        for a in a_list:
            fj_href = a.get_attribute('href')

            category = os.path.splitext(fj_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, fj_href, num, publishDate)
            if att_id:
                id_list.append(att_id)
                a['href'] = full_path
            else:
                pass
    except:
        pass
    # data = [num, title, publishDate, origin, href, writtenDate, organ, pub_hao, summary, content, fjtitle_list,
    #         fjhref_list]
    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': '1729042751554506754',
    }
    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():

    # driver = baseCore.buildDriver()
    driver = policy.createDriver()

    num = 1
    data_json = getDataJson()
    for data_ in data_json:
        data = getData(data_, driver, num)
        # log.info(f'{data[1]}===采集成功')
        # data_list.append(data)
        num += 1

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