# coding=utf-8
import datetime
import json
from celery import shared_task
from django.conf import settings
from operator import itemgetter

from gm_types.gaia import SIGN_TASK_TYPE

from api.models import SettlementItem, Order, SpecialItem
from rpc.cache import sign_rush_cache, sign_task_cache
from gm_types.push import PUSH_INFO_TYPE, AUTOMATED_PUSH
from django.db.models import Q, Max
from api.tasks.push_task import allocate_push_task_users, automate_push_task, push_all_task
from api.models.sign_activity import ActivityPrize, UserLastSign, SignActivity, SignPrize, SignActivityUserStatus, User
from api.models.sign_v2 import SignUserInfoV2, SignUserExchangedPrize, SignBlindExchangePrize, SignUserBlindBox, SignTaskUserFinish, SignBlindBox, SignPrizeV3, SignRecordLogV2, ExchangedRecordV3
from rpc.tool.log_tool import info_logger
from utils.wechat_applet_tools import applet_template_push

rush_cache_key = "sign_rush_user_list"
break_one_day_up = u"Oops❗️你好像断签啦，坚持签到必领多重福利哦！快来补签吧💕"
break_one_day_down = u"今天好像忘记签到啦❗️坚持签到即可100%领取礼品哦🎁~"
break_more_day_down = u"⚠️断签预警，已有92%的签到用户成功领取签到【{prize_name}】，你也不要错过哦～"

sign_new_push_up = u"美好的一天从签到领奖品开始🙋️连续签到100%领到{prize_name}😜还有盲盒抽{final_prize_name}哦～"
sign_new_push_down = u"休息一下吧～养成签到好习惯❗️{prize_name}拿到手软，更有盲盒抽{final_prize_name}哦～"
sign_sunday_push_up = u"周末啦～签到即可获得{prize_name}🎁！还不快行动起来！"
sign_sunday_push_down = u"📣注意！签到必领{prize_name}🔥还能积分抽大奖哦～  ！"


sign_new_push_up_v2 = u"美好的一天从签到领奖开始，连续签到100%领取{pirze_name}哦～"
sign_new_push_down_v2 = u"休息一下吧～养成签到好习惯{prize_name}拿到手软"
sign_sunday_push_up_v2 = u"周末啦～签到即可获得{prize_name}！还不快行动起来！"
sign_sunday_push_down_v2 = u"注意！签到100%领取{prize_name}哦～  ！"


sign_msg_one_up = u"签到1天get✔️，还差9天即可兑换【{prize_name}】，继续加油呀❗️"
sign_msg_one_down = u"你已签到1天🎉，再坚持签到9天就可领取【{prize_name}】， 快来看看吧~"
sign_msg_first_up = u"连续签到的第{has_day}天，爱你❤️保持签到好习惯，还差{day}天【{prize_name}】即可收入囊中~"
sign_msg_first_down = u"你已签到{has_day}天，努力永远都是有回报的❗️再坚持{day}天【{prize_name}】领回家～"
sign_msg_second_up = u"连续签到的第{has_day}天，继续努力签到{day}天把【{prize_name}】拿回家吧❗️"
sign_msg_second_down = u"你已签到{has_day}天💓，还差{day}天【{prize_name}】即可收入囊中✔️～️"
sign_msg_third_up = u"连续签到的第{has_day}天，不要放弃❗️继续签到{day}天把【{prize_name}】拿回家❗️"
sign_msg_third_down = u"你已签到{has_day}天，还差{day}天【{prize_name}】即可收入囊中～"
sign_msg_thirty_up = u"早安😀连续签到礼物多多❗️快来签到领取吧🙋️"
sign_msg_thirty_down = u"连续签到即可获得多重福利🎁快来签到领取吧"

