import os
import time
from urllib.parse import urljoin

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 = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh-TW;q=0.9,zh;q=0.8',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Host': 'www.shanxi.gov.cn',
    'Pragma': 'no-cache',
    'Referer': 'http://www.shanxi.gov.cn/',
    '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',
}


def paserUrl(html, listurl):
    # 获取所有的<a>标签和<img>标签
    if isinstance(html, str):
        html = BeautifulSoup(html, 'html.parser')

    links = html.find_all(['a', 'img'])
    # 遍历标签，将相对地址转换为绝对地址
    for link in links:
        if 'href' in link.attrs:
            link['href'] = urljoin(listurl, link['href'])
        elif 'src' in link.attrs:
            link['src'] = urljoin(listurl, link['src'])
    return html


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


def getPageSize():
    ip = baseCore.get_proxy()
    url = 'http://www.shanxi.gov.cn/trs-search/trssearch/v2/searchAll.do?siteId=110&searchTag=zc&allKeywords=REITs&fullKeywords=&orKeywords=&notKeywords=&sort=&position=0&organization=&pageNum=1&pageSize=10&zcYear=&zcMonth=&docno=&cdesc=&publisher=&cityName=&isAlways=1&isSearchRmzfAndBgt='
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    total = req.json()['data']['total']
    if total % 10 == 0:
        pageSize = int(total / 10)
    else:
        pageSize = int(total / 10) + 1
    return pageSize


def getJson(page):
    ip = baseCore.get_proxy()
    url = f'http://www.shanxi.gov.cn/trs-search/trssearch/v2/searchAll.do?siteId=110&searchTag=zc&allKeywords=REITs&fullKeywords=&orKeywords=&notKeywords=&sort=&position=0&organization=&pageNum={page}&pageSize=10&zcYear=&zcMonth=&docno=&cdesc=&publisher=&cityName=&isAlways=1&isSearchRmzfAndBgt='
    req = requests.get(url, headers=headers, proxies=ip)
    req.encoding = req.apparent_encoding
    return req.json()['data']['data']


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


def getContent(num, data):
    id_list = []
    title = data['title']
    pub_hao = data['docno']
    origin = data['sitedesc']
    organ = data['publisher']
    publishDate = data['docpubtime']
    writtenDate = data['scrq']
    summary = BeautifulSoup(data['zc_doccontent'], 'html.parser').text.lstrip().strip()
    url = data['docpuburl']
    # 根据链接判重
    is_member = baseCore.r.sismember('REITs::' + webname, url)
    if is_member:
        return
    url_ = url.split('/')[-1]
    soup = getSoup(url)
    soup = paserUrl(soup, url.replace(url_, ''))
    contentWithTag = soup.find('dt', class_='fl_pc')
    if not contentWithTag:
        contentWithTag = soup.find('div', class_='sxgzk-detail-con')
    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()
    a_list = contentWithTag.find_all('a')
    for a in a_list:
        href = a.get('href')

        category = os.path.splitext(href)[1]
        fj_title = a.text.lstrip()
        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
    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': '1729041791539326977',
    }
    try:
        baseCore.sendkafka(dic_info, topic)
        baseCore.r.sadd('REITs::' + webname, url)
        log.info(f'采集成功--{title}--{url}')
    except:
        for att_id in id_list:
            baseCore.deliteATT(att_id)
    return


def doJob():

    num = 1
    # data_list = []
    pageSize = getPageSize()
    for page in range(1, pageSize + 1):
        data_json = getJson(page)
        for i in range(len(data_json)):
            if data_json[i]['chnldesc'] == '政策文件':
                getContent(num, data_json[i])
                num += 1



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