from pot_libs.mysql_util.mysql_util import MysqlUtil
from pot_libs.sanic_api import summary
from unify_api.modules.electric.components.proxy_ranking_cps import \
    ProxyRankingReq, ProxyRankingResp


@summary("安电u管理版本-综合排名")
async def post_elec_count_info(req, body: ProxyRankingReq) -> ProxyRankingResp:
    cids = body.cids
    if not cids:
        return ProxyRankingResp(safety=[], health=[],
                                kwh=[], charge=[])
    month = body.month
    product = body.product
    # sql = "SELECT cid,safe_exp,health_exp,ele_quan,ele_charge " \
    #       "FROM safe_health_stats_cid where cid in %s and cal_month = %s"
    sql = "SELECT ifnull(safe_exp,0) safe_exp," \
          "ifnull(health_exp,0) health_exp," \
          "ifnull(ele_quan,0) ele_quan," \
          "ifnull(ele_charge,0) ele_charge," \
          "shsc.cid," \
          "company.shortname FROM safe_health_stats_cid shsc " \
          "left join company on shsc.cid=company.cid where " \
          "shsc.cid in %s and shsc.cal_month = %s"
    async with MysqlUtil() as conn:
        res = await conn.fetchall(sql, args=(cids, month))
    if not res:
        return ProxyRankingResp()
    safety_li = []
    health_li = []
    kwh_li = []
    charge_li = []
    for re in res:
        cid_name = re["shortname"]
        safety_li.append({"name": cid_name, "value": int(re["safe_exp"])})
        health_li.append({"name": cid_name, "value": int(re["health_exp"])})
        kwh_li.append({"name": cid_name, "value": int(re["ele_quan"])})
        charge_li.append({"name": cid_name, "value": int(re["ele_charge"])})
    safety_li_st = sorted(safety_li, key=lambda i: i['value'], reverse=True)
    health_li_st = sorted(health_li, key=lambda i: i['value'], reverse=True)
    kwh_li_st = sorted(kwh_li, key=lambda i: i['value'], reverse=True)
    charge_li_st = sorted(charge_li, key=lambda i: i['value'], reverse=True)
    return ProxyRankingResp(safety=safety_li_st, health=health_li_st,
                            kwh=kwh_li_st, charge=charge_li_st)