sign_msg_ten_exchanged_up = u"🎊恭喜你！【{prize_name_1}】已经收入囊中❗️再签到{day}天即可领取【{prize_name_2}】，继续加油鸭！"
sign_msg_ten_exchanged_down = u"📣恭喜你已坚持{has_day}天，再签{day}天即可get【{prize_name}】✅，加油鸭！"
sign_msg_ten_up = u"🎉恭喜你已签到{has_day}天，可以来领取【{prize_name_1}】啦！再签{day}天领取【{prize_name_2}】，继续加油鸭！"
sign_msg_ten_down = u"恭喜你已签到{has_day}天，是不是忘记领取【{prize_name_1}】啦！快来领取吧✌再签{day}天领取【{prize_name_2}】，继续加油鸭！"
sign_msg_twenty_exchanged_up = u"🎊恭喜你！【{prize_name_1}】已经收入囊中❗️再签到{day}天即可领取【{prize_name_2}】，继续加油鸭！"
sign_msg_twenty_exchanged_down = u"📣恭喜你已坚持{has_day}天，再签{day}天即可get【{prize_name}】✅，加油鸭！"
sign_msg_twenty_up = u"🎉恭喜你已签到{has_day}天，快来领取【{prize_name_1}】吧！继续签到赢【{prize_name_2}】，终极大奖戳起来！"
sign_msg_twenty_down = u"恭喜你已签到{has_day}天，是不是忘记领取【{prize_name_1}】吧！快来领取吧✌继续签到赢【{prize_name_2}】，终极大奖戳起来！"
sign_msg_thirty_exchanged_up = u"🎊恭喜你！【{prize_name_1}】已经收入囊中❗️再签到{day}天即可领取【{prize_name_2}】，继续加油鸭！"
sign_msg_thirty_exchanged_down = u"📣恭喜你已坚持{has_day}天，再签{day}天即可get【{prize_name_2}】✅，加油鸭！"
sign_msg_thirty_up_whole = u"签到{has_day}天啦！感谢陪伴❤️~记得来领取【{prize_name}】哦，新的一月也要一起加油鸭！"
sign_msg_thirty_down_whole = u"你真的好棒啊❗️签到{has_day}天啦！感谢陪伴~记得来领取【{prize_name}】哦，新的一月也要一起加油鸭！"

sign_msg_exchanged_up_new = u"🎊恭喜你！️再签到{day}天即可领取【{prize_name}】，继续加油鸭！"


def get_activity_info():
    activity = SignActivity.objects.filter(is_online=True, start_time__lte=datetime.datetime.now(),
                                           end_time__gte=datetime.datetime.now()).first()
    if not activity:
        return {}

    activity_goods_list = ActivityPrize.objects.filter(activity_id=activity.id).values("prize_id", "cost", "count")
    good_ids = [item["prize_id"] for item in activity_goods_list]
    # 获取这些商品
    goods_list = SignPrize.objects.filter(pk__in=good_ids).values("id", "name", "short_name", "img_url", "price")
    good_info_dict = {good["id"]: good for good in goods_list}

    goods_info_list = []
    for item in sorted(activity_goods_list, key=itemgetter("cost")):  # 按照兑换等级排序
        _data = dict(item)
        good_id = item.pop("prize_id", 0)
        _data.update(good_info_dict.get(good_id, {}))
        goods_info_list.append(_data)

    return {"activity_id": activity.id, "goods": goods_info_list}


@shared_task
def sign_push_intime():

    #正常签到的push
    activity_data = get_activity_info()
    if not activity_data:
        return {}
    user_list = UserLastSign.objects.filter(activity_id=activity_data.get('activity_id'), newest_time__lt=datetime.date.today(),
                                            newest_time__gte=datetime.date.today()+datetime.timedelta(days=-1))\
                                    .values('user_id', 'available_days')

    remind_users = SignActivityUserStatus.objects.filter(activity_id=activity_data.get('activity_id'), is_remind=True)\
                                                 .values_list('user_id', flat=True)
    url = 'gengmei://common_webview?url={}/phantom/sign_details?navigation_color_clear=1'.format(settings.BACKEND_API_HOST)
    extra = {
        'type': PUSH_INFO_TYPE.GM_PROTOCOL,
        'msgType': 4,
        'pushUrl': url,
        'push_url': url,
    }

    for user_info in user_list:
        if user_info.get('user_id') not in list(remind_users):
            continue
        for prize in activity_data.get('goods'):
            if user_info.get('available_days') >= prize.get('cost'):
                continue
            elif user_info.get('available_days') and prize.get('cost') and \
                    user_info.get('available_days') < prize.get('cost'):
                msg = u'今天还没签到，距离获得{prize_name}还需签到{days}天~'.\
                      format(prize_name=prize.get('short_name'), days=prize.get('cost')-user_info.get('available_days'))
                allocate_push_task_users(user_id=int(user_info.get('user_id')), alert=msg, extra=extra,
                                         push_type=AUTOMATED_PUSH.NEW_CHECK_IN_REMINDER)
                break


