import json
import time
import aioredis
import re
from pot_libs.settings import SETTING
from unify_api.modules.electric.procedures.electric_util import \
    add_random_change
from pot_libs.logger import log
from unify_api import constants
from unify_api.modules.common.service.td_engine_service import \
    get_td_engine_data
from unify_api.utils.taos_new import parse_td_columns

METERDATA_CURRENT_KEY = "meterdata_current"
METERDATA_CURRENT_HR_KEY = "meterdata_hr_current"


async def elec_current_data(point_mid):
    """用电监测实时值"""
    now_ts = int(time.time())
    res = None

    # pipline查询redis
    redis = await aioredis.create_redis_pool(SETTING.redis_single)
    tr1 = redis.multi_exec()
    for point, mid_ctnum in point_mid.items():
        mid = mid_ctnum["mid"]
        tr1.hget(METERDATA_CURRENT_KEY, mid)
    res_p1 = await tr1.execute()

    tr2 = redis.multi_exec()
    for point, mid_ctnum in point_mid.items():
        mid = mid_ctnum["mid"]
        tr2.hget(METERDATA_CURRENT_HR_KEY, mid)
    res_p2 = await tr2.execute()

    i = 0
    ret_dic = {}
    for point, mid_ctnum in point_mid.items():
        result = res_p1[i]
        result2 = res_p2[i]
        i += 1
        mid = mid_ctnum["mid"]
        ctnum = mid_ctnum["ctnum"]

        # 原本的计算逻辑
        if result and result2:
            res = json.loads(result)
            res2 = json.loads(result2)
            real1_tt = res.get("timestamp")
            real_tt = res2.get("timestamp")
            if (
                    real1_tt
                    and real_tt
                    and now_ts - real1_tt <= constants.REAL_EXP_TIME
                    and now_ts - real_tt <= constants.REAL_EXP_TIME
            ):
                for k in res2.keys():
                    if not k in res.keys():
                        res[k] = res2[k]
            else:
                log.info("1 realtime_elec_qual of mid %s is expired." % mid)
                res = None
        elif result2:
            res = json.loads(result2)
            real_tt = res.get("timestamp")
            if real_tt and now_ts - real_tt <= constants.REAL_EXP_TIME:
                res = res
            else:
                log.info("2 realtime_elec_qual of mid %s is expired." % mid)
                res = None
        elif result:
            res = json.loads(result)
            real_tt = res.get("timestamp")
            if real_tt and now_ts - real_tt <= constants.REAL_EXP_TIME:
                res = res
            else:
                log.info("3 realtime_elec_qual of mid %s is expired." % mid)
                res = None
        else:
            log.error("realtime_elec_qual not exist")

        # 加些随机变化(防止数据一直不变化)
        if res:
            for k in res.keys():
                res[k] = add_random_change(res[k])
        else:
            log.error("realtime_elec_qual not exist")
            ret_dic[mid] = None
            continue

        if not ctnum:
            # 如果已经拆掉了，还有报文，用报文中的ctnum
            ctnum = res.get("ctnum") or 3

        if "ctnum" in res:
            del res["ctnum"]

        # 识电U只有一项有数据,返回具体的项
        res["sdu_i"] = None
        res["sdu_u"] = None
        if "ia" in res and "ib" not in res and "ic" not in res:
            res["sdu_i"] = "ia"
            if ctnum == 3:
                res["sdu_u"] = "ua"
            if ctnum == 2:
                res["sdu_u"] = "uab"
        if "ib" in res and "ia" not in res and "ic" not in res:
            res["sdu_i"] = "ib"
            if ctnum == 3:
                res["sdu_u"] = "ub"
        if "ic" in res and "ia" not in res and "ib" not in res:
            res["sdu_i"] = "ic"
            if ctnum == 3:
                res["sdu_u"] = "uc"
            if ctnum == 2:
                res["sdu_u"] = "ucb"

        ret_dic[mid] = res

    return ret_dic


