# -*- coding: UTF-8 -*-

from rpc.tool.error_code import CODES, gen
from api.models import Order, ORDER_STATUS, TAG_TYPE
from django.conf import settings

from django.core.mail import EmailMessage, get_connection

connection = get_connection(
    username=settings.HERA_EMAIL_USER,
    password=settings.HERA_EMAIL_PSWD,
)


def get_seckill_order_total(service):
    status_set = [
        ORDER_STATUS.NOT_PAID,
        ORDER_STATUS.PAID,
        ORDER_STATUS.USED,
        ORDER_STATUS.SETTLED,
        ORDER_STATUS.AUDITING,
        ORDER_STATUS.SETTLING,
    ]
    # 已下单的秒杀订单量
    order_total = Order.objects.filter(
        service=service,
        created_time__range=[service.seckill_start_time, service.seckill_end_time],
        status__in=status_set,
    ).count()
    return order_total or 0


def check_tags_type_for_relate(parent, child):
    """检查两个tag的类型是否能产生关联

    关联条件:
    1. 两个都是项目tag，只能上下级关联
    2. 一个项目tag，一个自由添加，自由添加只能作为项目tag的父
    3. 其余tag不能产生关联
    """
    item_types = [TAG_TYPE.BODY_PART, TAG_TYPE.BODY_PART_SUB_ITEM, TAG_TYPE.ITEM_WIKI]
    parent_tag_type = parent.tag_type
    child_tag_type = child.tag_type
    if parent_tag_type in item_types and child_tag_type in item_types:
        if (parent_tag_type == TAG_TYPE.BODY_PART and child_tag_type == TAG_TYPE.BODY_PART_SUB_ITEM) or \
                (parent_tag_type == TAG_TYPE.BODY_PART_SUB_ITEM and child_tag_type == TAG_TYPE.ITEM_WIKI):
            return True
        else:
            # 项目tag非上下级，不能产生关联
            raise gen(CODES.TAG_CAN_NOT_RELATE, parent_id=parent.id, child_id=child.id)
    elif parent_tag_type == TAG_TYPE.FREE and child_tag_type in item_types:
        # 自由添加可以作为项目tag的父
        return True
    else:
        # 不能产生关联
        raise gen(CODES.TAG_CAN_NOT_RELATE, parent_id=parent.id, child_id=child.id)


def send_email(to_email_list, title, body):
    mail = EmailMessage(connection=connection)
    mail.from_email = settings.HERA_EMAIL_USER
    mail.subject = title
    mail.to = to_email_list
    mail.body = body
    mail.send()