# -*- coding:utf-8 -*-

import datetime
import time

from api.models import AssistPrize, AssistCode, Assister, AssistThirdInfo
from api.util.user_util import simple_user_info_by_user_ids

def get_successful_user_by_prize(prize_id):
    '''
    获取满足领取奖品条件的用户
    '''
    user_id_list = AssistCode.get_successful_user_by_pid(prize_id)
    user_info_list = simple_user_info_by_user_ids(user_id_list).values()
    user_info_list.sort(key=lambda x:user_id_list.index(x['user_id']))
    for uinfo in user_info_list:
        uinfo['nick_name'] = uinfo['nick_name'].strip()[0] + '*****'
    return user_info_list


def get_assister_info(code_obj):
    '''
    获取助力者信息
    '''
    if not code_obj:
        return []
    a_code = code_obj.a_code
    helper_list = Assister.get_assister_by_code(a_code)
    helper_list = list(filter(lambda x:x['assist_status'] == 1, helper_list))
    for x in helper_list:
        x['create_time'] = x['create_time'].strftime('%Y-%m-%d %H:%M')
    return helper_list


def get_code_detail(code_obj):
    '''
    获取助力码详情
    '''
    if not code_obj:
        return {}
    code_info = code_obj.detail_info()
    now = datetime.datetime.now()
    code_info['expired'] = bool(code_info['end_time'] <= now)
    countdown = -1
    if code_obj.assistprize.assist_time_long:
        countdown = int((code_info['end_time'] - now).total_seconds())
        if countdown <= 0:
            countdown = -1
    code_info['countdown'] = countdown
    code_info['start_time'] = int(time.mktime(code_info['start_time'].timetuple()))
    code_info['end_time'] = int(time.mktime(code_info['end_time'].timetuple()))

    return code_info


def _do_assist(user_id, acode):
    '''
    助力操作
    '''
    result = {
            'success': 0,
            'message': '助力失败'
    }
    code_obj = AssistCode.get_obj_by_acode(acode)
    if not code_obj:
        result.update({'reason': '无法获取助力信息'})
        return result

    now = datetime.datetime.now()
    code_info = code_obj.detail_info()
    assist_status = bool(code_info['end_time'] >= now)

    _created = Assister.create_record(user_id, acode, assist_status)
    if not assist_status:
        result.update({'reason': '此次助力已过期'})
    elif _created:
        result.update({'success':1, 'message': '助力成功'})
    return result
