import json
import time

import requests
from bs4 import BeautifulSoup
from base import BaseCore
import os
import pandas as pd
import numpy as np

baseCore = BaseCore.BaseCore()
log = baseCore.getLogger()
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')
    else:
        soup = getSoup(url)
        contentWithTag = soup.find('div', class_='view')
        if not contentWithTag:
            contentWithTag = soup.find('div',class_='document')
            contentWithTag.find('div',class_='item').decompose()
    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


def getData(data_, num):
    title = data_['f_202121500898']
    publishDate = data_['save_time']
    origin = data_['f_2021325755960']
    href = data_['doc_pub_url']
    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 = getContent(href)
    fjtitle_list = ''
    fjhref_list = ''
    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('./相关政策/重庆市人民政府/政策文件')
    total = getTotal()
    num = 1
    data_list = []
    for page in range(1, total + 1):
        data_json = getDataJson(page)
        for data_ in data_json:
            data = getData(data_, num)
            num += 1
            time.sleep(3)
            data_list.append(data)
            log.info(f'{data[1]}===采集成功')
    df = pd.DataFrame(np.array(data_list))
    df.columns = ['序号', '标题', '发布时间', '来源', '原文链接', '发文时间', '发文机构', '发文字号', '摘要', '正文', '附件名称', '附件连接']
    df.to_excel('./相关政策/重庆市人民政府/重庆市人民政府政策文件.xlsx', index=False)


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