from pot_libs.es_util.es_utils import EsUtil
from pot_libs.logger import log
from pot_libs.mysql_util.mysql_util import MysqlUtil
from unify_api.constants import COMPANY_15MIN_POWER, SLOTS, SLOTS_15MIN
from unify_api.modules.elec_charge.components.elec_statistics_cps import \
    SlotValue
from unify_api.modules.elec_charge.dao.elec_charge_dao import \
    power_charge_p_aggs
from unify_api.utils.common_utils import round_2
from unify_api.utils.es_query_body import EsQueryBody, es_process, \
    sql_time_process
from unify_api.utils.time_format import time_pick_transf


async def proxy_today_yesterday_p(cid_list, start, end):
    """proxy首页今日和昨日负荷"""
    index = COMPANY_15MIN_POWER
    terms = {"cid": cid_list}
    # 1.构造query_body
    query = EsQueryBody(terms=terms, start=start, end=end,
                        date_key="quarter_time", size=0)
    query_body = query.query()
    query_body["aggs"] = {
        "quarter_time": {
            "date_histogram": {
                "field": "quarter_time",
                "interval": "15m",
                "time_zone": "+08:00",
                "format": "yyyy-MM-dd HH:mm:ss"
            },
            "aggs": {
                "p": {
                    "stats": {
                        "field": "p"
                    }
                }
            }
        }
    }
    log.info(index + f"====={query_body}")
    # 2.获取slots
    intervel, slots = time_pick_transf(start, end)
    # 3. 查询es
    async with EsUtil() as es:
        es_re = await es.search_origin(body=query_body, index=index)
    es_re = es_re["aggregations"]["quarter_time"]["buckets"]
    if not es_re:
        return SlotValue(slots=slots, value=[])
    # 4.为了es结果和slots对应
    es_re = es_process(es_re, fmat="HH:mm")
    sv = SlotValue()  # 今日负荷对象
    sv.slots = slots
    tmp_list = []
    # 5.拼接返回
    for slot in slots:
        if slot in es_re:
            # 1.每个时间点,电量信息
            value = es_re[slot].get("p").get("sum")
            # 值为0是正常数据
            if value == 0:
                tmp_list.append(0.0)
            else:
                tmp_list.append(value or "")
        else:
            tmp_list.append("")
    sv.value = tmp_list
    return sv


async def proxy_today_yesterday_p_new15(cid_list, start, end):
    """proxy首页今日和昨日负荷"""
    sql = f"""
        select create_time,sum(p) as p from company_15min_power
        where cid in %s and create_time between %s and %s
        group by create_time
        order by create_time asc
    """
    # 2.获取slots
    intervel, slots = time_pick_transf(start, end)
    # 3. 查询es
    async with MysqlUtil() as conn:
        res = await conn.fetchall(sql=sql, args=(cid_list, start, end))
    if not res:
        return SlotValue(slots=slots, value=[])
    # 4.为了es结果和slots对应
    es_re = sql_time_process(res, fmt="%H:%M", time_key='create_time')
    sv = SlotValue()  # 今日负荷对象
    sv.slots = slots
    tmp_list = []
    # 5.拼接返回
    for slot in slots:
        if slot in es_re:
            # 1.每个时间点,电量信息
            value = es_re[slot].get("p")
            # 值为0是正常数据
            if value == 0:
                tmp_list.append(0.0)
            else:
                tmp_list.append(value or "")
        else:
            tmp_list.append("")
    sv.value = tmp_list
    return sv


def by_slots(slots, es_re_dic):
    # 拼接slot, value返回
    kwh_list = []
    charge_list = []
    # 功率: 取sum, 15分组则为电量乘以4, 效果一样
    p_list = []
    price_list = []
    for slot in slots:
        if slot in es_re_dic:
            # 1.每个时间点,电量信息
            kwh_value = round_2(es_re_dic[slot].get("kwh"))
            # 2.每个时间点,电费信息
            charge_value = round_2(es_re_dic[slot].get("charge"))
            # 3. 功率
            p_value = round_2(es_re_dic[slot].get("p"))
            # 4. 电价
            try:
                price_value = round_2(charge_value / kwh_value)
            except Exception as e:
                price_value = ""
            kwh_list.append(kwh_value)
            charge_list.append(charge_value)
            p_list.append(p_value)
            price_list.append(price_value)
        else:
            kwh_list.append("")
            charge_list.append("")
            p_list.append("")
            price_list.append("")
    return kwh_list, charge_list, p_list, price_list


async def power_charge_p_proxy(cid_list, start, end, date_type, interval):
    """渠道版下载excel,电量/电费/平均功率/电价"""
    if date_type == "day":
        # 1. 96个点数据
        slots_96 = SLOTS_15MIN
        es_re_96 = await power_charge_p_aggs(start, end, cid_list, "15m")
        es_re_96_dic = es_process(es_re_96, fmat="HH:mm",
                                  time_key="create_time")  # 为了es结果和slots对应
        kwh_24, charge_24, p_24, price_24 = by_slots(slots_96, es_re_96_dic)
        # 96个点,工厂电量电费
        
        # 2. 24个点数据
        slots_24 = SLOTS[date_type]
        es_re_24 = await power_charge_p_aggs(start, end, cid_list, "hour")
        es_re_24_dic = es_process(es_re_24, fmat="HH:mm",
                                  time_key="create_time")  # 为了es结果和slots对应
        kwh_24, charge_24, p_24, price_24 = by_slots(slots_24, es_re_24_dic)
    
    # elif date_type == "month":
    #     intervel, slots = time_pick_transf(start, end)
    #     es_re = es_process(es_re, fmat="MM-DD")  # 为了es结果和slots对应
