from pot_libs.mysql_util.mysql_util import MysqlUtil
from pot_libs.sanic_api import summary
from unify_api.modules.alarm_manager.components.alarm_static_cps import \
    SduAlarmReq, SduAlarmResp, ContentName, RiskCount, SasReq, SassReq, \
    SassResp, AppReq, AppResp, SisReq, SisResp, SiasReq, SiasResp, SebReq, \
    SebResp, SiarResp, ZsResp, ZasReq, ZasResp
from unify_api.modules.alarm_manager.procedures.alarm_static_pds import \
    alarm_content_info, risk_distribution
from unify_api.modules.alarm_manager.service.alarm_static_service import \
    sdu_alarm_statistics_service, sdu_alarm_statistics_sort_service, \
    sdu_app_statistics_sort_service, sdu_electric_behave_service, \
    sdu_index_alarm_ranking_service, zdu_level_distribution_service, \
    zdu_content_distribution_service, zdu_summary_service, \
    zdu_alarm_sort_service_2, sdu_alarm_statistics_sort_service_new15, \
    sdu_app_statistics_sort_service_new15, \
    sdu_index_alarm_ranking_service_new15
from unify_api.modules.home_page.components.security_info_cps import \
    SecurityCountResp, AlarmContentDistributionResp
from unify_api.modules.home_page.procedures.count_info_pds import \
    electric_use_info_sdu, electric_use_info_sdu_new15
from unify_api.utils.time_format import last30_day_range


@summary("报警统计")
async def post_alarm_statistics(req, body: SduAlarmReq) -> SduAlarmResp:
    """目前用于 识电u->报警统计"""
    product = body.product
    cid = body.cid
    start = body.start
    end = body.end
    # 获取point信息
    sql_point = "SELECT pid, name FROM point WHERE cid=%s"
    async with MysqlUtil() as conn:
        points = await conn.fetchall(sql_point, args=(cid,))
    if not points:
        return SduAlarmResp()
    point_id_list = [i["pid"] for i in points]
    # 1.调用函数获取报警统计信息
    alarm_info_map = await alarm_content_info(cid, start, end, points)
    if not alarm_info_map:
        return SduAlarmResp()
    high_power_app, ele_overload, illegal_ele_app, power_quality, \
    ele_car_battery, point_dic, total_alarm_cnt = (
        alarm_info_map["high_power_app"],
        alarm_info_map["ele_overload"],
        alarm_info_map["illegal_ele_app"],
        alarm_info_map["power_quality"],
        alarm_info_map["ele_car_battery"],
        alarm_info_map["point_dic"],
        alarm_info_map["total_alarm_cnt"]
    )
    # point_dic排序
    point_list = []
    for key, val in point_dic.items():
        point_list.append({"name": key, "value": val})
    point_list.sort(key=lambda x: x["value"], reverse=True)
    # 报警类型总数,用于求比例
    cn = ContentName(ele_overload=sum(ele_overload["value"]),
                     high_power_app=sum(high_power_app["value"]),
                     illegal_ele_app=sum(illegal_ele_app["value"]),
                     power_quality=sum(power_quality["value"]),
                     ele_car_battery=sum(ele_car_battery["value"])
                     )
    # 2.计算风险分布
    # 其中当前时段为发生过I级报警为风险用户，其余为安全用户
    security_user, risk_user = await risk_distribution(start, end,
                                                       point_id_list)
    rc = RiskCount(security_user=security_user, risk_user=risk_user)
    return SduAlarmResp(
        total_alarm_cnt=total_alarm_cnt,
        high_power_app=high_power_app,
        ele_overload=ele_overload,
        illegal_ele_app=illegal_ele_app,
        power_quality=power_quality,
        ele_car_battery=ele_car_battery,
        alarm_ranking=point_list,
        content_distribution=cn,
        risk_distribution=rc
    )


@summary("报警统计-识电u")
async def post_sdu_alarm_statistics(req, body: SduAlarmReq) -> SduAlarmResp:
    """目前用于 识电u->报警统计"""
    product = body.product
    cid = body.cid
    start = body.start
    end = body.end
    return await sdu_alarm_statistics_service([cid], start, end, product)


