from pot_libs.logger import log
from pot_libs.mysql_util.mysql_util import MysqlUtil
from unify_api.constants import Importance
from unify_api.modules.common.procedures.common_cps import (
    proxy_safe_run_info,
    alarm_time_distribution,
)
from unify_api.utils.time_format import proxy_power_slots, day_slots


async def alarm_count_info(company_ids, start, end, date_type):
    if date_type == "day":
        date_fmt = "DATE_FORMAT(event_datetime,'%%H')"
        slots = day_slots('hours')
    else:
        # date_type == "month"
        date_fmt = "DATE_FORMAT(event_datetime,'%%m-%%d')"
        slots = proxy_power_slots(start, end, "MM-DD", True)
    alarm_sql = f"""
        select {date_fmt} date,importance,count(*) count from point_1min_event
        where cid in %s and event_datetime between %s and %s
        group by {date_fmt},importance
    """
    cid_sql = f"""
        select cid,count(*) count from point_1min_event
        where cid in %s and event_datetime between %s and %s
        group by cid
    """
    type_sql = f"""
        select event_type,count(*) count from point_1min_event
        where cid in %s and event_datetime between %s and %s
        group by event_type
    """
    async with MysqlUtil() as conn:
        args = (company_ids, start, end)
        alarm_result = await conn.fetchall(sql=alarm_sql, args=args)
        cid_result = await conn.fetchall(sql=cid_sql, args=args)
        type_result = await conn.fetchall(sql=type_sql, args=args)

    first_alarm = {"slots": [], "value": [0] * len(slots)}
    second_alarm = {"slots": [], "value": [0] * len(slots)}
    third_alarm = {"slots": [], "value": [0] * len(slots)}

    cid_alarm_cnt_map = {i["cid"]: i["count"] for i in cid_result}
    type_alarm_cnt_map = {i["event_type"]: i["count"] for i in type_result}
    for index, slot in enumerate(slots):
        show_slot = slot + ":00" if date_type == "day" else slot
        first_alarm["slots"].append(show_slot)
        second_alarm["slots"].append(show_slot)
        third_alarm["slots"].append(show_slot)
        for item in alarm_result:
            if item.get("date") == slot:
                if item["importance"] == Importance.First.value:
                    first_alarm["value"][index] += item["count"]
                elif item["importance"] == Importance.Second.value:
                    second_alarm["value"][index] += item["count"]
                elif item["importance"] == Importance.Third.value:
                    third_alarm["value"][index] += item["count"]

    log.info(f"first_alarm={first_alarm}")
    log.info(f"second_alarm={second_alarm}")
    log.info(f"third_alarm={third_alarm}")
    return {
        "first_alarm": first_alarm,
        "second_alarm": second_alarm,
        "third_alarm": third_alarm,
        "cid_alarm_cnt_map": cid_alarm_cnt_map,
        "type_alarm_cnt_map": type_alarm_cnt_map,
    }


async def alarm_summary(company_ids, start, end, date_type):
    """
    电参数,温度,漏电流时间分布
    :param company_ids:
    :param start:
    :param end:
    :param date_type:
    :return:
    """
    sql = f"""
        select cid,count(*) count from point_1min_event
        where cid in %s and event_mode = 'alarm' and  event_datetime >= %s
        and event_datetime <= %s
        group by cid
    """
    log.info("alarm_summary sql={}".format(sql))
    async with MysqlUtil() as conn:
        datas = await conn.fetchall(sql, args=(company_ids, start, end))
        print(f"datas = {datas}")
    total_alarm_cnt, alarm_company_cnt = sum(
        [i["count"] for i in datas]), len(datas)
    cid_alarmcnt_list = [i["count"] for i in datas]

    safe_run_map = await proxy_safe_run_info(company_ids, start_time_str=start,
                                             end_time_str=end)
    log.info(f"alarm_summary safe_run_map======{safe_run_map}")
    safe_run_days = sum(
        [safe_run_map[cid]["safe_run_days"] for cid in safe_run_map])

    # 时间分布： 白天， 黑夜, 凌晨
    time_distribution_map = await alarm_time_distribution(company_ids, start,
                                                          end)

    total_valid_company = 0
    for cid in safe_run_map:
        # 选择的这段时间，客户必须已经接入进来才算
        if safe_run_map[cid]["total_days"] != 0:
            total_valid_company += 1
    summary_map = {
        "total_alarm_cnt": total_alarm_cnt,
        "alarm_company_cnt": alarm_company_cnt,
        "avg_alarm_cnt": round(total_alarm_cnt / alarm_company_cnt,
                               1) if alarm_company_cnt else 0,
        "max_alarm_cnt": max(cid_alarmcnt_list) if cid_alarmcnt_list else 0,
        "safe_run_days": safe_run_days,
        "avg_safe_run_days": round(safe_run_days / total_valid_company,
                                   1) if total_valid_company else 0,
        "day_alarm_cnt": time_distribution_map["day_alarm_cnt"],
        "night_alarm_cnt": time_distribution_map["night_alarm_cnt"],
        "morning_alarm_cnt": time_distribution_map["morning_alarm_cnt"],
    }
    return summary_map
