from apps.enp.models import EnvData
from apps.enp.serializers import EnvDataSerializer
from datetime import datetime

def get_last_envdata(eIds: list, time_start: datetime, time_end: datetime):
    eIds_str = ",".join([f"'{item}'" for item in eIds])  # 将 ID 列表格式化为字符串
    time_start_str = time_start.strftime("%Y-%m-%d %H:%M:%S")
    time_end_str = time_end.strftime("%Y-%m-%d %H:%M:%S")
    esql = f'''
    SELECT DISTINCT ON (equipment_id) *
    FROM enp_envdata ee
    WHERE equipment_id IN ({eIds_str})
    AND timex AT TIME ZONE 'Asia/Shanghai' >= '{time_start_str}'
    AND timex AT TIME ZONE 'Asia/Shanghai' <= '{time_end_str}'
    ORDER BY equipment_id, timex DESC
    '''
    edata = EnvDataSerializer(EnvData.objects.raw(esql), many=True).data

    # esql ='''SELECT DISTINCT ON (equipment_id) *
                #             FROM enp_envdata ee
                #             WHERE equipment_id IN %s
                #             AND timex AT TIME ZONE 'Asia/Shanghai' >= %s
                #             AND timex AT TIME ZONE 'Asia/Shanghai' <= %s
                #             ORDER BY equipment_id, timex DESC'''
                # res = query_all_dict(esql, [tuple(data_ids), now_10_before_str, now_str])
    return edata