import json
import re
from unify_api.utils.common_utils import round_2
from pot_libs.mysql_util import mysql_util
from pot_libs.sanic_api import summary
from unify_api.modules.common.procedures.pttl_max import load_pttl_max_15min
from unify_api.modules.load_analysis.components.load_distribution_cps import \
    DistributionReq, DistributionResp, LrBins, MaxpResp


def deal_x(x):
    """对x轴进线处理"""
    x_temp = []
    for index, value in enumerate(x):
        tmp_list = re.findall(r"\d+\.?\d*", value)
        print(tmp_list)
        if index == 0:
            x_temp.append(0)
        else:
            x_temp.append(int(float(tmp_list[0]) * 100))
    x_temp.append(100)
    return x_temp


@summary('负荷分布')
async def post_load_distribution(req,
                                 body: DistributionReq) -> DistributionResp:
    """负荷分布"""
    # 1.获取参数
    inline_id = body.inline_id
    start = body.start
    end = body.end
    cid = body.cid
    # 2.查询mysql数据
    sql = "select * from algo_load_character_basic where " \
          "inlid = %s and month >= %s and month <= %s"
    async with mysql_util.MysqlUtil() as conn:
        result = await conn.fetchone(sql, args=(inline_id, start, end))
    if not result:
        return DistributionResp()
    # 负载率
    lr_bins = json.loads(result["lr_bins"])
    x = lr_bins["bins_index"]
    y = lr_bins["bins"]
    # 对x进行处理
    x = deal_x(x)
    lb = LrBins(x=x, y=y)
    # 基础负荷
    base_load = result["base_load"]
    # 平均负载率
    mean_load_rate = result["mean_load_rate"]
    # 峰谷差
    peak_valley = result["peak_valley"]
    # 最高负荷
    max_val, max_val_time = await load_pttl_max_15min(cid=cid, start=start,
                                                      end=end,
                                                      inline_id=inline_id)
    max_p = MaxpResp(maxp=round_2(max_val), date_time=max_val_time)
    return DistributionResp(base_load=base_load, mean_load_rate=mean_load_rate,
                            peak_valley=peak_valley, max_load=max_p,
                            lr_bins=lb)
