from pot_libs.logger import log
from unify_api.utils.time_format import convert_es_str
from pot_libs.es_util.es_utils import EsUtil
from pot_libs.es_util.es_query import EsQuery
from pot_libs.common.components.query import PageRequest, Equal, Filter
from unify_api.modules.zhiwei_u.components.scope_operations_cps import \
    ScopeDetailsResponse
from pot_libs.mysql_util.mysql_util import MysqlUtil


async def scope_by_sql(mid_sql):
    sql = f"select * from point_1min_scope where {mid_sql} order by " \
          f"create_time desc limit 500"
    async with MysqlUtil() as conn:
        data = await conn.fetchall(sql)
    return data


async def scope_by_es(cid, point_id, page_num, page_size, start, end):
    query_body = {
        "from": (page_num - 1) * page_size,
        "size": page_size,
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "cid": cid
                        }
                    },
                    {
                        "terms": {
                            "point_id": point_id
                        }
                    }
                ]
            }
        },
        "sort": [
            {
                "datetime": {
                    "order": "desc"
                }
            }
        ]
    }
    if start and end:
        start_es = convert_es_str(start)
        end_es = convert_es_str(end)
        query_body["query"]["bool"]["must"].append(
            {
                "range": {
                    "datetime": {
                        "gte": start_es,
                        "lte": end_es
                    }
                }
            }
        )
    async with EsUtil() as es:
        es_re = await es.search_origin(body=query_body,
                                       index="poweriot_point_1min_scope")
    if es_re["hits"]:
        total = es_re["hits"]["total"]
        data = [get_source(hit) for hit in es_re['hits']['hits']]
    else:
        data, total = [], 0
    return data, total


async def detail_data_by_es(scope_id):
    query_body = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "_id": scope_id
                        }
                    }
                ]
            }
        }
    }
    try:
        async with EsUtil() as es:
            es_results = await es.search_origin(
                body=query_body,
                index="poweriot_point_1min_scope")
    except:
        log.error("es query error")
        return ScopeDetailsResponse().db_error()
    result = None
    if es_results["hits"]["total"]:
        result = es_results["hits"]["hits"][0]["_source"]
    return result


def get_source(hit):
    result = hit['_source']
    result['_id'] = hit['_id']
    return result


async def event_data_by_es(scope_id):
    query_body = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "doc_id.keyword": scope_id
                        }
                    }
                ]
            }
        }
    }
    try:
        async with EsUtil() as es:
            es_results = await es.search_origin(
                body=query_body,
                index="poweriot_point_1min_event")
    except:
        log.error("es query error")
        return ScopeDetailsResponse().db_error()
    result = None
    if es_results["hits"]["total"]:
        result = es_results["hits"]["hits"][0]["_source"]
    return result
