# -*- coding: utf-8 -*-
from datetime import date, timedelta
from django.db.models import Q
from rpc.decorators import bind_context
from api.models import BusinessKPIData
from themis.models import Team

business_kpi = 'hera/business_kpi_data'

@bind_context(business_kpi + '/import_excel')
def kpi_data_excel_import(ctx, data, kpi_date):
    if not data or not kpi_date:
        return []

    query_date = date(*[int(item) for item in kpi_date.split('-')])
    start_date = date(query_date.year, query_date.month, 1)
    if query_date.month == 12:
        end_date = date(query_date.year + 1, 1, 1)
    else:
        end_date = date(query_date.year, query_date.month + 1, 1)

    BusinessKPIData.objects.filter(kpi_date__gte=start_date, kpi_date__lte=end_date).delete()

    ids = []
    for item in data:
        team = Team.objects.filter(name__contains=item['advertisement_group']).first()
        item['advertisement_group'] = team.id if team else ''
        obj = BusinessKPIData(**item)
        obj.save()
        ids.append(obj.id)
    return ids
