from unify_api.modules.tsp_water.dao.alarm_record_dao import \
    tsp_event_search_dao
from unify_api.modules.tsp_water.components.alarm_record_cps import \
    AlarmRecordResp


async def alarm_record_service(cid, pm_type, start, end, importance,
                               page_size, page_num):
    li = [f"cid={cid}"]
    if pm_type:
        li.append(f"pm_type='{pm_type}'")
    if start and end:
        li.append(f"event_datetime > '{start}' and event_datetime < '{end}'")
    if importance:
        if len(importance) == 1:
            li.append(f"importance={importance[0]}")
        else:
            li.append(f"importance in {tuple(importance)}")
    current_page = (page_num - 1) * page_size

    cond_sql = " and ".join(li)
    sql = f"SELECT event_datetime,tsp_id,name,importance,message,pm_type" \
          f" FROM tsp_1min_event where {cond_sql} " \
          f"ORDER BY event_datetime desc limit {current_page}, {page_size}"
    t_sql = f"SELECT count(id) total FROM `tsp_1min_event` where " \
            f"{cond_sql}"

    datas = await tsp_event_search_dao(sql)
    for data in datas:
        data["event_datetime"] = \
            data["event_datetime"].strftime("%Y-%m-%d %H:%M:%S")
    total = await tsp_event_search_dao(t_sql)
    return AlarmRecordResp(total=total[0]["total"], rows=datas)
