from pot_libs.mysql_util.mysql_util import MysqlUtil
from pot_libs.settings import SETTING
from unify_api.modules.common.service.td_engine_service import \
    get_td_engine_data
from unify_api.utils.taos_new import parse_td_columns


async def get_location_dao(lids):
    location_info = {}
    sql = "SELECT lid, item, mtid, ad_type FROM location WHERE lid IN %s"
    async with MysqlUtil() as conn:
        result = await conn.fetchall(sql, args=(lids,))
        if result:
            for res in result:
                id = res.get("lid")
                item = res.get("item")
                type = res.get("ad_type")
                mtid = res.get("mtid")
                location_info[id] = {"item": item, "type": type, "mtid": mtid}
    return location_info


async def get_location_15min_dao(lid, start, end):
    sql = f"SELECT lid,value_max,value_max_time,value_avg,value_min," \
          f"value_min_time  FROM `location_15min_aiao`WHERE lid = %s " \
          f"and create_time BETWEEN '{start}' and '{end}'"
    async with MysqlUtil() as conn:
        result = await conn.fetchall(sql, args=(lid,))
    return result


async def get_adio_current_data(mtid):
    '''
        获取安全监测实时数据
    '''
    url = f"{SETTING.stb_url}db_adio?tz=Asia/Shanghai"
    sql = f"select last_row(*) from mt{mtid}_adi"
    is_success, results = await get_td_engine_data(url, sql)
    if not is_success:
        return {}
    if not results['data']:
        return {}
    head = parse_td_columns(results)
    res = dict(zip(head, results['data'][0]))
    return res
