import json
import time
import aioredis

from pot_libs.settings import SETTING
from unify_api import constants
from unify_api.constants import POINT_LEVEL_MAP
from unify_api.modules.adio.components.adio_card_cps import AcResp
from unify_api.modules.adio.dao.adio_card_dao import \
    monitor_location_join_by_locations, alarm_setting_by_locations
from unify_api.modules.common.procedures.list_point_pds import \
    monitor_map_point_location

ADIO_CURRENT = "adio_current"


async def post_adio_card_service(location_list, cid):
    """安全监测-卡片信息-level"""
    # 构造cid下每个monitor包含的point和location
    monitor_p_dic, monitor_l_dic = await monitor_map_point_location(cid)
    # 1. 获取每个location_id的详细信息, mysql的in查询,打乱了location_list顺序
    monitor_location_list = await monitor_location_join_by_locations(
        location_list)
    # 2. 查询温度漏电流阈值
    alarm_setting_list = await alarm_setting_by_locations(location_list)
    alarm_dic = {alarm["lid"]: alarm for alarm in alarm_setting_list}
    # 3. 根据location_list查询redis
    # multi_exec查询redis
    redis = await aioredis.create_redis_pool(SETTING.redis_single)
    tr = redis.multi_exec()
    for location_id in location_list:
        tr.hget(ADIO_CURRENT, location_id)
    res_redis = await tr.execute()
    # 3. 构造返回
    ret_data = {
        "inline": {},
        "transformer": {},
        "feeder": {},
        "power_dist": {},
        "device": {}
    }
    i = 0
    for info in monitor_location_list:
        m_name = info.get("name")
        mtid = info.get("mtid")
        m_type = POINT_LEVEL_MAP.get(info.get("m_type"))
        location_id = info.get("lid")
        location_type = info.get("ad_type")
        location_item = info.get("item")
        # redis数据
        adio_value = ""
        redis_data = res_redis[i]
        i += 1
        if redis_data:
            adio_info = json.loads(redis_data)
            time_now = int(time.time())
            real_tt = adio_info.get("timestamp", 0)
            if (time_now - real_tt) <= constants.REAL_EXP_TIME:
                adio_value = round(adio_info.get("value", 0), 2)

        threshold = alarm_dic[location_id]["threshold"]
        if m_name in ret_data[m_type]:
            if location_type == "temperature":
                ret_data[m_type][m_name].setdefault(location_type, []).append(
                    {"item": location_item, "value": adio_value}
                )
                # 阈值取最小数值
                if threshold < ret_data[m_type][m_name]["t_threshold"]:
                    ret_data[m_type][m_name]["t_threshold"] = threshold
            else:
                ret_data[m_type][m_name].setdefault(location_type, []).append(
                    {"item": "漏电流", "value": adio_value}
                )
                ret_data[m_type][m_name]["r_threshold"] = threshold
            # 卡片增加location_id字段
            ret_data[m_type][m_name]["location_id"].append(location_id)
        else:
            if location_type == "temperature":
                ret_data[m_type][m_name] = {
                    "name": m_name,
                    "t_threshold": threshold,
                    "temperature": [
                        {"item": location_item, "value": adio_value}]
                }
            else:
                ret_data[m_type][m_name] = {
                    "name": m_name,
                    "r_threshold": threshold,
                    "residual_current": [
                        {"item": "漏电流", "value": adio_value}]
                }
            # 卡片增加location_id字段
            ret_data[m_type][m_name]["location_id"] = [location_id]
            # 卡片增加point_id字段
            ret_data[m_type][m_name]["point_id"] = monitor_p_dic[mtid]
    # 返回内容,转换为list
    for key, value in ret_data.items():
        if value:
            ret_data[key] = [j for i, j in value.items()]
        else:
            ret_data[key] = []
    return AcResp(
        inline=ret_data["inline"],
        transformer=ret_data["transformer"],
        feeder=ret_data["feeder"],
        power_dist=ret_data["power_dist"],
        device=ret_data["device"],
    )
