# -*- coding:utf-8 -*-
'''
奖品接口等
'''

import datetime

from gm_types.error import ERROR as ERROR_CODES
from gm_types.gaia import TEMP_ACTIVITY_TYPE

from rpc.decorators import bind_context, bind
from rpc.tool.error_code import gen
from api.tool.user_tool import get_user_from_context
from api.models import AssistPrize, AssistCode, Assister, AssistThirdInfo, ActUserWechatInfo
from util import get_code_detail, get_successful_user_by_prize, get_assister_info

TIME_UNSTARTED = -1
TIME_VALID = 0
TIME_EXPIRED = 1

ASSIST_TYPE = TEMP_ACTIVITY_TYPE.NORMAL_ASSIST

@bind_context('account/assist/prize_page')
def prize_page_show(ctx, prize_id, acode=None):
    '''
    助力奖品页面展示
    param prize_id: 奖品id, 必填
    param acode: 助力码
    '''
    ### prize_info
    prize_info = AssistPrize.detail_info_by_id(prize_id)
    if not prize_info:
        gen(ERROR_CODES.ASSIST_PRIZE_INVALID)

    now = datetime.datetime.now()
    time_status = TIME_VALID
    if prize_info['start_time'] > now:
        time_status = TIME_UNSTARTED
    elif prize_info['end_time'] <= now:
        time_status = TIME_EXPIRED
    prize_info['start_time'] = prize_info['start_time'].strftime("%Y-%m-%d %H:%M:%S")
    prize_info['end_time'] = prize_info['end_time'].strftime("%Y-%m-%d %H:%M:%S")
    prize_info['time_status'] = time_status

    ### assist_info  
    user = get_user_from_context(ctx)
    cur_user_id = user and user.id or None

    a_code_obj = None
    if acode:
        a_code_obj = AssistCode.get_obj_by_acode(acode)
        if a_code_obj and str(a_code_obj.assistprize_id) != str(prize_id):
            a_code_obj = None

    if not a_code_obj:
        if cur_user_id:
            a_code_obj = AssistCode.get_last_record_by_uid_pid(cur_user_id, prize_id)

    code_user_id = a_code_obj and a_code_obj.user_id or None
    # code_info
    code_info = {}
    assist_user_info = []
    if a_code_obj:
        code_info = get_code_detail(a_code_obj) 
        assist_user_info = get_assister_info(a_code_obj)
        for u in assist_user_info:
            u['is_valid'] = u['create_time'] <= code_info['end_time']
    assist_info = {}
    assist_info['code_info'] = code_info
    assist_info['assist_users'] = assist_user_info
    # head_user_info
    head_user_id = code_user_id or cur_user_id
    head_user = ActUserWechatInfo.get_third_detail_by_uid_aty(head_user_id, aty_type=ASSIST_TYPE)
    # cur_user_info
    cur_user_info = {}
    cur_user_info['cur_user_id'] = cur_user_id
    cur_user_info['has_assisted'] = Assister.has_assisted_by_uid_code(cur_user_id, code_info.get('a_code'))
    ### combine
    result = {}
    result['prize_info'] = prize_info
    result['head_user'] = head_user
    result['assist_info'] = assist_info
    result['success_user_list'] = get_successful_user_by_prize(prize_id)
    result['cur_user_info'] = cur_user_info
    return result

