#!/usr/bin/python3
# -*- coding: utf-8 -*-

from database import get_db
from sqlalchemy.orm import Session
from fastapi import  Depends
from models import *


def get_idx_01(index_no:str,area_id:str=None, db: Session = Depends(get_db)):
    """
    返回单个指标最新指标信息
    """
    if area_id == None:
        idx_info = db.query(OprIdxStat).filter(OprIdxStat.index_no==index_no).order_by(OprIdxStat.stat_dt.desc()).first()
    else:
        idx_info = db.query(OprIdxStat).filter(OprIdxStat.index_no == index_no,OprIdxStat.area_id == area_id).order_by(
            OprIdxStat.stat_dt.desc()).first()
    if idx_info==None:
        return {'msg':'指标不存在'}

    return {"stat_dt":idx_info.stat_dt,
            'stat_lvl':idx_info.stat_lvl,
            'area_id':idx_info.area_id,
            'area_nm':idx_info.area_nm,
            'index_no':idx_info.index_no,
            'index_nm':idx_info.index_nm,
            'index_value':idx_info.index_value,
            'index_unit':idx_info.index_unit,
            'etl_time':idx_info.etl_time}

def get_idx_02(index_no:str,area_id:str=None, db: Session = Depends(get_db)):
    """
    返回单个指标历史所有信息
    """
    if area_id == None:
        idx_info = db.query(OprIdxStat).filter(OprIdxStat.index_no==index_no).order_by(OprIdxStat.stat_dt.desc()).all()
    else:
        idx_info = db.query(OprIdxStat).filter(OprIdxStat.index_no == index_no,OprIdxStat.area_id == area_id).order_by(
            OprIdxStat.stat_dt.desc()).all()
    result = []
    if idx_info==None:
        return {'msg':'指标不存在'}

    for info in idx_info:
        result.append({"stat_dt":info.stat_dt,
            'stat_lvl':info.stat_lvl,
            'area_id':info.area_id,
            'area_nm':info.area_nm,
            'index_no':info.index_no,
            'index_nm':info.index_nm,
            'index_value':info.index_value,
            'index_unit':info.index_unit,
            'etl_time':info.etl_time})
    return result
