from datetime import datetime

from pot_libs.utils.time_format import convert_timestamp_to_str_no_sec
from unify_api.modules.common.dao.common_dao import monitor_by_cid, \
    company_by_cids, monitor_point_storey_join, company_by_cid, \
    detection_point_by_cid, monitor_page_by_cid, start_time_by_cids, \
    tcs_runtime_by_cids, item_by_mitd_dao
from unify_api.modules.common.procedures.points import point_to_mid
from unify_api.modules.product_info.components.hardware_cps import HisResp, \
    HlsResp, HardwareInfoManResq, HardwareInfoListResq
from unify_api.modules.common.procedures.cids import get_cids


async def hardware_info_sdu_service(cid):
    """安装信息-识电u"""
    # 1. 监测户数
    monitor_list = await monitor_by_cid(cid)
    point_num = len(monitor_list)
    # 2. 安装点数, 去重sid
    sid_list = [monitor["sid"] for monitor in monitor_list]
    device_num = len(set(sid_list))
    # 3. 启用时间
    company_list = await company_by_cids([cid])
    if company_list:
        create_time = company_list[0]["create_time"]
        start_time = datetime.strftime(
            datetime.fromtimestamp(create_time), "%Y-%m-%d %H:%M")
    else:
        start_time = ""
    return HisResp(
        point_num=point_num,
        device_num=device_num,
        start_time=start_time
    )


async def hardware_list_sdu_service(cid, page_num, page_size):
    """安装信息分页数据-识电u"""
    # 1. 总监测户数
    monitor_list = await monitor_by_cid(cid)
    point_num = len(monitor_list)
    # 2. 分页信息
    monitor_point_storey_list = await monitor_point_storey_join(cid, page_num,
                                                                page_size)
    if not monitor_point_storey_list:
        return HlsResp(rows=[], total=0)
    # 3. 增加相序字段
    # pids = [i["pid"] for i in monitor_point_storey_list]
    # # 3.1 point和mid对应关系
    # point_mid, p_num = await point_to_mid(pids)
    # # 3.2 mid查询相序
    # mids = point_mid.values()
    # meter_list = await meter_by_mids(mids=mids)
    # # 把mid提出来, {mid: meter_no}
    # mid_meter_dic = {i["mid"]: i["meter_no"] for i in meter_list}
    mtid_list, mtid_info = [], {}
    for data in monitor_point_storey_list:
        if data["mtid"]:
            mtid_list.append(data["mtid"])
            mtid_info[data["mtid"]] = data
    mtid_item = await item_by_mitd_dao(mtid_list)
    mtid_item_info = {i["mtid"]: i["meter_no"] for i in mtid_item}
    rows = []
    for info in monitor_point_storey_list:
        mtid = info.get("mtid")
        room_name = info["room_name"]
        storey_name = info["storey_name"]
        name = info["name"]
        sid = info["sid"]
        # 增加相序字段
        meter_no = mtid_item_info.get(mtid) + "相"
        create_time = info["create_time"]
        create_time = datetime.strftime(
            datetime.fromtimestamp(create_time), "%Y-%m-%d %H:%M")
        rows.append(
            {
                "room_name": room_name,
                "storey_name": storey_name,
                "name": name,
                "sid": sid,
                "meter_no": meter_no,
                "create_time": create_time
            }
        )
    return HlsResp(rows=rows, total=point_num)


async def hardware_info_management_service(cids):
    # 项目总数 + 时间
    info_list = await company_by_cid(cids)
    if info_list:
        project_count = len(info_list)
        create_time_timestamp = info_list[0].get("create_time")
        start_time = datetime.strftime(
            datetime.fromtimestamp(create_time_timestamp), "%Y-%m-%d %H:%M")
    else:
        project_count, start_time = 0, ""
    # 监测点总数
    detection_point_list = await detection_point_by_cid(cids)
    detection_point_count = detection_point_list[0].get("point_num", 0)
    return HardwareInfoManResq(
        project_count=project_count,
        start_time=start_time,
        detection_point_count=detection_point_count
    )


async def hardware_info_list_manage_service(cids, page_num, page_size):
    info_list = await monitor_page_by_cid(cids, page_num, page_size)
    page_cids = [info.get("cid") for info in info_list]
    for key, value in enumerate(info_list):
        if value["create_time"]:
            info_list[key]["create_time"] = convert_timestamp_to_str_no_sec(
                value["create_time"])
    tcs_counts = await tcs_runtime_by_cids(page_cids)
    if len(tcs_counts) != len(page_cids):
        tcs_cids = [tcs.get("cid") for tcs in tcs_counts]
        loss_list = list(set(page_cids) - set(tcs_cids))
        for num in loss_list:
            tcs_counts = list(tcs_counts)
            tcs_counts.append({"cid": num, "tcs": ""})
    for tcs in tcs_counts:
        for index, info in enumerate(info_list):
            if tcs["cid"] == info["cid"]:
                info_list[index].update(tcs)
                continue
    return HardwareInfoListResq(rows=info_list, total=len(cids))
