# coding=utf-8
from __future__ import absolute_import

from time import sleep

from celery import shared_task
from django.conf import settings

from api.models.settlement import Settlement
from api.models.settlement import SETTLEMENT_STATUS
from api.tool.settlement_tool import cancel_settlement
from gm_types.trade import SETTLEMENT_PAY_MODE
from gm_types.gaia import SETTLEMENT_CANCEL_REASON
from gm_types.push import PUSH_INFO_TYPE
from gm_types.push import AUTOMATED_PUSH
from api.tool.log_tool import logging_exception
from api.tasks.push_task import allocate_push_task_one

from rpc.all import get_rpc_remote_invoker
from rpc.tool.protocol import gm_protocol

@shared_task
def settlement_create_event(settlement_id):
    # 非分期 才有 软超时
    # 分期超时 1 day
    settlement = Settlement.objects.get(pk=settlement_id)

    settlement_soft_timeout_event.apply_async(
        args=(settlement_id,),
        countdown=settings.SETTLEMENT_SOFT_TIMEOUT
    )

    if settlement.pay_mode == SETTLEMENT_PAY_MODE.INSTALLMENT:
        countdown = settings.INSTALLMENT_HARD_TIMEOUT
    else:
        countdown = settings.SETTLEMENT_HARD_TIMEOUT

    settlement_hard_timeout_event.apply_async(
        args=(settlement_id,),
        countdown=countdown
    )

    settlement_pay_remind_event.apply_async(
        args=(settlement_id,),
        countdown=settings.SETTLEMENT_PAY_REMIND_COUNTDOWN
    )


@shared_task
def settlement_event_for_apollo(event_message):
    rpc_invoker = get_rpc_remote_invoker()

    retry_count = 0

    while retry_count < 3:
        try:
            rpc_invoker['apollo/gaia/proccess_event'](
                event_message=event_message
            ).unwrap()

            break
        except Exception as e:
            retry_count += 1
            print(e)
            logging_exception()
            sleep(retry_count * 2)


@shared_task
def settlement_soft_timeout_event(settlement_id):
    '''
    超时时判断是否正在付款，若正在付款则延长一倍时间
    '''
    settlement = Settlement.objects.get(pk=settlement_id)

    if settlement.status == SETTLEMENT_STATUS.NOT_PAID:
        cancel_settlement(settlement, SETTLEMENT_CANCEL_REASON.TIMEOUT)


@shared_task
def settlement_hard_timeout_event(settlement_id):
    '''
    超过最长超时时间后，只要尚未付款均强制取消掉
    '''
    settlement = Settlement.objects.get(pk=settlement_id)
    if settlement.status in [SETTLEMENT_STATUS.NOT_PAID, SETTLEMENT_STATUS.PAYING]:
        cancel_settlement(settlement, SETTLEMENT_CANCEL_REASON.TIMEOUT)


@shared_task
def settlement_pay_remind_event(settlement_id):
    settlement = Settlement.objects.get(pk=settlement_id)

    if settlement.status not in [SETTLEMENT_STATUS.PAID, SETTLEMENT_STATUS.CANCEL]:
        user_id = settlement.person.user_id

        pushurl = gm_protocol.get_order_list() + "?tab_type=1"
        extra = {
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'pushUrl': pushurl,
        }
        alert = u'您有一个订单未支付，剩下的时间不多了，好东西很抢手，快点去支付吧。'
        from api.tasks.push_task import automate_push_task
        automate_push_task(user_ids=[user_id], push_type=AUTOMATED_PUSH.PAYMENT_REMINDER, extra=extra, alert=alert)
