import logging

from django.conf import settings
from django.db import transaction
from django.utils import timezone

logger = logging.getLogger(__name__)


def on_pre_sales_order_created(sender, **kwargs):
    """Handle PreSalesOrder created domain event.

    - 在事务提交后发送企业微信机器人通知（markdown）
    - 测试环境默认跳过，避免单测出网/刷屏
    """

    if not getattr(settings, "PRE_SALES_ORDER_CREATED_WECOM_NOTIFY_ENABLED", True):
        return
    if getattr(settings, "TESTING", False):
        return

    order = kwargs.get('instance')
    created_by = kwargs.get('created_by')
    operator = kwargs.get('operator')
    items_count = kwargs.get('items_count')

    if order is None:
        logger.warning('[business.handlers] pre_sales_order_created 缺少 instance，已跳过')
        return

    try:
        from .pre_order_services import render_pre_sales_order_created_markdown

        created_at_dt = getattr(order, 'created_at', None)
        created_at = (
            timezone.localtime(created_at_dt).strftime('%Y-%m-%d %H:%M:%S')
            if created_at_dt is not None
            else timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M:%S')
        )

        operator_label = getattr(operator, 'name', None) if operator else None

        emp = getattr(created_by, 'employee', None) if created_by else None
        created_by_employee_name = getattr(emp, 'name', None) if emp is not None else None
        created_by_username = getattr(created_by, 'username', None) if created_by else None
        sender_label = operator_label or created_by_employee_name or created_by_username or '系统自动发送'

        try:
            customer_name = getattr(getattr(order, 'customer', None), 'name', None)
        except Exception:
            customer_name = None

        try:
            warehouse_name = getattr(getattr(order, 'warehouse', None), 'name', None)
        except Exception:
            warehouse_name = None

        try:
            kind_label = getattr(order, 'get_kind_display', lambda: None)() or None
        except Exception:
            kind_label = None

        resolved_items_count = items_count
        if resolved_items_count is None:
            try:
                resolved_items_count = int(getattr(order, 'items', []).count())
            except Exception:
                resolved_items_count = 0

        message = render_pre_sales_order_created_markdown(
            pre_sales_order_id=str(getattr(order, 'id', '-') or '-'),
            human_id=str(getattr(order, 'human_id', '-') or '-'),
            created_at=str(created_at),
            sender_label=str(sender_label),
            customer_name=str(customer_name or '-'),
            warehouse_name=str(warehouse_name or '-'),
            kind=str(kind_label or '-'),
            items_count=int(resolved_items_count or 0),
        )
    except Exception:
        logger.exception('[business.handlers] 渲染企业微信消息失败，跳过通知')
        return

    def _send_wecom():
        try:
            from api_v1.utils.wecom_webhook import send_wecom_webhook_message

            resp = send_wecom_webhook_message(content=message, msgtype='markdown')
            if not resp.ok:
                logger.warning(
                    '[business.handlers] WeCom webhook 返回失败：errcode=%s, errmsg=%s, raw=%s',
                    resp.errcode,
                    resp.errmsg,
                    resp.raw,
                )
        except Exception:
            logger.exception('[business.handlers] 发送 WeCom webhook 失败（已忽略，不影响主流程）')

    # 在事务提交后再发送，避免事务回滚但通知已发出
    transaction.on_commit(_send_wecom)
