#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2019/8/21

from celery import shared_task
from hera.utils import get_mail_instance
from api.models import CashBackOrder, Order
from api.models.types import NEW_CASH_BACK_STATUS, CASH_BACK_STATUS


@shared_task
def alert_cash_back_status():
    """
    定期检查返现单状态
    :return:
    """
    wait_sync_cashback_order_ids = CashBackOrder.objects.filter(
        status=NEW_CASH_BACK_STATUS.WAIT, order__cash_back_status=CASH_BACK_STATUS.APPLY
    ).values_list('order_id', flat=True)
    total = wait_sync_cashback_order_ids.count()

    print("total cashback_order_ids: {nums}".format(nums=total))

    failed_order_ids_str = ""

    for order_id in wait_sync_cashback_order_ids:
        try:
            order = Order.objects.get(id=order_id)
            order.cash_back_status = CASH_BACK_STATUS.WAIT
            order.save()
        except Order.DoesNotExist:
            failed_order_ids_str += str(order_id)
            print("order_id: {order_id}, does not exist".format(order_id=order_id))
            continue

    message = u'同步总计:{nums}, 失败订单: {failed_order_ids}'.format(
        nums=total, failed_order_ids=failed_order_ids_str)

    if failed_order_ids_str:
        get_mail_instance(u"返现单状态同步提醒", message, ['chenwei@igengmei.com']).send()
