#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2019/5/20
import json
from celery import shared_task
from datetime import datetime
from hera.utils import get_mail_instance
from api.models import SpecialItem


def send_export_mail(subject, body, to_list, send=True):
    if not isinstance(to_list, (list, tuple)):
        to_list = [to_list]
    mail = get_mail_instance(subject, body, to_list)
    if send:
        mail.send()

    return mail


@shared_task
def update_price_info():
    _tmp, to_list = [], ['chenwei@igengmei.com']
    spi = SpecialItem.objects.filter(special__is_new_special=True, doctorseckillapply__isnull=False)

    info = {
        "total_counts": spi.count(),
        "fail_counts": 0,
        "fail_where": None,
    }

    for obj in spi:
        price_info = obj.get_price_info()
        active_price = int(price_info.get('gengmei_price', 0))
        pre_payment_price = int(price_info.get('pre_payment_price', 0))
        if active_price < pre_payment_price:
            print("active_price: %d, pre_payment_price: %d" % (active_price, pre_payment_price))
            obj.update_or_create_price_info()
            info['fail_counts'] += 1
            _tmp.append("special_id:{}-floor_id:{}-active_price:{}-pre_payment_price:{}".format(
                obj.special_id, obj.floor_id, active_price, pre_payment_price)
            )

    info['fail_where'] = _tmp
    info['date'] = datetime.now().strftime("%Y-%m-%H")
    body = '专题美购列表数据修复, 数据为: {}'.format(json.dumps(info))
    if info["fail_counts"]:
        send_export_mail('专题美购列表数据修复！', body, to_list)