import hashlib
import requests


def generate_md5_code(sn):
    dt = "dgj" + sn + "cet"
    dt_md5 = hashlib.md5(dt.encode()).hexdigest()
    return dt_md5[8:24]


def post_energy_data(meter_data, gateway_id, tm):
    for meter in meter_data:
        meter_id = meter["id"]
        meter_status = meter["status"]
        meter_name = meter["name"]
        data = meter["values"]
        sn = gateway_id + meter_id
        v = generate_md5_code(sn)

        post_data = {"sn": sn,
                     "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["Fr"],
                         "px": str(float(data["MD"])*1000),
                         "ep": data["EPI"],
                         "eq1": data["EQL"],
                         "eq2": data["EQC"],
                         "udis": str(float(data["VUB"])*0.01),
                         "idis": str(float(data["CUB"])*0.01),
                         "uah": 0,
                         "ubh": 0,
                         "uch": 0,
                         "iah": 0,
                         "ibh": 0,
                         "ich": 0
                     },
                     "v": v}
        requests.post(url="http://api.epkeeper.cn/in/v2/?from=zhongdian",
                      json=post_data)
