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 si_chuan():
    num = 0
    count = 0
    start_time = time.time()
    for page in range(1, 3):
        if page == 1:
            url = 'http://gzw.sc.gov.cn/scsgzw/CU2304010701/cu_xxgk_xzgfxwj.shtml'
        else:
            url = 'http://gzw.sc.gov.cn/scsgzw/CU2304010701/cu_xxgk_xzgfxwj_2.shtml'
        try:
            resp_text = requests.get(url=url, headers=baseTool.headers, verify=False).text
            doc_resp = pq(resp_text)
            doc_items_ = doc_resp('.biaobody')
            doc_items = doc_items_('li').items()
            for doc_item in doc_items:
                id_list = []
                # print(doc_item)
                pub_time = doc_item('.lie4').text().strip() + ' 00:00:00'
                pub_hao = doc_item('.lie3').text().strip()
                title = doc_item('a').attr('title')
                href = doc_item('a').attr('href')
                if 'http:' not in href:
                    href = 'http://gzw.sc.gov.cn' + doc_item('a').attr('href')
                # href = 'http://gzw.sc.gov.cn/scsgzw/CU2304010701/2018/1/22/9c5db691e09f4efdafce41763a0d7e03.shtml'
                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)
                    # title = str(doc_href('.xxgkzn_title').text()).replace('\n', '').replace('\r', '')
                    # content = str(doc_href('#scrollBox').children())
                    # 将doc_href转化为BeautifulSoup
                    doc_href = BeautifulSoup(str(doc_href), 'html.parser')
                    # 相对路径转化为绝对路径
                    doc_href = baseTool.paserUrl(doc_href, href)
                    contentWithTag = doc_href.find('div', id='scrollBox')
                    content = contentWithTag.text
                    if content == '' or content == None:
                        log.info(f'-----{href}----{title}----内容为空-----')
                        continue
                    fu_jian_list = doc_href.find_all('a')

                    for fu_jian in fu_jian_list:
                        try:
                            fu_jian_href = fu_jian['href']
                        except:
                            continue
                        file_name = fu_jian.text.strip()
                        if '.doc' in fu_jian_href or '.docx' in fu_jian_href or '.pdf' in fu_jian_href or '.xls' in fu_jian_href or '.xlsx' in fu_jian_href or '.zip' in fu_jian_href \
                                or '.rar' in fu_jian_href or '.ppt' in fu_jian_href or '.PDF' in fu_jian_href or '.DOC' in fu_jian_href \
                                or '.XLS' in fu_jian_href or '.ZIP' in fu_jian_href or '.RAR' in fu_jian_href:
                            category = os.path.splitext(fu_jian_href)[1]
                            if category not in file_name:
                                file_name = file_name + category
                            # 对附件上传至文件服务器
                            retData = baseCore.uptoOBS(fu_jian_href, '1678', 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:obs.ciglobal.cn/' + str(full_path)

                            # fu_jian_href_list.append(fu_jian_href)
                    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                    # todo:传kafka字段
                    dic_news = {
                        'attachmentIds': id_list,
                        'author': '',
                        'content': content,
                        'contentWithTag': str(contentWithTag),
                        'createDate': time_now,
                        'deleteFlag': 0,
                        'id': '',
                        'labels': [{'relationId': "1678", 'relationName': "四川省国资委", 'labelMark': "policy"}],
                        'origin': '',
                        'organ': '',
                        'topicClassification': '',
                        'issuedNumber': pub_hao,
                        '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)
                        count += 1
                        num = num + 1
                except Exception as e:
                    pass
        except:
            pass
    end_time = time.time()
    log.info(f'共抓取{count}条数据,共耗时{end_time - start_time}')

if __name__ == "__main__":
    si_chuan()