@shared_task
def sign_push_late():

    #断签的push
    activity_data = get_activity_info()
    if not activity_data:
        return {}

    url = 'gengmei://common_webview?url={}/phantom/sign_details?navigation_color_clear=1'.format(settings.BACKEND_API_HOST)
    extra = {
        'type': PUSH_INFO_TYPE.GM_PROTOCOL,
        'msgType': 4,
        'pushUrl': url,
        'push_url': url,
    }
    remind_users = SignActivityUserStatus.objects.filter(activity_id=activity_data.get('activity_id'), is_remind=True). \
                                                  values_list('user_id', flat=True)

    user_list = UserLastSign.objects.filter(activity_id=activity_data.get('activity_id'),
                                            newest_time__lt=datetime.date.today() + datetime.timedelta(days=-1),
                                            newest_time__gte=datetime.date.today() + datetime.timedelta(days=-2)) \
                                    .values('user_id', 'available_days')

    for user_info in user_list:
        if user_info.get('user_id') not in list(remind_users):
            continue
        for prize in activity_data.get('goods'):
            if user_info.get('available_days') >= prize.get('cost'):
                continue
            elif user_info.get('available_days') and prize.get('cost') and\
                    user_info.get('available_days') < prize.get('cost'):
                msg = u'您断签1天，还差{days}天可领{prize_name}，点我立即补签!'.\
                      format(prize_name=prize.get('short_name'), days=prize.get('cost')-user_info.get('available_days'))
                allocate_push_task_users(user_id=int(user_info.get('user_id')), alert=msg, extra=extra,
                                         push_type=AUTOMATED_PUSH.NEW_CHECK_IN_REMINDER)
                break


@shared_task
def sign_v2_push_broken_sign_user():
    """
    2019/07签到push改版  当天所有断签用户发布推送
    :return:
    """
    user_list = SignUserInfoV2.objects.filter(Q(newest_time__lt=datetime.date.today()) | Q(newest_time__isnull=True)).values_list('user_id', flat=True)

    url = 'gengmei://common_webview?url={}/phantom/new_sign_details'.format(
        settings.BACKEND_API_HOST)
    extra = {
        'type': PUSH_INFO_TYPE.GM_PROTOCOL,
        'msgType': 4,
        'pushUrl': url,
        'push_url': url,
    }
    if datetime.datetime.now().hour > 12:
        msg = u'下午好，休息一下吧！快来领取你的专属福利～'
    else:
        msg = u'上午好，签到的小仙女有大礼包领取哦～点击随意挑选~'

    user_ids, step = list(user_list), 128
    _u = [user_ids[i: i + step] for i in range(0, len(user_ids), step)]
    for user_ids in _u:
        allocate_push_task_users(user_id=list(user_ids), alert=msg, extra=extra,
                                 push_type=AUTOMATED_PUSH.NEW_CHECK_IN_REMINDER)


@shared_task
def has_express_push(user_id, express_no):
    """
    兑换奖品 运营填入运单号后push   以后备用
    :return:
    """
    if not user_id or not express_no:
        return

    url = 'gengmei://common_webview?url={}/phantom/sign_details?navigation_color_clear=1'.format(
        settings.BACKEND_API_HOST)

    extra = {
        'type': PUSH_INFO_TYPE.GM_PROTOCOL,
        'msgType': 4,
        'pushUrl': url,
        'push_url': url,
    }

    msg = u"您签到兑换的礼物已经发货了，运单编号：{express_no}".format(express_no=express_no)
    allocate_push_task_users(user_id=int(user_id), alert=msg, extra=extra,
                             push_type=AUTOMATED_PUSH.NEW_CHECK_IN_REMINDER)


