"""
历史的mongoDB中间表，现在已经废弃
"""
import datetime
import time
import traceback

from bson import ObjectId

from base.utils import mongo_helper

DB_NEWS_DETAIL = 'aic_news_detail'
DB_NEWS_DETAIL_COUNT = 'aic_news_detail_count'


def _clear(search_str, start_stamp, end_stamp):
    if start_stamp is None:
        start_stamp = 0
    start_datetime = datetime.datetime.fromtimestamp(start_stamp)
    start_datetime = start_datetime + datetime.timedelta(days=0, hours=-8, minutes=0,
                                                         weeks=0)
    start_objectId = ObjectId.from_datetime(start_datetime)
    if end_stamp is None:
        end_stamp = int(time.time())
    end_datetime = datetime.datetime.fromtimestamp(end_stamp)
    end_datetime = end_datetime + datetime.timedelta(days=0, hours=-8, minutes=0,
                                                     weeks=0)
    end_objectId = ObjectId.from_datetime(datetime.datetime.fromtimestamp(end_stamp))
    return start_objectId, end_objectId


def count_mongo(search_str, start_stamp, end_stamp):
    """
      查询mongo库里的数据总量，可按各种条件检索
         search_str设定条件:
            kind:例如输入 kind_item.news
            source:例如输入 source_item.齐鲁网
            type:例如输入 type_item.deep
            全部:输入None

         stamp设定时间:
            start_stamp 秒级时间戳,可以不给,默认所有
            end_stamp 秒级时间戳,可以不给,默认现在

    """
    start_objectId, end_objectId = _clear(search_str, start_stamp, end_stamp)
    count = -1
    try:
        if search_str is not None:
            item = list(mongo_helper.mongo_db[DB_NEWS_DETAIL_COUNT].aggregate([
                {"$match": {"_id": {"$lt": end_objectId}}},
                {"$match": {"_id": {"$gte": start_objectId}}},
                {"$group": {"_id": search_str, "total": {"$sum": "$" + search_str}}}
            ]))[0]
            total_histroy = item['total']
            # 再通过最后一条数据查询剩余数据
            item_last = mongo_helper.mongo_db[DB_NEWS_DETAIL_COUNT].find().sort('_id', -1).limit(1)[0]
            object_id_end = item_last['object_id_end']
            count = mongo_helper.query_count(table=DB_NEWS_DETAIL,
                                             filter={"$and": [{"_id": {"$gte": object_id_end, "$lte": end_objectId}},
                                                              {search_str.split("_item")[0]: search_str.split(".")[
                                                                  -1]}]})
            return total_histroy + count
        else:
            # 查询全部
            item = list(mongo_helper.mongo_db[DB_NEWS_DETAIL_COUNT].aggregate([
                {"$match": {"_id": {"$lt": end_objectId}}},
                {"$match": {"_id": {"$gte": start_objectId}}},
                {"$group": {"_id": search_str, "total": {"$sum": "$total"}}}
            ]))[0]
            total_histroy = item['total']
            # 再通过最后一条数据查询剩余数据
            item_last = mongo_helper.mongo_db[DB_NEWS_DETAIL_COUNT].find().sort('_id', -1).limit(1)[0]
            object_id_end = item_last['object_id_end']
            count = mongo_helper.query_count(table=DB_NEWS_DETAIL,
                                             filter={"_id": {"$gte": object_id_end, "$lte": end_objectId}})
            return total_histroy + count
    except:
        traceback.print_exc()


def list_mongo(search_str, start_stamp, end_stamp):
    start_objectId, end_objectId = _clear(search_str, start_stamp, end_stamp)
    items = mongo_helper.mongo_db[DB_NEWS_DETAIL_COUNT].find({"_id": {"$gte": start_objectId, "$lte": end_objectId}})
    dictData = {}
    for item in items:
        for key in item[search_str]:
            if key not in dictData:
                dictData[key] = item[search_str][key]
            else:
                dictData[key] += item[search_str][key]
    lstData = []
    for key in dictData.keys():
        lstData.append({"name": key, "num": dictData[key]})
    lstData.sort(key=lambda k: (k.get('num', 0)), reverse=True)
    return lstData


def get_blank(search_str, start_stamp, end_stamp, blank=86400):
    if blank < 60 * 60:
        raise Exception("请勿输入一小时以下的间隔")
    data_list = []
    for start_stamp_now in range(start_stamp, end_stamp, blank):
        data_list.append(
            {
                "start_stamp": start_stamp_now,
                "end_stamp": start_stamp_now + blank,
                "num": count_mongo(search_str, start_stamp_now, start_stamp_now + blank)
            }
        )
    return data_list


if __name__ == '__main__':
    startStamp = 1606503162
    endStamp = 1606903162
    # print(count_mongo(None, None, None))  # 查询全部
    # print(count_mongo("kind_item.bid", None, None))  # 查询kind
    # print(count_mongo("source_item.齐鲁网", None, None))  # 查询source
    # print(count_mongo("type_item.search", None, None))  # 查询type
    # print(count_mongo(None, startStamp, endStamp))  # 查询时间范围
    # print(count_mongo("kind_item.news", startStamp, endStamp))  # 联合条件和时间范围

    # print(list_mongo("kind_item", None, None))
    # print(list_mongo("kind_item", startStamp, endStamp))
    # print(list_mongo("source_item", None, None))
    # print(list_mongo("source_item", startStamp, endStamp))

    print(get_blank(None, startStamp, endStamp))
