# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function

import datetime

from django.db.models import Q, Count

from gm_types.point import ACTIVITY_TYPE, POINT_ACTIVITY_RESULT_TYPE, GOODS_TYPE
from gm_types.point.error import ERROR

from rpc.tool.error_code import gen

from api.models import ChannelGift
from point.models import PointActivity, PointActivityGoods, PointUserGoods
from hera.models import Config


def _try_get_point_activity(point_activity_id, now=None):
    pa = PointActivity.objects.filter(id=point_activity_id, is_online=True,
                                      start_time__lte=now, end_time__gt=now).first()

    return pa


def get_point_activity_goods_id_to_count(point_activity_goods_ids, user_id):
    point_activity_goods_id_to_count = {i.get('activity_goods_id'): i.get('count') for i in
                                        PointUserGoods.objects.filter(
                                            user_id=user_id,
                                            activity_goods_id__in=point_activity_goods_ids
                                        ).values('activity_goods_id').annotate(count=Count('id'))}

    return point_activity_goods_id_to_count


def get_point_activity_id_to_count(point_activity_ids, user_id):
    point_activity_id_to_count = {i.get('activity_id'): i.get('count') for i in
                                  PointUserGoods.objects.filter(
                                      user_id=user_id,
                                      activity_id__in=point_activity_ids
                                  ).values('activity_id').annotate(count=Count('id'))}

    return point_activity_id_to_count


def get_channel_gift_id_to_coupon_infos(all_channel_gift_id):
    channel_gift_id_to_coupon_infos = {}
    all_cg = ChannelGift.objects.filter(id__in=all_channel_gift_id).select_related('gift')
    for cg in all_cg:
        info_data = cg.gift.info_data
        start_time = cg.gift.start_time.strftime('%Y-%m-%d')
        end_time = cg.gift.end_time.strftime('%Y-%m-%d')
        time_text = '有效期 {}-{}'.format(start_time, end_time)
        ci = {
            "coupon_claim_start_time": info_data['start_time'],
            "coupon_claim_end_time": info_data['end_time'],
            "coupon_claim_time_desc": time_text,
            "coupon_values": info_data['value'],
            "coupon_count": info_data['coupon_number'],
        }
        channel_gift_id_to_coupon_infos[cg.id] = ci
    return channel_gift_id_to_coupon_infos


def get_user_activity_record(user_id, start, count):
    record_data = list(PointUserGoods.objects.filter(
        user_id=user_id
    ).order_by('-create_time')[start:start + count])

    all_activity_ids = {r.activity_id for r in record_data}
    all_activity_goods_id = {r.activity_goods_id for r in record_data}

    activity_id_to_activity_type = {
        aid: atype for aid, atype in PointActivity.objects.filter(
            id__in=all_activity_ids).values_list('id', 'activity_type')
    }

    activity_good_id_to_obj = {
        pag.id: pag for pag in PointActivityGoods.objects.filter(
            id__in=all_activity_goods_id).select_related('good')
    }

    result = []
    for record in record_data:
        activity_type = activity_id_to_activity_type[record.activity_id]

        type_name = "兑换专区" if activity_type == ACTIVITY_TYPE.EXCHANGE else "幸运抽奖"
        thumb = None

        if record.activity_goods_id:
            activity_goods = activity_good_id_to_obj[record.activity_goods_id]

            thumb = activity_goods.good.thumb

            if activity_goods.good.goods_type == GOODS_TYPE.POINT:
                activity_result_type = POINT_ACTIVITY_RESULT_TYPE.POINT
            elif activity_goods.good.goods_type == GOODS_TYPE.COUPON:
                activity_result_type = POINT_ACTIVITY_RESULT_TYPE.COUPON
            elif activity_goods.good.goods_type == GOODS_TYPE.REAL:
                activity_result_type = POINT_ACTIVITY_RESULT_TYPE.REAL
            else:
                activity_result_type = POINT_ACTIVITY_RESULT_TYPE.NOTHING
            good_name = activity_goods.good.name

        else:
            activity_result_type = POINT_ACTIVITY_RESULT_TYPE.NOTHING
            good_name = "谢谢参与"

        title = "{}，{}".format(type_name, good_name)
        time_desc = record.create_time.strftime('%Y-%m-%d %H:%M:%S')
        use_point = record.point

        r = {
            'title': title,
            'time_desc': time_desc,
            'use_point': use_point,
            'thumb': thumb,
            'activity_result_type': activity_result_type
        }
        result.append(r)
    return result


def get_point_mall_config():
    # 潜规则编程  point_1 是 ACTIVITY_TYPE.LOTTERY 的id
    # point_2 和 point_3 是 ACTIVITY_TYPE.EXCHANGE 的id
    # point_4 是 free_activity的id
    keys = ['point_1', 'point_2', 'point_3', 'point_4']

    activity_key_to_id = {}

    configs = Config.objects.filter(key__in=keys)

    for c in configs:
        activity_key_to_id[c.key] = c.value

    return activity_key_to_id