@shared_task
def sign_v2_push_all_user():
    """
    2019/07签到push改版  全量用户推送
    :return:
    """

    url = 'gengmei://common_webview?url={}/phantom/new_sign_details?navigation_color_clear=1'.format(
        settings.BACKEND_API_HOST)
    extra = {
        'type': PUSH_INFO_TYPE.GM_PROTOCOL,
        'msgType': 4,
        'pushUrl': url,
        'push_url': url,
    }

    msg = u'叮～你有一份【口红、眼影、香水】大礼包待领取～快来点我签到'
    push_all_task(alert=msg, extra=extra)

#已上的废弃了


@shared_task
def sign_rush_prize(user_id, prize_id, is_check=True):
    """抢购兑换签到商品"""
    exchanged_record = SignUserExchangedPrize.objects.filter(user_id=user_id, prize_id=prize_id)
    for record in exchanged_record:
        if record.created_time.date() == datetime.date.today():
            return {}

    try:
        prize = SignBlindExchangePrize.objects.filter(id=prize_id).first()
        have_blind_box = SignUserBlindBox.objects.filter(user_id=user_id, blind_prize_id__in=prize.blind_box_list)
        for blind_box in have_blind_box:
            if blind_box.count <= 0:
                return
            blind_box.count -= 1
            blind_box.save()

        SignUserExchangedPrize.objects.create(user_id=user_id, prize_id=prize_id, check_adress=is_check)
    except:
        cache_data = {
            "user_id": user_id,
            "prize_id": prize_id,
            "is_check": is_check
        }
        rush_cache_prize = rush_cache_key + u"rush_prize"
        sign_rush_cache.rpush(rush_cache_prize, cache_data)


@shared_task
def verfy_rush_task():
    from api.view.sign_v2 import RushBuyHour
    if datetime.datetime.now().hour < RushBuyHour:
        return

    rush_cache_prize = rush_cache_key + u"rush_prize"
    handle_len = sign_rush_cache.llen(rush_cache_prize)
    if not handle_len:
        return

    cache_data = sign_rush_cache.lpop()
    cache_data = eval(cache_data)
    user_id, prize_id, is_check = cache_data.get("user_id"), cache_data.get("prize_id"), cache_data.get("is_check")
    try:
        prize = SignBlindExchangePrize.objects.filter(id=prize_id).first()
        have_blind_box = SignUserBlindBox.objects.filter(blind_prize_id__in=prize.blind_box_list)
        for blind_box in have_blind_box:
            blind_box.count -= 1
            blind_box.save()

        SignUserExchangedPrize.objects.create(user_id=user_id, prize_id=prize_id, check_adress=is_check)
    except:
        cache_data = {
            "user_id": user_id,
            "prize_id": prize_id,
            "is_check": is_check
        }
        rush_cache_prize = rush_cache_key + u"rush_prize"
        sign_rush_cache.rpush(rush_cache_prize, cache_data)


@shared_task
def sign_remind_push():
    sign_user_list = list(SignUserInfoV2.objects.filter(rush_remind=True).values_list("user_id", flat=True))
    url = 'gengmei://common_webview?url={}/phantom/new_sign_details'.format(
        settings.BACKEND_API_HOST)
    extra = {
        'type': PUSH_INFO_TYPE.GM_PROTOCOL,
        'msgType': 4,
        'pushUrl': url,
        'push_url': url,
    }

    msg = u'⏰签到兑奖五分钟倒计时🎁快来看看你能兑换什么奖品吧！'

    user_ids, step = list(sign_user_list), 128
    _u = [user_ids[i: i + step] for i in range(0, len(user_ids), step)]
    for user_ids in _u:
        allocate_push_task_users(user_id=list(user_ids), alert=msg, extra=extra,
                                 push_type=AUTOMATED_PUSH.NEW_CHECK_IN_RUSH_PRIZE)


