import datetime
import os
import re
import time
import requests
from bs4 import BeautifulSoup
from pyquery import PyQuery as pq

from ClassTool import ClassTool
baseTool = ClassTool()

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

# 广东
def guang_dong():
    start = time.time()
    num = 0
    count = 0
    url = 'http://gzw.gd.gov.cn/zcfg/index.html'
    try:
        resp_href = requests.get(url=url, headers=baseTool.headers, verify=False)
        resp_href.encoding = resp_href.apparent_encoding
        doc_resp = BeautifulSoup(resp_href.text, 'html.parser')
        page_items = str(doc_resp.find('div', attrs={'class': 'page'}).text)
        total = page_items.split('共 ')[1].split(' 条')[0].strip().lstrip()
        total = int(total)
        if total % 23 != 0:
            pagen = total / 23 + 1
        else:
            pagen = total / 23
        for page in range(1, int(pagen + 1)):
            if page == 1:
                url = 'http://gzw.gd.gov.cn/zcfg/index.html'
            else:
                url = f'http://gzw.gd.gov.cn/zcfg/index_{page}.html'
            resp_text = requests.get(url=url, headers=baseTool.headers, verify=False).text
            doc_resp = pq(resp_text)
            doc_items = doc_resp('.list li').items()
            for doc_item in doc_items:
                id_list = []
                title = doc_item('a').text().replace('\n', '')
                href = doc_item('a').attr('href')
                is_href = baseTool.db_storage.find_one({'网址': href})
                if is_href:
                    num += 1
                    continue
                try:
                    # print(href)
                    href_text = requests.get(url=href, headers=baseTool.headers, verify=False).text
                    doc_href = pq(href_text)
                    pub_result = doc_href('.title_info_sub').text()
                    pub_time = pub_result.split('文章来源：')[0].replace('发布时间：', '').strip() + ' 00:00:00'
                    pub_source = pub_result.split('文章来源：')[1].strip()
                    i_soup = BeautifulSoup(href_text, 'html.parser')
                    i_soup = baseTool.paserUrl(i_soup, href)
                    content = i_soup.find('div', attrs={'class', 'box_info'})
                    contentwithTag = str(content)
                    if content == '' or content == None:
                        log.info(f'{href}-----{title}----内容为空----')
                        continue
                    fu_jian_list = content.find_all('a')
                    for fu_jian in fu_jian_list:
                        try:
                            file_name = fu_jian.text
                            fj_href = fu_jian['href']
                        except:
                            continue

                        if '.doc' in fj_href or '.docx' in fj_href or '.pdf' in fj_href or '.xls' in fj_href or '.zip' in fj_href \
                                or '.rar' in fj_href or '.ppt' in fj_href or '.PDF' in fj_href or '.DOC' in fj_href \
                                or '.xlsx' in fj_href or '.ZIP' in fj_href or '.RAR' in fj_href:
                            category = os.path.splitext(fj_href)[1]
                            if category not in file_name:
                                file_name = file_name + category
                            # 附件上传至文件服务器
                            retData = baseCore.uptoOBS(fj_href, '1676', file_name)
                            if retData['state']:
                                pass
                            else:
                                continue
                            att_id, full_path = baseCore.tableUpdate(retData, '广东省国资委', file_name, num, pub_time)
                            id_list.append(att_id)
                            # 将文件服务器的链接替换
                            fu_jian['href'] = 'http:zzsn.luyuen.com/' + str(full_path)

                    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                    # todo:传kafka字段
                    dic_news = {
                        'attachmentIds': id_list,
                        'author': '',
                        'content': content.text,
                        'contentWithTag': str(contentwithTag),
                        'createDate': time_now,
                        'deleteFlag': 0,
                        'id': '',
                        'labels': [{'relationId': "1676", 'relationName': "广东省国资委", 'labelMark': "policy"}],
                        'origin': pub_source,
                        'organ': '',
                        'topicClassification': '',
                        'issuedNumber': '',
                        'publishDate': pub_time,
                        'writtenDate': None,
                        'sid': '1697458829758697473',
                        'sourceAddress': href,
                        'summary': '',
                        'title': title
                    }
                    # print(dic_news)
                    flag = baseTool.sendKafka(dic_news)
                    if flag:
                        baseTool.save_data(dic_news)
                        log.info(title)
                        num = num + 1
                        count += 1
                except:
                    pass
    except:
        pass
    end = time.time()
    log.info(f'共抓取{count}条数据，共耗时{end - start}')

if __name__ == "__main__":
    guang_dong()