"""LEKO 下号（UIN）source 流程 RPA · step3 保存成功后的企业微信通知。

与 `rpa_leko_step1_search_error_sendmsg.py`（错误通知）对应：step3 回写
`EPRRegInfo.RegBackNumber` + `PushTaxBureauStatus=4` 成功后，向企业微信群
发送成功提醒（含流水号 / 公司名 / 注册码，可 @ 指定成员）。

API 流程（`/api/epr/leko-rpa/result`）不需要本脚本：回执由服务端落库并
调用 SaaS 统一异步通知（契约 §13）。

自包含约束：禁止 import 其它 rpa 脚本。
"""

import json

import requests

# 企业微信群消息发送配置（与 rpa_leko_step1_search_error_sendmsg.py 为同一 webhook）。
# ⚠️ 该 key 已进入 git 历史：建议在企业微信侧轮换后，改为从环境变量/配置注入，避免继续硬编码。
WECHAT_WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6b1d20eb-28ec-40b6-8ce5-ae91a11af1f4"


def send_uin_success_message(
    serial_no: str,
    company_name: str,
    reg_back_number: str,
    mentioned_mobile: str = None,
) -> bool:
    """发送下号成功通知。

    :param serial_no: 业务流水号
    :param company_name: 公司名
    :param reg_back_number: 注册码（RegBackNumber）
    :param mentioned_mobile: 需要@的成员手机号，如 "138xxxx1234"
    :return: 是否发送成功
    """
    message = f"{serial_no} {company_name} 下号成功，注册码 {reg_back_number}"

    payload = {
        "msgtype": "text",
        "text": {
            "content": message,
            "mentioned_mobile_list": [mentioned_mobile] if mentioned_mobile else []
        }
    }

    try:
        response = requests.post(
            WECHAT_WEBHOOK_URL,
            data=json.dumps(payload),
            headers={"Content-Type": "application/json"}
        )
        result = response.json()

        if result.get("errcode") == 0:
            print(f"消息发送成功: {message}")
            return True
        else:
            print(f"消息发送失败: {result}")
            return False

    except Exception as e:
        print(f"发送异常: {e}")
        return False