@shared_task
def sign_pay_finish_task(settlement_id):
    from api.view.sign_v2 import task_limit_everyday
    limit_count, add_point = task_limit_everyday.get(str(SIGN_TASK_TYPE.PAY_ORDER))

    order_ids = list(SettlementItem.objects.filter(
        settlement_id=settlement_id).values_list('order_id', flat=True))

    if not order_ids:
        return

    order_id = order_ids[0]
    demo_order = Order.objects.filter(id=order_id).first()
    user_id = demo_order.user_id

    service_ids = list(Order.objects.filter(
        id__in=order_ids,
    ).values_list('service_id', flat=True))

    task_finish_count = SignTaskUserFinish.objects.filter(
        user_id=user_id, task_type=SIGN_TASK_TYPE.PAY_ORDER, finish_time=datetime.date.today()).count()
    if task_finish_count >= limit_count:
        return
    cached_key = u"sign_order_{user_id}".format(user_id=user_id)
    try:
        cached_special_ids = list(map(int, sign_task_cache.smembers(cached_key)))
    except:
        cached_special_ids = []

    for service_id in service_ids:
        special_ids = list(SpecialItem.objects.filter(
            service_id=service_id,
        ).values_list('special_id', flat=True))
        if not special_ids:
            continue
        finished_special_ids = set(cached_special_ids) & set(special_ids)
        try:
            sign = SignUserInfoV2.objects.get(user_id=user_id)
        except SignUserInfoV2.DoesNotExist:
            return

        if finished_special_ids:
            sign.points_count += add_point
            sign.show_point += add_point
            sign.save()
            SignTaskUserFinish.objects.create(
                user_id=user_id, task_type=SIGN_TASK_TYPE.PAY_ORDER, task_value=finished_special_ids.pop()
            )


@shared_task
def sign_xcx_push():
    from api.util.user_util import get_open_id_by_user_id
    from api.util.wechat_util import get_wechat_access_token
    from utils.wechat_applet_tools import applet_template_push
    from api.models.sign_v2 import SignUserInfoV2
    from django.conf import settings
    records = SignUserInfoV2.objects.filter(rush_remind=True)
    if not records:
        return
    template_id = settings.SIGN_PUSH_TEMPLATE_ID
    access_token = get_wechat_access_token()
    for record in records:
        if not record.xcx_form_id:
            continue
        data = {
            "keyword1": {
                "value": u'活动名称：更美签到抽盲盒活动'
            },
            "keyword2": {
                "value": u"活动起始时间：10月18日"
            },
            "keyword3": {
                "value": u"活动奖励：LV包包、Lamer面霜、NARS口红、ins风化妆包等等～"
            },
            "keyword4": {
                "value": u"完成条件：集齐该奖品所需盲盒娃娃"
            },
        }
        open_id = get_open_id_by_user_id(record.user_id)
        if not open_id:
            continue
        applet_template_push(
            access_token,
            open_id,
            template_id,
            record.xcx_form_id,
            data=data,
            page=u"packageActivity/pages/user/sign/main"
        )
        record.xcx_form_id = ""
        record.save()


def get_prize_name():
    prize_list = SignBlindExchangePrize.objects.filter(is_online=True)

    final_prize_name, prize_name = u"", u""
    for prize in prize_list:
        is_final = False
        for card_id in prize.blind_box_list:
            card = SignBlindBox.objects.filter(id=int(card_id)).first()
            if not card:
                continue
            if card.is_final:
                is_final = True

        if is_final:
            final_prize_name = prize.name
            break

    prize_list = SignPrizeV3.objects.filter(is_online=True).order_by("exchange_days")
    for prize in prize_list:
        prize_name += u"【{prize_name}】".format(prize_name=prize.name
                                               )
    return prize_name, u"【{prize_name}】".format(prize_name=final_prize_name)


