from pot_libs.mysql_util.mysql_util import MysqlUtil
from pot_libs.es_util.es_utils import EsUtil
from unify_api.constants import POINT_1MIN_EVENT, SDU_ALARM_LIST


async def get_user_product_auth(user_id):
    sql = "SELECT * from user_product_auth where user_id=%s and product=4"
    async with MysqlUtil() as conn:
        user_info = await conn.fetchone(sql, args=(user_id,))
    return user_info


async def get_basic_info_by_mtid(mtid, cid):
    sql = "select s.room_name,s.storey_name,m.meter_no,m.sid,m.latitude," \
          "m.longitude from storey_room_map s left join point p " \
          "on p.pid=s.point_id LEFT JOIN monitor m on m.mtid=p.mtid " \
          "where m.mtid=%s and m.demolished=0 and s.cid =%s"
    async with MysqlUtil() as conn:
        info = await conn.fetchone(sql, args=(mtid, cid))
    return info


async def monitor_point_company(cids):
    sql = "SELECT c.cid,c.address,c.fullname,p.pid,m.mtid,s.storey_name," \
          "s.room_name,m.sid FROM `company` c INNER JOIN monitor m " \
          "on c.cid=m.cid INNER JOIN point p on m.mtid=p.mtid " \
          "INNER JOIN storey_room_map s on s.point_id=p.pid where c.cid in %s"
    async with MysqlUtil() as conn:
        datas = await conn.fetchall(sql, args=(cids, ))
    return datas


async def result_longgang_by_cid(cids, page_num, page_size, importance):
    alarm_list = SDU_ALARM_LIST

    query_body = {
        "from": (page_num - 1) * page_size,
        "size": page_size,
        "query": {
            "bool": {
                "must": [
                    {
                        "terms": {
                            "cid": cids
                        }
                    },
                    {
                        "terms": {
                            "type.keyword": alarm_list
                        }
                    },
                    {
                        "terms": {
                            "importance": importance
                        }
                    }
                ]
            }
        },
        "sort": [
            {
                "datetime": {
                    "order": "desc"
                }
            }
        ]
    }
    async with EsUtil() as es:
        es_re = await es.search_origin(body=query_body, index=POINT_1MIN_EVENT)
    return es_re