import logging
import datetime
import requests

from common.utils.encryption import imei_md5
from common.utils.repositories import monitor_resp

logger = logging.getLogger("")


class MonitorService(object):
    def get_target_table(self, imei):
        rst = monitor_resp.get_tar_table_name(imei)
        if rst and rst[0]["point_id"]:
            return "mo_" + rst[0]["number"].split("-")[-1], rst[0]["point_id"], \
                   rst[0]["current_ratio"], rst[0]["voltage_ratio"]
        else:
            return "mo_test", None, 1, 1

    def insert_raw_or_create_tb(self, table, imei, point_id, value,
                                tm=None, current_ratio=1, voltage_ratio=1):
        va_list = value.get("data")
        if not va_list:
            return
        current_ratio = float(current_ratio)
        voltage_ratio = float(voltage_ratio)
        vl_len = len(va_list)
        for i in range(vl_len):
            if point_id:
                va_list[i].update({"point_id": point_id})
            else:
                va_list[i].update({"imei": imei})
            dt = datetime.datetime.strptime(tm, "%Y-%m-%d %H:%M:%S")
            va_list[i]["ua"] = va_list[i]["ua"] * voltage_ratio
            va_list[i]["ub"] = va_list[i]["ub"] * voltage_ratio
            va_list[i]["uc"] = va_list[i]["uc"] * voltage_ratio

            va_list[i]["uab"] = va_list[i]["uab"] * voltage_ratio
            va_list[i]["ubc"] = va_list[i]["ubc"] * voltage_ratio
            va_list[i]["uca"] = va_list[i]["uca"] * voltage_ratio

            va_list[i]["ia"] = va_list[i]["ia"] * current_ratio
            va_list[i]["ib"] = va_list[i]["ib"] * current_ratio
            va_list[i]["ic"] = va_list[i]["ic"] * current_ratio
            va_list[i]["ir"] = va_list[i]["ir"] * current_ratio

            va_list[i]["pa"] = va_list[i]["pa"] * current_ratio * voltage_ratio
            va_list[i]["pb"] = va_list[i]["pb"] * current_ratio * voltage_ratio
            va_list[i]["pc"] = va_list[i]["pc"] * current_ratio * voltage_ratio
            va_list[i]["p"] = va_list[i]["p"] * current_ratio * voltage_ratio
            va_list[i]["qa"] = va_list[i]["qa"] * current_ratio * voltage_ratio
            va_list[i]["qb"] = va_list[i]["qb"] * current_ratio * voltage_ratio
            va_list[i]["qc"] = va_list[i]["qc"] * current_ratio * voltage_ratio
            va_list[i]["q"] = va_list[i]["q"] * current_ratio * voltage_ratio
            va_list[i]["sa"] = va_list[i]["sa"] * current_ratio * voltage_ratio
            va_list[i]["sb"] = va_list[i]["sb"] * current_ratio * voltage_ratio
            va_list[i]["sc"] = va_list[i]["sc"] * current_ratio * voltage_ratio
            va_list[i]["s"] = va_list[i]["s"] * current_ratio * voltage_ratio

            va_list[i]["ept"] = va_list[i]["ept"] * current_ratio * voltage_ratio
            va_list[i]["eqi"] = va_list[i]["eqi"] * current_ratio * voltage_ratio
            va_list[i]["eqe"] = va_list[i]["eqe"] * current_ratio * voltage_ratio
            if va_list[i]["t1"] == -40:
                va_list[i]["t1"] = None
            if va_list[i]["t2"] == -40:
                va_list[i]["t2"] = None
            if va_list[i]["t3"] == -40:
                va_list[i]["t3"] = None
            if va_list[i]["t4"] == -40:
                va_list[i]["t4"] = None
            va_list[i].update({"tm": (dt - datetime.timedelta(minutes=vl_len-1-i)).strftime("%Y-%m-%d %H:%M:%S")})
            monitor_resp.insert_raw_or_create_tb(table, va_list[i])

    def send_to_oa_cet_v2(self, raw):
        url = "http://api.epkeeper.cn/in/v2/?from=zhongdian"
        data = raw["data"][0]
        post_data = {"sn": raw["imei"],
                     "data": {
                         "ua": data["ua"],
                         "ub": data["ub"],
                         "uc": data["uc"],
                         "ia": data["ia"],
                         "ib": data["ib"],
                         "ic": data["ic"],
                         "pa": str(float(data["pa"])*1000),
                         "pb": str(float(data["pb"])*1000),
                         "pc": str(float(data["pc"])*1000),
                         "psum": str(float(data["p"])*1000),
                         "qa": str(float(data["qa"])*1000),
                         "qb": str(float(data["qb"])*1000),
                         "qc": str(float(data["qc"])*1000),
                         "qsum": str(float(data["q"])*1000),
                         "pfa": data["pfa"],
                         "pfb": data["pfb"],
                         "pfc": data["pfc"],
                         "pf": data["pf"],
                         "fr": data["f"],
                         "px": str(float(data["p_d"])*1000),
                         "ep": data["ept"],
                         "eq1": data["eqi"],
                         "eq2": data["eqe"],
                         "udis": str(float(data["lvur"])*0.01),
                         "idis": str(float(data["iur"])*0.01),
                         "uah": data["ua_thd"],
                         "ubh": data["ub_thd"],
                         "uch": data["uc_thd"],
                         "iah": data["ia_thd"],
                         "ibh": data["ib_thd"],
                         "ich": data["ic_thd"],
                         "tc1": data["t1"],
                         "tc2": data["t2"],
                         "tc3": data["t3"],
                         "tc4": data["t4"],
                     },
                     "t": 0,
                     "s": 0,
                     "v": imei_md5(raw["imei"], "cet")}
        try:
            rst = requests.post(url=url, json=post_data)
            logger.debug(rst.content)
        except Exception as e:
            logger.debug(e)

    def update_monitor_device(self, imei, status):
        monitor_resp.update_monitor_device(imei, status)

    def update_monitor_points(self, point_id, status):
        monitor_resp.update_monitor_points(point_id, status)

    def update_by_iccid(self, imei, iccid):
        monitor_resp.update_monitor_iccid(imei, iccid)

    def update_by_alarm_status(self, alarm, imei, point_id, tm):
        status = 1
        if alarm:
            status = 2
            dt = {
                "name": "监控设备失电",
                "type": 4,
                "level": 2,
                "monitor_point_id": point_id,
                "is_end": False,
            }
        else:
            dt = {
                "type": 0,
                "level": 0,
            }
        monitor_resp.create_or_update_alarm(point_id, dt, tm)
        self.update_monitor_device(imei, status)

        if point_id:
            self.update_monitor_points(point_id, status)


monitor_service = MonitorService()
