# -*- coding:utf-8 -*-
import random
from collections import defaultdict

from pot_libs.logger import log
from pot_libs.mysql_util.mysql_util import MysqlUtil


async def get_wiring_type(point_id):
    """
    获取监测点接线方式：二表法/三表法
    :param point_id:
    :return: ctnum, mid
    """
    ctnum = None
    mtid = None
    if not point_id:
        log.error("para error point_id:%s exception" % point_id)
        return ctnum, mtid
    sql = "SELECT mtid, ctnum FROM point WHERE pid=%s "
    async with MysqlUtil() as conn:
        result = await conn.fetchone(sql, args=(point_id,))
        if result:
            mtid = result.get("mtid", None)
            ctnum = result.get("ctnum", None)
    return ctnum, mtid


async def load_point_ctnum(pid):
    sql = "SELECT ctnum FROM `point` WHERE pid=%s"
    async with MysqlUtil() as conn:
        result = await conn.fetchone(sql, args=(pid,))
    return result.get("ctnum")


async def batch_get_wiring_type(point_ids):
    """
    获取监测点接线方式：二表法/三表法
    :param point_id:
    :return: ctnum, mid
    """
    # 根据point_id去change_meter_record查询最新的mid
    sql = "SELECT pid, mtid, ctnum FROM point WHERE " \
          "pid in %s ORDER BY pid, create_time"

    async with MysqlUtil() as conn:
        change_meter_records = await conn.fetchall(sql, args=(
            point_ids,)) if point_ids else []

        point_info_map = {
            i["pid"]: i for i in change_meter_records if i.get("pid")}

    return point_info_map


def add_random_change(value):
    """
    给value加一点随机值
    :param value:
    :return:
    """
    try:
        new_value = value + value * random.randint(-10, 10) / 1000
        new_value = -abs(new_value) if value < 0 else abs(new_value)
        return new_value
    except:
        return value


def convert_number(number, divisor=10000, precision=2, convert_to_str=False):
    """
    
    :param number:
    :param divisor:
    :param precision: 小数点精度
    :param convert_to_str:
    :return:
    """
    try:
        number = float(number) / divisor
        number = round(number, precision)
        if convert_to_str:
            str_format = "%%.%sf" % precision
            return str_format % number
        return number
    except:
        return number


def format_value(value, unit="", precision=2, divisor=1, empty=""):
    if value is None:
        return ""
    if unit:
        return "%s%s" % (convert_number(value, divisor, precision), unit)
    return convert_number(value, divisor, precision)


def format_value_by_unit(value, key, with_unit=False):
    mappings = {
        "万kWh": {"precision": 3, "divisor": 10000, "unit": "万kWh"},
        "万元": {"precision": 3, "divisor": 10000, "unit": "万元"},
        "percentage": {"precision": 1, "divisor": 0.01, "unit": "%"},
        "kWh": {"precision": 0, "divisor": 1, "unit": "kWh"},
        "元": {"precision": 4, "divisor": 1, "unit": "元"},
        "元/kW": {"precision": 2, "divisor": 1, "unit": "元/kW"},
        "元/kVA*月": {"precision": 2, "divisor": 1, "unit": "元/kVA*月"},
        "V": {"precision": 1, "divisor": 1, "unit": "V"},
        "A": {"precision": 1, "divisor": 1, "unit": "A"},
        "kW": {"precision": 2, "divisor": 1, "unit": "kW"},
        "kVar": {"precision": 2, "divisor": 1, "unit": "kVar"},
        "cos": {"precision": 2, "divisor": 1, "unit": ""},
        "var_percentage": {"precision": 2, "divisor": 1, "unit": "%"},
        "var_percentage1": {"precision": 2, "divisor": 0.01, "unit": "%"},
        "Hz": {"precision": 2, "divisor": 1, "unit": "Hz"},
    }
    unit = mappings[key]["unit"] if with_unit and key in mappings else ""
    pricison = mappings[key]["precision"] if key in mappings else 2
    divisor = mappings[key]["divisor"] if key in mappings else 1
    return format_value(value, unit, pricison, divisor)


ELEC_UNIT = {
    "ua": "V",
    "ub": "V",
    "uc": "V",
    "uab": "V",
    "ucb": "V",
    "ia": "A",
    "ib": "A",
    "ic": "A",
    "pa": "kW",
    "pb": "kW",
    "pc": "kW",
    "pttl": "kW",
    "qa": "kVar",
    "qb": "kVar",
    "qc": "kVar",
    "qttl": "kVar",
    "freq": "Hz",
    "cosa": "cos",
    "cosb": "cos",
    "cosc": "cos",
    "costtl": "cos",
    "lf": "var_percentage1",
    "ubl": "var_percentage1",
    "ibl": "var_percentage1",
    "thduab": "var_percentage1",  # 二相电压谐波畸变量
    "thducb": "var_percentage1",
    "thdua": "var_percentage1",  # 三相电压谐波畸变量
    "thdub": "var_percentage1",
    "thduc": "var_percentage1",
    "thdia": "var_percentage1",  # 电流谐波畸变量
    "thdib": "var_percentage1",
    "thdic": "var_percentage1",
    "thd": "var_percentage1",
    "hr3ua": "var_percentage1",
    "hr3ub": "var_percentage1",
    "hr3uc": "var_percentage1",
    "hr3uab": "var_percentage1",
    "hr3ucb": "var_percentage1",
    "hr3ia": "var_percentage1",
    "hr3ib": "var_percentage1",
    "hr3ic": "var_percentage1",
    "hr5ua": "var_percentage1",
    "hr5ub": "var_percentage1",
    "hr5uc": "var_percentage1",
    "hr5uab": "var_percentage1",
    "hr5ucb": "var_percentage1",
    "hr5ia": "var_percentage1",
    "hr5ib": "var_percentage1",
    "hr5ic": "var_percentage1",
    "hr7ua": "var_percentage1",
    "hr7ub": "var_percentage1",
    "hr7uc": "var_percentage1",
    "hr7uab": "var_percentage1",
    "hr7ucb": "var_percentage1",
    "hr7ia": "var_percentage1",
    "hr7ib": "var_percentage1",
    "hr7ic": "var_percentage1",
    "hr9ua": "var_percentage1",
    "hr9ub": "var_percentage1",
    "hr9uc": "var_percentage1",
    "hr9uab": "var_percentage1",
    "hr9ucb": "var_percentage1",
    "hr9ia": "var_percentage1",
    "hr9ib": "var_percentage1",
    "hr9ic": "var_percentage1",
    "hr11ua": "var_percentage1",
    "hr11ub": "var_percentage1",
    "hr11uc": "var_percentage1",
    "hr11uab": "var_percentage1",
    "hr11ucb": "var_percentage1",
    "hr11ia": "var_percentage1",
    "hr11ib": "var_percentage1",
    "hr11ic": "var_percentage1",
    "hr13ua": "var_percentage1",
    "hr13ub": "var_percentage1",
    "hr13uc": "var_percentage1",
    "hr13uab": "var_percentage1",
    "hr13ucb": "var_percentage1",
    "hr13ia": "var_percentage1",
    "hr13ib": "var_percentage1",
    "hr13ic": "var_percentage1",
}