def push_user(user_list, msg, eta=None):
    url = 'gengmei://common_webview?url={}/phantom/new_sign_details'.format(
        settings.BACKEND_API_HOST)
    extra = {
        'type': PUSH_INFO_TYPE.GM_PROTOCOL,
        'msgType': 4,
        'pushUrl': url,
        'push_url': url,
    }

    user_ids, step = list(user_list), 128
    _u = [user_ids[i: i + step] for i in range(0, len(user_ids), step)]
    for user_ids in _u:
        allocate_push_task_users(user_id=list(user_ids), alert=msg, extra=extra, eta=eta,
                                 push_type=AUTOMATED_PUSH.NEW_CHECK_IN_REMINDER, others={"title": u"【签到提醒】",
                                                                                         "alert": msg})


@shared_task
def push_sign_user():
    # 获取最小的那个奖品
    first_prize = SignPrizeV3.objects.filter(is_online=True).order_by("exchange_days").first()
    first_name = first_prize.name if first_prize else u""

    prize_name, final_prize_name = get_prize_name()
    time_slot = u"up" if datetime.datetime.today().hour < 12 else u"down"
    yestday_date = datetime.date.today() + datetime.timedelta(days=-1)
    # 断签1-3天
    break_date = datetime.date.today() + datetime.timedelta(days=-4)
    sign_user_list = list(
        SignUserInfoV2.objects.filter(newest_time__lt=yestday_date, newest_time__gte=break_date).values_list("user_id", flat=True))
    msg = break_one_day_up if time_slot == u"up" else break_one_day_down
    msg = msg.format(prize_name=prize_name)
    push_user(user_list=sign_user_list, msg=msg)
    # 断签3天+
    break_days = [5, 8, 10]
    for break_day in break_days:
        break_date = datetime.date.today() + datetime.timedelta(days=-(break_day + 1))
        sign_user_list = list(
            SignUserInfoV2.objects.using(settings.SLAVE_DB_NAME).filter(newest_time=break_date).values_list("user_id", flat=True))
        msg = u"" if time_slot == u"up" else break_more_day_down
        if not msg:
            continue
        msg = msg.format(prize_name=first_name)
        push_user(user_list=sign_user_list, msg=msg)


@shared_task
def sign_push_to_step_users(start_user_id, end_user_id, sign_user_list):
    prize_name, final_prize_name = get_prize_name()
    Saturday, Sunday = 5, 6
    time_slot = u"up" if datetime.datetime.today().hour < 12 else u"down"
    todat_date = datetime.datetime.today()

    def get_msg():
        if todat_date.weekday() in [Saturday, Sunday]:
            msg = sign_sunday_push_up_v2 if time_slot == u"up" else sign_sunday_push_down_v2
            msg = msg.format(prize_name=prize_name)
            return msg

        msg = sign_new_push_up_v2 if time_slot == u"up" else sign_new_push_down_v2
        msg = msg.format(prize_name=prize_name)
        return msg

    push_msg = get_msg()
    while(True):
        user_ids = list(User.objects.using(settings.SLAVE_DB_NAME).filter(id__gt=start_user_id, id__lte=end_user_id).order_by("id")[:128].values_list("id", flat=True))
        if not user_ids:
            break

        push_user_ids = list(set(user_ids) - set(sign_user_list))
        expire_time = int((todat_date.replace(hour=0, minute=0, second=0) - todat_date).seconds)
        cache_lock = sign_task_cache.set(u"sign_push_{start_user_id}__{time_slot}".format(
                                                                               start_user_id=start_user_id,
                                                                               time_slot=time_slot), 1,
                                         nx=True, ex=expire_time)

        if not cache_lock:
            start_user_id = user_ids[-1]
            continue

        push_user(user_list=push_user_ids, msg=push_msg)
        start_user_id = user_ids[-1]


