# -*- coding:utf-8 -*-
from unify_api.modules.common.dao.common_dao import storey_by_cid, \
    tsp_by_cid, monitor_point_join, inline_zdu_all_by_cid
from unify_api.modules.common.dao.level_dao import transformer_by_cid, \
    feeder_by_cid, power_dist_by_cid, inline_zdu_by_cid, device_level_by_cid
from unify_api.modules.common.procedures.list_point_pds import \
    monitor_map_point_location
from pot_libs.mysql_util.mysql_util import MysqlUtil
from unify_api.modules.common.components.list_points_cps import (
    ListPointRequest,
    ListPointResponse,
    CommonPoint,
    CommonLocation,
    Inline, LsRep, LtpRep, LplResp, LpiResp
)
from unify_api.modules.common.dao.common_dao import (
    load_user_lang, load_monitor_names
)


async def list_storey_service(cid):
    """获取楼层-识电u"""
    storey_list = await storey_by_cid(cid)
    # 根据storey_name排序
    storeys = []
    for storey in storey_list:
        storey_id = storey["storey_id"]
        storey_id_list = [i["storey_id"] for i in storeys]
        if storey_id not in storey_id_list:
            storeys.append({
                "storey_id": storey_id,
                "storey_name": storey["storey_name"]
            })
    return LsRep(storeys)


async def list_tsp_point_service(cid):
    """获取TSP监测点-扬尘"""
    tsp_list = await tsp_by_cid(cid)
    return LtpRep(tsp_list)


async def list_point_level_service(cid):
    """新版监测点-包含进线变压器层级"""
    # 1.构造cid下每个monitor包含的point和location
    monitor_p_dic, monitor_l_dic = await monitor_map_point_location(cid)
    # 1. 进线
    inline_zdu_list = await inline_zdu_by_cid(cid)
    inline_res = [{"name": inline["m2.name"],
                   "id": inline["inlid"],
                   "point_id": monitor_p_dic.get(inline["mtid"]),
                   "location_id": monitor_l_dic.get(inline["mtid"]) or []}
                  for inline in inline_zdu_list]
    # 2. 变压器
    transformer_list = await transformer_by_cid(cid)
    transformer_res = [{"name": t["m2.name"],
                        "id": t["transf_id"],
                        "point_id": monitor_p_dic.get(t["mtid"]),
                        "location_id": monitor_l_dic.get(t["mtid"]) or []}
                       for t in transformer_list]
    # 3. 馈线
    feeder_list = await feeder_by_cid(cid)
    feeder_res = [{"name": f["m2.name"],
                   "id": f["feeder_id"],
                   "point_id": monitor_p_dic.get(f["mtid"]),
                   "location_id": monitor_l_dic.get(f["mtid"]) or []}
                  for f in feeder_list]
    # 4. 配电
    power_dist_list = await power_dist_by_cid(cid)
    power_dist_res = [{"name": p["m2.name"],
                       "id": p["power_dist_id"],
                       "point_id": monitor_p_dic.get(p["mtid"]),
                       "location_id": monitor_l_dic.get(p["mtid"]) or []}
                      for p in power_dist_list]
    # 5. 设备级
    device_list = await device_level_by_cid(cid)
    device_res = [{"name": d["m2.name"],
                   "id": d["dev_lv_id"],
                   "point_id": monitor_p_dic.get(d["mtid"]),
                   "location_id": monitor_l_dic.get(d["mtid"]) or []}
                  for d in device_list]

    monitor_point_list = await monitor_point_join(cid)
    return LplResp(
        inline=inline_res,
        transformer=transformer_res,
        feeder=feeder_res,
        power_dist=power_dist_res,
        device=device_res,
        power_show_all=1 if any(
            i for i in monitor_point_list if i["add_to_company"] == 1) else 0
    )


async def list_point_inline_service(cid):
    """新版监测点-进线"""
    inline_zdu_dic = await inline_zdu_all_by_cid(cid)
    inlines = [{"name": inline["name"], "inline_id": inline["inlid"]} for
               inline in inline_zdu_dic]
    return LpiResp(inlines=inlines)


async def load_list_point(user_id, cid):
    sql = "SELECT p.pid, p.mtid, m.name, p.add_to_company FROM point p " \
          "INNER JOIN monitor m ON p.mtid=m.mtid " \
          "WHERE m.demolished=0 AND m.cid=%s;"
    async with MysqlUtil() as conn:
        points = {r["mtid"]: r for r in await conn.fetchall(sql, (cid,))}
        if not points:
            return ListPointResponse(points=[], inlines=[], power_show_all=0)

        locs = {mtid: [] for mtid in list(points.keys())}
        sql = f"SELECT ln.lid, ln.item, ln.mtid " \
              f"FROM location ln INNER JOIN monitor mr on ln.mtid = mr.mtid " \
              f"WHERE mr.demolished=0 AND mr.cid=%s"
        for r in await conn.fetchall(sql, (cid,)):
            mtid, lid, item = r["mtid"], r["lid"], r["item"]
            loc_item = CommonLocation(location_id=lid, item=item)
            if mtid not in locs:
                locs[mtid] = [loc_item]
            else:
                locs[mtid].append(loc_item)

        list_point = []
        lang = await load_user_lang(user_id)
        if lang != "zh_CN":
            mtr_names = await load_monitor_names(list(points.keys()), lang)
        else:
            mtr_names = {}
        for mtid, point in points.items():
            pid, p_name = point["pid"], point.get("name", "")
            add_to_company = point["add_to_company"]
            mtr_name = mtr_names.get(mtid, p_name)
            p_item = CommonPoint(name=mtr_name, point_id=pid,
                                 locations=locs.get(mtid, {}),
                                 add_to_company=add_to_company)
            list_point.append(p_item)

        sql = "SELECT inlid, `name` FROM inline WHERE cid=%s"
        inline_list = [Inline(inline_id=r["inlid"], name=r["name"])
                       for r in await conn.fetchall(sql, (cid,))]

        return ListPointResponse(
            points=list_point,
            inlines=inline_list,
            power_show_all=1 if any(
                i for i in list_point if i.add_to_company == 1) else 0
        )
