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

from base import BaseCore

baseCore = BaseCore.BaseCore()
log = baseCore.getLogger()
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):
    fjhref_list = ''
    fjtitle_list = ''
    title = data_['title']['raw']
    publishDate = data_['date']['raw']
    origin = '上海市人民政府'
    href = data_['url']['raw']
    organ = data_['fwjg']['raw']
    pub_hao = data_['wh']['raw']
    summary = data_['content']['snippet']
    driver.get(href)
    time.sleep(1)
    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 = ''
    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')
            fjhref_list += fj_href + '\n'
            category = os.path.splitext(href)[1]
            fj_title = f'{num}-{publishDate}-{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
            fjtitle_list += fj_title + '\n'
    #         fjcontent = getFjContent(href)
    #         file = f'./相关政策/内蒙古自治区人民政府/政策文件/{fj_title}'
    #         with open(file, 'wb') as f:
    #             f.write(fjcontent)
    #         log.info(f'{fj_title}===附件下载成功')
    except:
        pass
    data = [num, title, publishDate, origin, href, writtenDate, organ, pub_hao, summary, content, fjtitle_list,
            fjhref_list]
    return data


def doJob():
    if not os.path.exists('./相关政策/上海市人民政府/政策文件'):
        os.makedirs('./相关政策/上海市人民政府/政策文件')
    driver = baseCore.buildDriver()
    data_list = []
    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
    df = pd.DataFrame(np.array(data_list))
    df.columns = ['序号', '标题', '发布时间', '来源', '原文链接', '发文时间', '发文机构', '发文字号', '摘要', '正文', '附件名称', '附件连接']
    df.to_excel('./相关政策/上海市人民政府/上海市人民政府政策文件.xlsx', index=False)


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