from pot_libs.logger import log
from pot_libs.mysql_util.mysql_util import MysqlUtil
from pot_libs.settings import SETTING
from unify_api.utils.cachetools_ttlchache import async_ttl_cache


async def get_username(userid):
    sql = "SELECT user_id, real_name as user_name, zhiweiu_auth as role " \
          "FROM `user` where user_id = %s"
    async with MysqlUtil() as conn:
        user = await conn.fetchone(sql, args=(userid,))
    return user


@async_ttl_cache()
async def select_user_dao(prod_id):
    """根据平台选择客户 """
    sql = f"select cid, shortname from company where product = {prod_id}" \
          f" and is_show = 1 "
    async with MysqlUtil() as conn:
        user_list = await conn.fetchall(sql)
    return user_list


@async_ttl_cache()
async def select_point_dao(cid):
    """根据客户选择监测点 """
    sql = f"select * from point where cid = {cid}"
    async with MysqlUtil() as conn:
        point_list = await conn.fetchall(sql)
    return point_list


async def warning_state_ignore_dao(id, state, remark):
    """运维报警状态改变为已忽略 """
    sql = f"UPDATE data_warn_record set state={state}, remark='{remark}' " \
          f"where id in %s"
    async with MysqlUtil(db=SETTING.mysql_zhiwei_u_db) as conn:
        await conn.execute(sql, args=(id, ))
        log.info(sql % id)


async def warning_state_focus_dao(id, state):
    """运维报警 已忽略撤销 """
    sql = "UPDATE data_warn_record set state=%s where id in %s"
    async with MysqlUtil(db=SETTING.mysql_zhiwei_u_db) as conn:
        await conn.execute(sql, args=(state, id))
        log.info(f"UPDATE data_warn_record set state={state} where id in {id}")


async def get_warn_by_id(id):
    """根据id获取运维报警信息"""
    sql = "select * from data_warn_record where id = %s"
    async with MysqlUtil(db=SETTING.mysql_zhiwei_u_db) as conn:
        data = await conn.fetchone(sql, args=(id,))
    return data


async def insert_order_data(data, w_origin, order_num, username):
    sql = """INSERT INTO `data_order_record` (`cid`, `compy_name`, `sid`, 
    `mtid`, `monitor_name`, `w_type`, `warn_info`, `check_dt`, `prod_id`, 
    `handle_user_id`, `w_origin`, `alarm_record_id`, 
    `create_user_id`, `order_num`)
    VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
    """
    async with MysqlUtil(db=SETTING.mysql_zhiwei_u_db) as conn:
        await conn.execute(sql, args=(data["cid"], data["compy_name"],
                                      data["sid"], data["mtid"],
                                      data["monitor_name"], data["w_type"],
                                      data["warn_info"], data["check_dt"],
                                      data["prod_id"],
                                      None, w_origin, data.get("id"),
                                      username, order_num))
