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 liao_ning():

    num = 0
    count = 0
    start_time = time.time()
    for page in range(1, 3):
        url = f'https://gzw.ln.gov.cn/gzw/xxgk/zc/zcfb/aa251549-{page}.shtml'
        try:
            resp_text = requests.get(url=url, headers=baseTool.headers, verify=False)
            resp_text.encoding = resp_text.apparent_encoding
            resp_text = resp_text.text
            doc_resp = BeautifulSoup(resp_text, 'html.parser')
            doc_items = doc_resp.select(
                '#aa25154996104f57858a48e0b1aecca9 > div:nth-of-type(2) > div.tablist-show > div.tab-list-page')[0]
            li_list = doc_items.select('li')
            for li in li_list:
                # print(li)
                href = str(li.select('a')[0].get('href'))
                if 'http' not in href:
                    if 'https' not in href:
                        href = 'https://gzw.ln.gov.cn/' + href
                is_href = baseTool.db_storage.find_one({'网址': href})
                if is_href:
                    num += 1
                    continue
                try:
                    href_text = requests.get(url=href, headers=baseTool.headers, verify=False)
                    href_text.encoding = href_text.apparent_encoding
                    href_text = href_text.text
                    doc_href = baseTool.paserUrl(href_text, href)
                    doc = pq(str(doc_href))
                    title = doc('p[class="govxlTText"]').text().strip()
                    origintag = doc('p[class="govxlTText2"]').text().strip()
                    origin = origintag.split('文章来源：')[1].split('发布时间：')[0].strip()
                    publishDate = origintag.split('发布时间：')[1].strip().replace('年', '-').replace('月', '-').replace('日',
                                                                                                                  '') + ' 00:00:00'
                    contentWithTag = doc('div[class="TRS_Editor"]')
                    if len(title) < 1:
                        title = doc('h1[class="title"]')
                        issuedNumber = doc('p[class="wjh"]')
                    if len(contentWithTag) < 1:
                        contentWithTag = doc('div[class="content"]')

                    soup = baseTool.paserUrl(str(contentWithTag), href)
                    fu_jian_soup = soup.find_all('a')
                    id_list = []
                    for file in fu_jian_soup:
                        try:
                            file_href = file['href']
                        except Exception as e:
                            continue
                        if '.pdf' in file_href or '.docx' in file_href or '.doc' in file_href or 'xlsx' in file_href or '.zip' in file_href \
                                or '.rar' in file_href or '.ppt' in file_href or '.PDF' in file_href or '.DOC' in file_href \
                                or '.XLS' in file_href or '.ZIP' in file_href or '.RAR' in file_href:
                            file_name = file.text.strip()
                            category = os.path.splitext(file_href)[1]
                            if category not in file_name:
                                file_name = file_name + category
                            retData = baseCore.uptoOBS(file_href, '1685', file_name)
                            if retData['state']:
                                pass
                            else:
                                continue
                            att_id, full_path = baseCore.tableUpdate(retData, '辽宁省国资委', file_name, num, publishDate)
                            id_list.append(att_id)
                            # todo:将返回的地址更新到soup
                            file['href'] = 'http:zzsn.luyuen.com/' + str(full_path)
                    # id_ = redefid(id_list)
                    contentWithTag = str(soup.prettify())
                    if len(contentWithTag) < 1:
                        continue
                    content = soup.text
                    if content == '' or content == None:
                        log.info(f'-----{href}----{title}----内容为空-----')
                        continue
                    pattern = r'(辽国资.{1,}?号)|(国资.{1,}?号)'
                    match_list = re.findall(pattern, content)
                    if len(match_list) > 0:
                        issuedNumber = match_list[0][0]
                        if len(issuedNumber) > 20:
                            issuedNumber = ''
                    else:
                        issuedNumber = ''
                    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                    # todo:传kafka字段
                    dic_news = {
                        'attachmentIds': id_list,
                        'author': '',
                        'content': str(content),
                        'contentWithTag': str(contentWithTag),
                        'createDate': time_now,
                        'deleteFlag': 0,
                        'id': '',
                        'labels': [{'relationId': "1685", 'relationName': "辽宁省国资委", 'labelMark': "policy"}],
                        'origin': origin,
                        'organ': "",
                        'topicClassification': "",
                        'issuedNumber': issuedNumber,
                        'publishDate': publishDate,
                        'writtenDate': None,
                        'sid': '1697458829758697473',
                        'sourceAddress': href,
                        'summary': '',
                        'title': title
                    }
                    # print(dic_news)
                    flag = baseTool.sendKafka(dic_news)
                    if flag:
                        baseTool.save_data(dic_news)
                        num += 1
                        count += 1
                except:
                    pass
        except:
            pass
    end_time = time.time()
    log.info(f'共抓取{num}条数据,共耗时{end_time - start_time}')


if __name__ == "__main__":
    liao_ning()