# coding: utf-8
import datetime

from celery import shared_task
from django.db import transaction
from gm_types.gaia import GROUPBUY_STATUS, ORDER_STATUS
from api.util.wechat_util import wechat_template_push
from api.manager.order_manager import apply_refund_order_by_user
from api.models import GroupBuyTeam, Order, GroupBuyTeamOrder,ServiceItem
from api.models import UserExtraWechatInfo
from rpc.tool.log_tool import info_logger


@shared_task
def system_op_groupbuy_fail_order_refund():
    # 先将拼团状态和订单的拼团状态改变成拼团失败， 再通过order ids 一个个进行退款
    now = datetime.datetime.now()
    find_time = now - datetime.timedelta(days=3)
    gbt_ids = GroupBuyTeam.objects.filter(
        end_time__gte=find_time, end_time__lte=now, status=GROUPBUY_STATUS.GROUPBUY_STARTED
    ).values_list('id', flat=True)

    for gbt_id in gbt_ids:
        with transaction.atomic():
            gbt = GroupBuyTeam.objects.select_for_update().get(id=gbt_id)
            if gbt.status != GROUPBUY_STATUS.GROUPBUY_STARTED:
                continue
            gbt.status = GROUPBUY_STATUS.GROUPBUY_FAIL
            gbt.save(update_fields=['status'])

            order_ids = GroupBuyTeamOrder.objects.filter(
                groupbuy_team_id=gbt.id
            ).values_list('order_id', flat=True)
            bulk_number = 10
            for start in range(0, len(order_ids), bulk_number):
                Order.objects.filter(
                    id__in=list(order_ids[start: start + bulk_number])
                ).update(groupbuy_status=GROUPBUY_STATUS.GROUPBUY_FAIL)

            need_refund_order_ids = GroupBuyTeamOrder.objects.filter(
                groupbuy_team_id=gbt.id, paid=True
            ).values_list('order_id', flat=True)
            for order_id in need_refund_order_ids:
                apply_refund_order_by_user(order_id, u"拼团失败, 自动退款")


@shared_task
def system_op_after_groupbuy_fail_order_refund():
    """处理拼团结束后， 用户才支付这部分的订单进行退款"""
    now = datetime.datetime.now()
    find_time = now - datetime.timedelta(days=3)
    order_ids = list(GroupBuyTeamOrder.objects.filter(
        groupbuy_team__end_time__gte=find_time,
        groupbuy_team__end_time__lte=now,
        groupbuy_team__status=GROUPBUY_STATUS.GROUPBUY_FAIL,
        paid=True
    ).values_list('order_id', flat=True))
    need_refund_order_ids = list(Order.objects.filter(
        id__in=order_ids, status=ORDER_STATUS.PAID
    ).values_list('id', flat=True))
    for order_id in need_refund_order_ids:
        apply_refund_order_by_user(order_id, u"拼团失败, 自动退款")