async def qual_current_data(point_mid):
    """电能质量实时值"""
    now_ts = int(time.time())
    res = None

    # pipline查询redis
    redis = await aioredis.create_redis_pool(SETTING.redis_single)
    tr1 = redis.multi_exec()
    for point, mid_ctnum in point_mid.items():
        mid = mid_ctnum["mid"]
        tr1.hget(METERDATA_CURRENT_KEY, mid)
    res_p1 = await tr1.execute()

    tr2 = redis.multi_exec()
    for point, mid_ctnum in point_mid.items():
        mid = mid_ctnum["mid"]
        tr2.hget(METERDATA_CURRENT_HR_KEY, mid)
    res_p2 = await tr2.execute()

    i = 0
    ret_dic = {}
    for point, mid_ctnum in point_mid.items():
        result = res_p1[i]
        result2 = res_p2[i]
        i += 1
        mid = mid_ctnum["mid"]
        ctnum = mid_ctnum["ctnum"]

        # 原本的计算逻辑
        if result and result2:
            res = json.loads(result)
            res2 = json.loads(result2)
            real1_tt = res.get("timestamp")
            real_tt = res2.get("timestamp")
            if (
                    real1_tt
                    and real_tt
                    and now_ts - real1_tt <= constants.REAL_EXP_TIME
                    and now_ts - real_tt <= constants.REAL_EXP_TIME
            ):
                for k in res2.keys():
                    if not k in res.keys():
                        res[k] = res2[k]
            else:
                log.info("1 realtime_power_qual of mid %s is expired." % mid)
                res = None
        elif result2:
            res = json.loads(result2)
            real_tt = res.get("timestamp")
            if real_tt and now_ts - real_tt <= constants.REAL_EXP_TIME:
                res = res
            else:
                log.info("2 realtime_power_qual of mid %s is expired." % mid)
                res = None
        elif result:
            res = json.loads(result)
            real_tt = res.get("timestamp")
            if real_tt and now_ts - real_tt <= constants.REAL_EXP_TIME:
                res = res
            else:
                log.info("3 realtime_power_qual of mid %s is expired." % mid)
                res = None
        else:
            log.error("realtime_elec_qual not exist")

        # 加些随机变化(防止数据一直不变化)
        if res:
            for k in res.keys():
                res[k] = add_random_change(res[k])
        else:
            log.error("realtime_power_quality not exist")
            ret_dic[mid] = None
            continue

        if not ctnum:
            # 如果已经拆掉了，还有报文，用报文中的ctnum
            ctnum = res.get("ctnum") or 3

        if "ctnum" in res:
            del res["ctnum"]

        # 识电U只有一项有数据,返回具体的项
        res["sdu_i"] = None
        res["sdu_u"] = None
        if ctnum == 3:
            if "ua_dev" in res and "ub_dev" not in res and "uc_dev" not in res:
                res["sdu_i"] = "ia"
                res["sdu_u"] = "ua"
            if "ub_dev" in res and "ua_dev" not in res and "uc_dev" not in res:
                res["sdu_i"] = "ib"
                res["sdu_u"] = "ub"
            if "uc_dev" in res and "ub_dev" not in res and "ua_dev" not in res:
                res["sdu_i"] = "ic"
                res["sdu_u"] = "uc"
        if ctnum == 2:
            if "uab_dev" in res and "ucb_dev" not in res:
                res["sdu_i"] = "ia"
                res["sdu_u"] = "uab"
            if "ucb_dev" in res and "uab_dev" not in res:
                res["sdu_i"] = "ic"
                res["sdu_u"] = "ucb"

        ret_dic[mid] = res

    return ret_dic


async def elec_current_data_new15(mtids, cid):
    res_map = {}
    url = f"{SETTING.stb_url}db_electric?tz=Asia/Shanghai"
    sql = f"""
            select tbname,last_row(*) from electric_stb
            where cpyid={cid}
            group by tbname
        """
    is_succ, results = await get_td_engine_data(url, sql)
    if is_succ:
        head = parse_td_columns(results)
        for res in results["data"]:
            data = dict(zip(head, res))
            if data["mtid"] in mtids:
                res_map[data["mtid"]] = data
    return res_map
