# -*- coding:utf-8 -*-

import pymongo
from base_framework.public_tools.db_dbutils_init import get_my_mongo_connection
from base_framework.public_tools import log
obj_log = log.get_logger()


class MongoDbHelper:
    def __init__(self):
        # """
        # 初始化mongodb、并且链接指定数据库
        # :param collection:
        # :param collect_db_name:
        # """
        # init = InitConfig()
        # self.host = init.MONGO_HOST
        # self.port = init.MONGO_PORT
        # self.user = init.MONGO_USER
        # self.pwd = init.MONGO_PASSWORD
        #
        # try:
        #     self.connect_ = pymongo.MongoClient(host=self.host,
        #                                        port=int(self.port),
        #                                        username=self.user,
        #                                        password=self.pwd,
        #                                        authSource="hulk_teach_marketing"
        #                                        )
        # except Exception as e:
        #     obj_log.error("mongdb连接失败：{}".format(e))
        self.conn = get_my_mongo_connection().mongo_connect()

    def mongo_find(self, db_name, collection_name, query={}, select_value=None):
        db = self.conn[db_name]
        data = db.get_collection(collection_name).find(query, select_value)
        obj_log.info("mongo查询语句：db.getCollection({}).find({},{}).limit(501)".format(collection_name, query, select_value))
        return data

    def mongo_select_all(self, db_name, collection_name, query={}, select_value=None):
        """
        | 功能说明： | 查询mongo数据 |
        | 输入参数： | db_name | 数据库 |
        |           | collection_name | 表(集合) |
        |           | query={} | 查询条件 |
        |           | column={} | 展示列：默认会展示 "_id" |
        | 返回参数： | 查询结果(tuple) |
        | 作者信息： | xl     | 2020/11/26 21:11 |
        | 函数位置： | public_tool/mongohelper.py ||
        """
        data = self.mongo_find(db_name, collection_name, query, select_value)
        d = []
        for i in data:
            d.append(i)
        return tuple(d)

    def mongo_insert_many(self, db_name, collection_name, insert_value):
        """
        | 功能说明： | 插入mongo数据 |
        | 输入参数： | db_name | 数据库 |
        |           | collection_name | 表(集合) |
        |           | insert_value | 插入值 |
        | 返回参数： | TRUE/FALSE |
        | 作者信息： | xl     | 2020/11/26 21:11 |
        | 函数位置： | public_tool/mongohelper.py ||
        """
        try:
            db = self.conn[db_name]
            db.get_collection(collection_name).insert_many(insert_value)
            obj_log.info("mongo插入语句：db.getCollection({}).insertMany({})".format(collection_name, insert_value))
        except Exception as e:
            obj_log.error("插入数据失败：{}".format(e))
            return False
        return True

    def mongo_update_many(self, db_name, collection_name, query, update_value):
        """
        | 功能说明： | 修改mongo数据 |
        | 输入参数： | db_name | 数据库 |
        |           | collection_name | 表(集合) |
        |           | query | 修改条件 |
        |           | update_value | 修改值 |
        | 返回参数： | TRUE/FALSE |
        | 作者信息： | xl     | 2020/11/26 21:11 |
        | 函数位置： | public_tool/mongohelper.py ||
        """
        try:
            db = self.conn[db_name]
            result = db.get_collection(collection_name).update_many(query, update_value)
            obj_log.info("mongo修改语句：db.getCollection({}).updateMany({})".format(collection_name, update_value))
            obj_log.info("修改数量：{}".format(result.modified_count))
        except Exception as e:
            obj_log.error("修改失败：{}".format(e))
            return False
        return True

    def mongo_delete_many(self, db_name, collection_name, delete_value):
        """
        | 功能说明： | 删除mongo数据 |
        | 输入参数： | db_name | 数据库 |
        |           | collection_name | 表(集合) |
        |           | delete_value | 删除值 |
        | 返回参数： | TRUE/FALSE |
        | 作者信息： | xl     | 2020/11/26 21:11 |
        | 函数位置： | public_tool/mongohelper.py ||
        """
        try:
            db = self.conn[db_name]
            result = db.get_collection(collection_name).delete_many(delete_value)
            obj_log.info("mongo删除语句：db.getCollection({}).deleteMany({})".format(collection_name, delete_value))
            obj_log.info("删除数量：{}".format(result.deleted_count))
        except Exception as e:
            obj_log.error("删除失败：{}".format(e))
            return False
        return True

    def mongo_count(self, db_name, collection_name, filter, session=None, **kwargs):
        """
        | 功能说明： | 查询mongo数据 |
        | 输入参数： | db_name | 数据库 |
        |           | collection_name | 表(集合) |
        |           | filter | 查询条件 |
        | 返回参数： | 统计结果 |
        | 作者信息： | xl     | 2020/11/26 21:11 |
        | 函数位置： | public_tool/mongohelper.py ||
        """
        db = self.conn[db_name]
        db_collection = db[collection_name]
        db_count = db_collection.count_documents(filter, session, **kwargs)
        return db_count

    def mongo_aggregate(self, db_name, collection_name, pipline, session=None, **kwargs):
        """
        | 功能说明： | (aggregate)主要用于处理数据(诸如统计平均值，求和等)，并返回计算后的数据结果 |
        | 输入参数： | db_name | 数据库 |
        |           | collection_name | 表(集合) |
        |           | pipline | a list of aggregation pipeline stages |
        | 返回参数： | 返回聚合结果 |
        | 作者信息： | xl     | 2020/11/26 21:11 |
        | 函数位置： | public_tool/mongohelper.py ||
        """
        db = self.conn[db_name]
        db_collection = db[collection_name]
        data = db_collection.aggregate(pipline, session, **kwargs)
        s = []
        for i in data:
            s.append(i)
        return s


if __name__ == '__main__':
    s = MongoDbHelper()

    # 查询
    select_value = {"name": {"$regex": "^测试"}, "status":0}
    ss = s.mongo_count(db_name='hulk_teach_marketing', collection_name='activity', filter=select_value)
    print(ss)
    # print("{}\n".format(ss))
    # for i in ss:
    #     print(i)

    # 插入数据
    # dd = [{"code": "ACT2079479569078477", "created_time":1637897233410, "creator_id":586470, "creator_name":"xiaoliang02", "creator_type":1, "delete_flag":0, "deleted_time":0,"language":0,"name":"自动插入活动1-page-1001","region":"1","remark":"自动添加活动备注信息","status":1,"type":0,"user_type":0},
    #       {"code": "ACT2079479569078476", "created_time":1637897233410, "creator_id":586470, "creator_name":"xiaoliang02", "creator_type":1, "delete_flag":0, "deleted_time":0,"language":0,"name":"自动插入活动2-page-1001","region":"1","remark":"自动添加活动备注信息","status":2,"type":0,"user_type":0}]
    # s.mongo_insert_many(db_name='hulk_teach_marketing', collection_name='activity', insert_value=dd)

    # # 修改数据
    # q = {"code": "ACT210477219578032135"}
    # y = {"$set": {"name": "切图信息-右下角B区"}}
    # dd = s.mongo_update_many(db_name='hulk_teach_marketing', collection_name='activity', query=q, update_value=y)

    # # 删除数据
    # ddd = {"name": {"$regex": "^自动插入"}}
    # s.mongo_delete_many(db_name='hulk_teach_marketing', collection_name='activity', delete_value=ddd)
    # pipline = [{"$match": {"region": "5", "delete_flag": 0}}, {"$group": {"_id": "$region", "max_order": {"$max": "$order"}}}]
    # p = s.mongo_aggregate('hulk_teach_marketing', 'activity', pipline)
