from apps.mtm.models import Goal, Mgroup
from django.core.cache import cache
from django.db.models import Q

def get_mgroup_goals(mgroupId, year, reload=False):
    """
    获取工段某年的全部目标值, 以字典形式返回, 带缓存
    """
    goals = Goal.objects.filter(Q(mgroup__id=mgroupId)|Q(mgroup__name=mgroupId), year=year)
    key = f'mgroup_{mgroupId}_goals'
    if reload is False:
        mgroup_goals = cache.get(key, None)
        if mgroup_goals is not None:
            return mgroup_goals
    mgroup_goals = {}
    for goal in goals:
        mgroup_goals[f'{goal.goal_cate.code}_year'] = goal.goal_val
        for i in range(12):
            mgroup_goals[f'{goal.goal_cate.code}_{i+1}'] = getattr(goal, f'goal_val_{i+1}')
    cache.set(key, mgroup_goals, 10)
    return mgroup_goals