from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone

from api_v1.utils.wecom_webhook import send_wecom_webhook_message
from business import models as business_models
from business.pre_order_services import render_pre_sales_order_created_markdown


class Command(BaseCommand):
    help = "发送预销售单创建通知到企业微信，并在控制台输出渲染后的消息内容"

    def add_arguments(self, parser):
        parser.add_argument("pre_sales_order_id", type=int, help="预销售单 ID")
        parser.add_argument("--key", type=str, default=None, help="可选：临时覆盖 settings.WECOM_WEBHOOK_KEY")
        parser.add_argument(
            "--timeout",
            type=float,
            default=10.0,
            help="HTTP 超时（秒）",
        )

    def handle(self, *args, **options):
        pre_sales_order_id = options["pre_sales_order_id"]
        key = options["key"]
        timeout = options["timeout"]

        try:
            order = (
                business_models.PreSalesOrder.objects.select_related(
                    "customer",
                    "warehouse",
                    "operator",
                    "created_by",
                )
                .get(id=pre_sales_order_id)
            )
        except business_models.PreSalesOrder.DoesNotExist as exc:
            raise CommandError(f"预销售单 {pre_sales_order_id} 不存在") from exc

        created_by = getattr(order, "created_by", None)
        operator = getattr(order, "operator", None)

        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 "系统自动发送"

        customer_name = getattr(getattr(order, "customer", None), "name", None) or "-"
        warehouse_name = getattr(getattr(order, "warehouse", None), "name", None) or "-"
        try:
            kind_label = getattr(order, "get_kind_display", lambda: None)() or None
        except Exception:
            kind_label = None

        items_count = order.items.count()

        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")
        )

        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),
            warehouse_name=str(warehouse_name),
            kind=str(kind_label or "-"),
            items_count=int(items_count or 0),
        )

        self.stdout.write("\n===== Rendered WeCom Markdown =====\n")
        self.stdout.write(message)
        self.stdout.write("\n===== End =====\n")

        try:
            resp = send_wecom_webhook_message(
                content=message,
                msgtype="markdown",
                key=key,
                timeout_seconds=timeout,
            )
        except Exception as exc:
            raise CommandError(str(exc)) from exc

        if not resp.ok:
            raise CommandError(f"WeCom webhook 返回失败：errcode={resp.errcode}, errmsg={resp.errmsg}, raw={resp.raw}")

        self.stdout.write(self.style.SUCCESS(f"OK: {resp.raw}"))
