# -*- coding:utf-8 -*-
from pot_libs.logger import log
from pot_libs.mysql_util.mysql_util import MysqlUtil


async def get_all_points(cid):
    """获取工厂所有points"""
    point_infos = {}
    sql = "SELECT pid, name FROM point WHERE cid=%s"
    try:
        async with MysqlUtil() as conn:
            result = await conn.fetchall(sql, args=(cid,))
            point_infos = {res['pid']: res['name'] for res in result}
    except Exception:
        log.error("mysql error")
    return point_infos


async def get_point_inlines(cid):
    """获取工厂所有进线数据"""
    point_inlines = {}
    sql = "SELECT pid, inlid FROM point WHERE cid=%s"
    try:
        async with MysqlUtil() as conn:
            result = await conn.fetchall(sql, args=(cid,))
            point_inlines = {res['pid']: res['inlid'] for res in
                             result}
    except Exception:
        log.error("mysql error")
    return point_inlines


async def get_monitor_points(cid):
    monitor_points = {}
    sql = "SELECT pid, name FROM point WHERE cid=%s"
    try:
        async with MysqlUtil() as conn:
            result = await conn.fetchall(sql, args=(cid,))
            points = {res['pid']: res['name'] for res in result}
    except Exception:
        log.error("mysql error")
        return monitor_points
    
    groups = {}
    sql = "SELECT id, `group`, item FROM location WHERE cid=%s"
    try:
        async with MysqlUtil() as conn:
            result = await conn.fetchall(sql, args=(cid,))
            for res in result:
                group = res.get("group")
                groups.setdefault(group, []).append((res['id'], res['item']))
    except Exception:
        log.error("mysql error")
        return monitor_points
    
    for pid, name in points.items():
        items = groups.get(name, [])
        for id, item in items:
            monitor_points.setdefault(pid, []).append(id)
    
    return monitor_points
