import json
import time

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 = {
    'Content-Type': 'application/json',
    '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',
}


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 = 'http://www.cq.gov.cn/irs/front/list'
    data_post = {"customFilter": {"operator": "and", "properties": [], "filters": [{"operator": "or", "properties": [
        {"property": "f_202121500898", "operator": "eq", "value": "REITs"},
        {"property": "f_202142777829", "operator": "eq", "value": "REITs"}], "filters": []}, {"operator": "or",
                                                                                              "properties": [{
                                                                                                  "property": "f_202146838317",
                                                                                                  "operator": "gte",
                                                                                                  "value": "2023-11-17 11:21:40"},
                                                                                                  {
                                                                                                      "property": "f_202146235090",
                                                                                                      "operator": "gte",
                                                                                                      "value": "2023-11-17 11:21:40"}],
                                                                                              "filters": [
                                                                                                  {"operator": "and",
                                                                                                   "properties": [{
                                                                                                       "property": "f_202146838317",
                                                                                                       "operator": "eq",
                                                                                                       "value": None},
                                                                                                       {
                                                                                                           "property": "f_202146235090",
                                                                                                           "operator": "eq",
                                                                                                           "value": None}]}]}]},
                 "sorts": [{"sortField": "save_time", "sortOrder": "DESC"}], "tableName": "t_1775cd018c6",
                 "tenantId": "7", "pageSize": 10, "pageNo": 1}
    data_post = json.dumps(data_post)
    ip = baseCore.get_proxy()
    req = requests.post(url, data=data_post, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    total = int(req.json()['data']['pager']['pageCount'])
    return total


def getDataJson(page):
    url = 'http://www.cq.gov.cn/irs/front/list'
    data_post = {"customFilter": {"operator": "and", "properties": [], "filters": [{"operator": "or", "properties": [
        {"property": "f_202121500898", "operator": "eq", "value": "REITs"},
        {"property": "f_202142777829", "operator": "eq", "value": "REITs"}], "filters": []}, {"operator": "or",
                                                                                              "properties": [{
                                                                                                  "property": "f_202146838317",
                                                                                                  "operator": "gte",
                                                                                                  "value": "2023-11-17 11:21:40"},
                                                                                                  {
                                                                                                      "property": "f_202146235090",
                                                                                                      "operator": "gte",
                                                                                                      "value": "2023-11-17 11:21:40"}],
                                                                                              "filters": [
                                                                                                  {"operator": "and",
                                                                                                   "properties": [{
                                                                                                       "property": "f_202146838317",
                                                                                                       "operator": "eq",
                                                                                                       "value": None},
                                                                                                       {
                                                                                                           "property": "f_202146235090",
                                                                                                           "operator": "eq",
                                                                                                           "value": None}]}]}]},
                 "sorts": [{"sortField": "save_time", "sortOrder": "DESC"}], "tableName": "t_1775cd018c6",
                 "tenantId": "7", "pageSize": 10, "pageNo": page}
    data_post = json.dumps(data_post)
    ip = baseCore.get_proxy()
    req = requests.post(url, data=data_post, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    return req.json()['data']['list']


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')
    time.sleep(3)
    return soup


def getContent_(id):
    url = 'http://www.cq.gov.cn/govserver/tors/getPolicyDetail.html'
    data_post = {
        'policyId': f'{id}'
    }
    ip = baseCore.get_proxy()
    req = requests.post(url,headers=headers_,data=data_post,proxies=ip)
    req.encoding = req.apparent_encoding
    return req.json()['data']['DETAIL']['ZCYW']

def getContent(url):
    if 'policyId' in url:
        id = url.split('policyId=')[1]
        contentWithTag  = getContent_(id)
        contentWithTag = BeautifulSoup(contentWithTag,'lxml')
        policy.paserUrl(contentWithTag, url)
    else:
        soup = getSoup(url)
        policy.paserUrl(soup, url)
        contentWithTag = soup.find('div', class_='view')
        if not contentWithTag:
            contentWithTag = soup.find('div',class_='document')
            try:
                contentWithTag.find('div',class_='item').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
    content = contentWithTag.text.lstrip().strip()
    return content, contentWithTag


def getData(data_, num):
    title = data_['f_202121500898']
    publishDate = data_['save_time']
    origin = data_['f_2021325755960']
    href = data_['doc_pub_url']

    # 根据链接判重
    is_member = baseCore.r.sismember('REITs::' + webname, href)
    if is_member:
        return
    try:
        writtenDate = data_['f_202121607647']
    except:
        writtenDate = ''
    try:
        organ = data_['f_202121437464']
    except:
        organ = ''
    try:
        pub_hao = data_['f_202121837479']
    except:
        pub_hao = ''
    summary = data_['f_202142777829']
    summary = BeautifulSoup(summary, 'lxml').text.lstrip().strip()
    content, contentWithTag = getContent(href)
    contentWithTag_str = str(contentWithTag)
    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    lang = baseCore.detect_language(content)
    dic_info = {
        'attachmentIds': [],
        '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': '1729045755020103681'
    }

    try:
        baseCore.sendkafka(dic_info, topic)
        baseCore.r.sadd('REITs::' + webname, href)
        log.info(f'采集成功--{title}--{href}')
    except Exception as e:
        return
    return

def doJob():

    total = getTotal()
    num = 1
    for page in range(1, total + 1):
        data_json = getDataJson(page)
        for data_ in data_json:
            getData(data_, num)
            num += 1
            time.sleep(3)


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