@summary("报警统计-wx-识电u")
async def post_sdu_alarm_statistics_wx(req, body: SasReq) -> SduAlarmResp:
    """目前用于 识电u->报警统计"""
    product = body.product
    cids = body.cids
    start = body.start
    end = body.end
    return await sdu_alarm_statistics_service(cids, start, end, product)


@summary("报警统计-报警记录-排名-识电u")
async def post_sdu_alarm_statistics_sort(req,
                                         body: SassReq) -> SassResp:
    """目前用于 识电u->报警统计"""
    product = body.product
    cid = body.cid
    start = body.start
    end = body.end
    page_size = body.page_size
    page_num = body.page_num
    sort = body.sort
    # return await sdu_alarm_statistics_sort_service(cid, start, end, page_size,
    #                                                page_num, sort)
    return await sdu_alarm_statistics_sort_service_new15(cid, start, end,
                                                         page_size, page_num,
                                                         sort)


@summary("报警统计-电器识别-排名-识电u")
async def post_sdu_app_statistics_sort(req, body: AppReq) -> AppResp:
    """目前用于 识电u->报警统计"""
    product = body.product
    cid = body.cid
    start = body.start
    end = body.end
    return await sdu_app_statistics_sort_service_new15(cid, start, end)


@summary("首页-运行趋势-识电u")
async def post_sdu_index_statistics(req, body: SisReq) -> SisResp:
    product = body.product
    cid = body.cid
    start = body.start
    end = body.end
    sr = await sdu_alarm_statistics_service([cid], start, end, product)
    return SisResp(
        ele_overload=sr.ele_overload,
        illegal_ele_app=sr.illegal_ele_app,
        power_quality=sr.power_quality
    )


@summary("首页-报警统计-新版识电u")
async def post_sdu_index_alarm_statistics(req, body: SiasReq) -> SiasResp:
    # 最近30天, 不包含今天
    start, end = last30_day_range()
    product = body.product
    cid = body.cid
    # 安全和报警统计
    res = await sdu_alarm_statistics_service([cid], start, end, product)
    # 安全指数
    alarm_res = await electric_use_info_sdu_new15(cid)
    electric_use_score = round(alarm_res.electric_use_score)
    return SiasResp(
        risk_distribution=res.risk_distribution,
        content_distribution=res.content_distribution,
        electric_use_score=electric_use_score
    )


@summary("用电行为-卡片数据-新版识电u")
async def post_sdu_electric_behave(req, body: SebReq) -> SebResp:
    """近30天用电行为"""
    cid = body.cid
    storeys = body.storeys
    product = body.product
    # 最近30天, 不包含今天
    start, end = last30_day_range()
    return await sdu_electric_behave_service(cid, start, end, storeys, product)


@summary("首页-报警违规排名-新版识电u")
async def post_sdu_index_alarm_ranking(req, body: SiasReq) -> SiarResp:
    """近30天用电行为"""
    cid = body.cid
    product = body.product
    # 最近30天, 不包含今天
    start, end = last30_day_range()
    return await sdu_index_alarm_ranking_service_new15(cid, start, end, product)


@summary("报警统计-报警等级-智电u")
async def post_zdu_level_distribution(req,
                                      body: SduAlarmReq) -> SecurityCountResp:
    product = body.product
    cid = body.cid
    start = body.start
    end = body.end
    return await zdu_level_distribution_service(cid, start, end, product)


@summary("报警统计-报警内容-智电u")
async def post_zdu_content_distribution(req,
                                        body: SduAlarmReq) \
        -> AlarmContentDistributionResp:
    product = body.product
    cid = body.cid
    start = body.start
    end = body.end
    return await zdu_content_distribution_service(cid, start, end, product)


@summary("报警统计-统计概况信息-智电u")
async def post_zdu_summary(req, body: SduAlarmReq) -> ZsResp:
    product = body.product
    cid = body.cid
    start = body.start
    end = body.end
    return await zdu_summary_service(cid, start, end, product)


@summary("报警统计-报警排名-智电u")
async def post_zdu_alarm_sort(req, body: ZasReq) -> ZasResp:
    product = body.product
    cid = body.cid
    start = body.start
    end = body.end
    page_size = body.page_size
    page_num = body.page_num
    return await zdu_alarm_sort_service_2(cid, start, end, page_size, page_num)
