from unify_api.modules.zhiwei_u import config
from unify_api.modules.zhiwei_u.dao.select_dao import *
from unify_api.modules.zhiwei_u.components.select_cps import \
    WarningSearchResp, OrderSearchResp
from unify_api.modules.zhiwei_u.dao.warning_operations_dao import get_username
from unify_api.modules.zhiwei_u.procedures.common import get_all_user


async def warning_search_service(params, start, end, state, user_id, page_num,
                                 page_size):
    """运维报警搜索 """
    li = [f"state={state}"]
    for i in ["prod_id", 'cid', 'w_type', 'sid']:
        if params.get(i):
            li.append("%s='%s'" % (i, params.get(i)))
    cond_sql = " and ".join(li)
    if start and end:
        cond_sql += f" and check_dt > '{start}' and check_dt < '{end}'"
    current_page = (page_num - 1) * page_size
    sql = f"SELECT id, cid, compy_name, sid, mtid, monitor_name, w_type, " \
          f"warn_info, check_dt, prod_id, remark  " \
          f"FROM data_warn_record where {cond_sql} " \
          f"ORDER BY check_dt desc limit {current_page}, {page_size}"
    datas = await search_dao(sql)
    user = await get_username(user_id)
    for data in datas:
        data["check_dt"] = data["check_dt"].strftime("%Y-%m-%d %H:%M")
        data["prod_id"] = config.PRODUCT[data["prod_id"]] if data["prod_id"] else None
    t_sql = f"SELECT count(id) total FROM `data_warn_record` where {cond_sql}"
    total = await total_search_dao(t_sql)
    total = 500 if total > 500 else total
    return WarningSearchResp(total=total, is_power=user["role"], rows=datas)


async def order_search_service(params, start, end, page_num, page_size,
                               userid):
    """运维工单搜索"""
    li = []
    if params.get("w_origin") == 1:
        li.append("a.%s='%s'" % ("w_origin", params.get("w_origin")))
        li.append("a.%s='%s'" % ("create_user_id",
                                 params.get("create_user_id")))
    elif params.get("w_origin") == 2:
        li.append("a.%s='%s'" % ("w_origin", 0))
    for i in ["prod_id", 'cid', 'w_type', 'sid', "state"]:
        if params.get(i):
            li.append("a.%s='%s'" % (i, params.get(i)))
    if start and end:
        li.append("a.check_dt>'%s'" % start)
        li.append("a.check_dt<'%s'" % end)
    cond_sql = " and ".join(li)
    if cond_sql:
        cond_sql = "where " + cond_sql
    current_page = (page_num - 1) * page_size
    sql = f"SELECT a.id, a.cid,a.compy_name, a.sid, a.mtid, a.monitor_name, " \
          f"a.w_type,a.order_num,a.warn_info,a.check_dt,a.prod_id, a.state, " \
          f"a.create_user_id,a.handle_user_id,a.w_origin " \
          f"FROM data_order_record a " \
          f"{cond_sql} ORDER BY check_dt desc " \
          f"limit {current_page}, {page_size}"
    datas = await search_dao(sql)
    t_sql = f"SELECT count(id) total FROM `data_order_record` a {cond_sql}"
    total = await total_search_dao(t_sql)
    total = 500 if total > 500 else total
    user_info = await get_all_user()
    user = user_info[userid]
    # user = await get_username(userid)
    for data in datas:
        data["check_dt"] = data["check_dt"].strftime("%Y-%m-%d %H:%M")
        if data["w_origin"] == 1:
            create_data = user_info[data["create_user_id"]]
            # create_data = await get_username(data["create_user_id"])
            data["origin"] = f"{create_data['user_name']}"
        else:
            data["origin"] = "自动"
        if data["handle_user_id"]:
            handle_user = user_info[data["handle_user_id"]]
            # handle_user = await get_username(data["handle_user_id"])
            data["username"] = handle_user["user_name"]
        data["prod_id"] = config.PRODUCT[data["prod_id"]]
        data["is_order"] = 1 if user["role"] == 2 else 0
        data["is_mod"] = 1 if \
            userid == data["create_user_id"] \
            and data["state"] == 1 and data["w_origin"] == 1\
            else 0
        data["state"] = config.ORDER_STATE[data["state"]]
    return OrderSearchResp(total=total, rows=datas)


async def myself_do_service(params, start, end, page_num, page_size, userid):
    """表示我的待办"""
    li = [f"a.handle_user_id={userid}", "a.state in (1, 2)"]
    for i in ["prod_id", 'cid', 'w_type', 'sid', "state", "create_user_id"]:
        if params.get(i):
            li.append("a.%s='%s'" % (i, params.get(i)))
    cond_sql = " and ".join(li)
    if start and end:
        cond_sql += f" and a.check_dt > '{start}' and a.check_dt < '{end}'"
    if cond_sql:
        cond_sql = "where " + cond_sql
    current_page = (page_num - 1) * page_size
    sql = f"SELECT a.id, a.cid,a.compy_name, a.sid, a.mtid, a.monitor_name, " \
          f"a.w_type,a.order_num,a.warn_info,a.check_dt,a.prod_id, a.state, " \
          f"a.create_user_id,a.handle_user_id,a.w_origin " \
          f"FROM data_order_record a " \
          f"{cond_sql} ORDER BY check_dt desc " \
          f"limit {current_page}, {page_size}"
    datas = await search_dao(sql)
    t_sql = f"SELECT count(id) total FROM `data_order_record` a {cond_sql}"
    total = await total_search_dao(t_sql)
    total = 500 if total > 500 else total
    user_info = await get_all_user()
    for data in datas:
        data["check_dt"] = data["check_dt"].strftime("%Y-%m-%d %H:%M")
        if data["w_origin"] == 1:
            create_data = user_info[data["create_user_id"]]
            data["origin"] = f"{create_data['user_name'] }"
        else:
            data["origin"] = "自动"
        if data["handle_user_id"]:
            handle_user = user_info[data["handle_user_id"]]
            data["username"] = handle_user["user_name"]
        data["prod_id"] = config.PRODUCT[data["prod_id"]]

        data["state"] = config.ORDER_STATE[data["state"]]
    return OrderSearchResp(total=total, rows=datas)