@shared_task
def sign_push_to_all_new_user():
    user_id = 0
    step = 100000

    sign_user_list = list(SignUserInfoV2.objects.using(settings.SLAVE_DB_NAME).all().values_list("user_id", flat=True))
    while(True):
        user_info = User.objects.using(settings.SLAVE_DB_NAME).filter(id__gt=user_id).order_by("id")[:step].aggregate(Max('id'))

        if not user_info.get("id__max"):
            break

        sign_push_to_step_users.delay(start_user_id=user_id, end_user_id=user_info.get("id__max"), sign_user_list=sign_user_list)
        user_id = user_info.get("id__max")


def get_msg_last(has_day, user_id, day):
    """
    连续签到获取文案
    :param day:
    :return:
    """
    from api.view.sign_v2 import handle_prize_exchange
    time_slot = u"up" if datetime.datetime.today().hour < 12 else u"down"
    msg = u""
    if not day:
        return msg

    prize_list = SignPrizeV3.objects.filter(is_online=True).order_by("exchange_days")
    max_days, days_prize, prize_days, days_prize_id = 0, {}, [], {}
    for prize in prize_list:
        prize_days.append(prize.exchange_days)
        max_days = max(max_days, prize.exchange_days)
        days_prize[str(prize.exchange_days)] = prize.name
        days_prize_id[str(prize.exchange_days)] = prize.id

    if len(prize_days) and day == prize_days[0]:
        prize_id = days_prize_id.get(str(prize_days[0]))
        prize_name = days_prize.get(str(prize_days[0]))
        exchange_status = handle_prize_exchange(user_id=user_id, prize_id=prize_id)
        if exchange_status == 1:
            msg = sign_msg_ten_up if time_slot == u"up" else sign_msg_ten_up
            msg = msg.format(has_day=has_day, prize_name_1=prize_name, day=prize_days[1] - prize_days[0],
                             prize_name_2=days_prize.get(str(prize_days[1])))

            return msg
        if exchange_status == 2:
            sign_msg_ten_exchanged_up_tmp = sign_msg_ten_exchanged_up.format(prize_name_1=prize_name,
                                                                             day=prize_days[1] - prize_days[0],
                                                                             prize_name_2=days_prize.get(str(prize_days[1])))
            sign_msg_ten_exchanged_down_tmp = sign_msg_ten_exchanged_down.format(has_day=has_day,
                                                                             day=prize_days[1] - prize_days[0],
                                                                             prize_name=prize_name)
            msg = sign_msg_ten_exchanged_up_tmp if time_slot == u"up" else sign_msg_ten_exchanged_down_tmp
            return msg

    if len(prize_days) > 1 and day == prize_days[1]:
        prize_id = days_prize_id.get(str(prize_days[1]))
        prize_name = days_prize.get(str(prize_days[1]))
        exchange_status = handle_prize_exchange(user_id=user_id, prize_id=prize_id)
        if exchange_status == 1:
            msg = sign_msg_twenty_up if time_slot == u"up" else sign_msg_twenty_down
            msg = msg.format(has_day=has_day, prize_name_1=prize_name, day=prize_days[2] - prize_days[1],
                             prize_name_2=days_prize.get(str(prize_days[2])))

            return msg
        if exchange_status == 2:
            sign_msg_twenty_exchanged_up_tmp = sign_msg_twenty_exchanged_up.format(prize_name_1=prize_name,
                                                                             day=prize_days[2] - prize_days[1],
                                                                             prize_name_2=days_prize.get(
                                                                                 str(prize_days[2])))
            sign_msg_twenty_exchanged_down_tmp = sign_msg_twenty_exchanged_down.format(has_day=has_day,
                                                                                 day=prize_days[2] - prize_days[1],
                                                                                 prize_name=days_prize.get(
                                                                                 str(prize_days[2])))
            msg = sign_msg_twenty_exchanged_up_tmp if time_slot == u"up" else sign_msg_twenty_exchanged_down_tmp
            return msg

    if len(prize_days) > 2 and day == prize_days[2]:
        prize_id = days_prize_id.get(str(prize_days[2]))
        prize_name = days_prize.get(str(prize_days[2]))
        exchange_status = handle_prize_exchange(user_id=user_id, prize_id=prize_id)
        if exchange_status == 1:
            msg = sign_msg_thirty_up_whole if time_slot == u"up" else sign_msg_thirty_down_whole
            msg = msg.format(has_day=has_day, prize_name=prize_name)

            return msg

        if exchange_status == 2:
            sign_msg_thirty_exchanged_up_tmp = sign_msg_thirty_exchanged_up.format(prize_name_1=prize_name,
                                                                                   day=prize_days[0],
                                                                                   prize_name_2=days_prize.get(str(prize_days[0])))
            sign_msg_thirty_exchanged_down_tmp = sign_msg_thirty_exchanged_down.format(has_day=has_day,
                                                                                       day=prize_days[0],
                                                                                       prize_name_2=days_prize.get(str(prize_days[0])))
            msg = sign_msg_thirty_exchanged_up_tmp if time_slot == u"up" else sign_msg_thirty_exchanged_down_tmp
            return msg

    if day == 1:
        msg = sign_msg_one_up if time_slot == u"up" else sign_msg_one_down
        dic_key = min([i for i in prize_days if i >=day])
        prize_name = days_prize.get(str(dic_key))
        msg = msg.format(prize_name=prize_name)
        return msg

    if day < min(prize_days):
        msg = sign_msg_first_up if time_slot == u"up" else sign_msg_first_down
        dic_key = min([i for i in prize_days if i >= day])
        prize_name = days_prize.get(str(dic_key))
        msg = msg.format(day=min(prize_days)-day, has_day=has_day, prize_name=prize_name)
        return msg

    if len(prize_days) > 1 and prize_days[0] < day < prize_days[1]:
        msg = sign_msg_second_up if time_slot == u"up" else sign_msg_second_down
        dic_key = prize_days[1]
        prize_name = days_prize.get(str(dic_key))
        msg = msg.format(day=prize_days[1] - day, has_day=has_day, prize_name=prize_name)
        return msg

    if len(prize_days) > 2 and prize_days[1] < day < prize_days[2]:
        msg = sign_msg_third_up if time_slot == u"up" else sign_msg_third_down
        dic_key = prize_days[2]
        prize_name = days_prize.get(str(dic_key))
        msg = msg.format(day=prize_days[2] - day, has_day=has_day, prize_name=prize_name)
        return msg

    if has_day > prize_days[-1]:
        msg = sign_msg_thirty_up if time_slot == u"up" else sign_msg_thirty_down
        return msg

    return u""


