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 jiang_su():
    num = 0
    count = 0
    pathType = 'policy/jiangsu/'
    start_time = time.time()
    pagestart = 1
    pageend = 45
    for page in range(1, 3):
        url = f"http://jsgzw.jiangsu.gov.cn/module/web/jpage/dataproxy.jsp?startrecord={pagestart}&endrecord={pageend}&perpage=15"
        pagestart = pageend + 1
        pageend = pageend + 45
        payload = "col=1&appid=1&webid=39&path=%2F&columnid=85683&sourceContentType=1&unitid=369983&webname=%E6%B1%9F%E8%8B%8F%E7%9C%81%E5%9B%BD%E8%B5%84%E5%A7%94&permissiontype=0"
        header = {
            'Connection': 'keep-alive',
            'Accept': 'application/xml, text/xml, */*; q=0.01',
            'X-Requested-With': 'XMLHttpRequest',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Origin': 'http://jsgzw.jiangsu.gov.cn',
            'Referer': 'http://jsgzw.jiangsu.gov.cn/col/col61490/index.html?uid=247686&pageNum=4',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cookie': 'JSESSIONID=ADB520E83E1FC10429D961634BAD303D; __jsluid_h=02c2c950abb71f547a79da79719246aa; _gscu_210493472=24936291qq5dvl18; _gscbrs_210493472=1; yunsuo_session_verify=60cc00825d4e2dd3dee278a301f60f1e; _gscs_210493472=24936291p77pyu18|pv:3'
        }
        try:
            resp_text = requests.request("POST", url, headers=header, data=payload).text
            li_list = re.findall('CDATA\[(.*?)\]\]></record>', str(resp_text))
            for li in li_list:
                a = BeautifulSoup(li, 'lxml').find('a')
                href = 'https://jsgzw.jiangsu.gov.cn/' + a['href']
                title = a.text
                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 = BeautifulSoup(href_text, 'html.parser')
                    soup = baseTool.paserUrl(href_text, href)
                    doc = pq(str(soup))
                    publishDate = doc('div[class="cf tip"]>span:contains(发布日期：)').text().replace('发布日期：', '')
                    writtenDate = doc('table[class="xlt_table"]>tbody>tr:nth-child(1)>td:nth-child(4)').text()
                    organ = doc('table[class="xlt_table"]>tbody>tr:nth-child(2)>td:nth-child(2)').text()
                    pub_hao = doc('table[class="xlt_table"]>tbody>tr:nth-child(2)>td:nth-child(4)').text()
                    contentWithTag = doc('div[id="zoom"]')
                    if len(contentWithTag) < 1:
                        contentWithTag = doc('div[class="main-txt"]')
                    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, '1687', 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)

                    contentWithTag = str(soup.prettify())
                    content = soup.text
                    if content == '' or content == None:
                        log.info(f'-----{href}----{title}----内容为空-----')
                        continue
                    if len(pub_hao) < 1:
                        pattern = r'(苏国.{1,}?号)|(国.{1,}?号)'
                        match_list = re.findall(pattern, content)
                        if len(match_list) > 0:
                            pub_hao = match_list[0][0]
                        else:
                            pub_hao = ''
                    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': "1687", 'relationName': "江苏省国资委", 'labelMark': "policy"}],
                        'origin': '',
                        'organ': organ,
                        'topicClassification': '',
                        'issuedNumber': pub_hao,
                        'publishDate': publishDate,
                        'writtenDate': writtenDate,
                        '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'共抓取{count}条数据,共耗时{end_time - start_time}')


if __name__ == "__main__":
    jiang_su()