def get_msg_last_simple(has_day, prize_list):
    """
    连续签到获取文案
    :param has_day: 已经签到天数
    :param prize_list: 礼物列表
    :return:
    """
    turn = has_day % 30
    for prize in prize_list:
        exchange_days = prize.exchange_days
        left_days = exchange_days - turn
        if left_days > 0:
            prize_name = prize.name
            sign_msg_ten_exchanged_up = sign_msg_exchanged_up_new.format(day=left_days,
                                                                         prize_name=prize_name)
            return sign_msg_ten_exchanged_up
    return ''


@shared_task
def sign_push_to_good_user():
    newest_date_start = datetime.date.today() + datetime.timedelta(days=-3)
    newest_date_end = datetime.date.today()

    today = datetime.datetime.now().date()
    yesterday = today - datetime.timedelta(days=1)

    prize_list = SignPrizeV3.objects.filter(is_online=True).order_by("exchange_days")
    max_days, days_prize = 0, {}
    for prize in prize_list:
        max_days = max(max_days, prize.exchange_days)
        days_prize[str(prize.exchange_days)] = prize.name

    sign_user_list = SignUserInfoV2.objects.filter(newest_time__gt=newest_date_start, newest_time__lt=newest_date_end)
    for sign_user in sign_user_list:
        if sign_user.last_days > 0 and sign_user.newest_time not in [today, yesterday]:
            sign_user.last_days = 0

        msg = get_msg_last_simple(has_day=sign_user.last_days, prize_list=prize_list)
        info_logger.info("签到推送；用户id：%s， 文案：%s" % (str(sign_user.user_id), msg))
        if not msg:
            continue
        push_user(user_list=[sign_user.user_id], msg=msg)
