import json
import jingrow
from wechatpayv3 import WeChatPay, WeChatPayType

class WeChatPayAPI:
    def __init__(self):
        # 从 Jcloud Settings 获取配置
        settings = jingrow.get_single("Jcloud Settings")
        
        # 存储支付回调URL
        self.notify_url = settings.wechatpay_notify_url
        
        # 微信支付参数
        self.mchid = settings.wechatpay_mchid
        self.private_key = self.load_key('/home/jingrow/jingrow-bench/apps/jcloud/jcloud/api/payment/apiclient_key.pem')
        self.cert_serial_no = settings.wechatpay_cert_serial_no
        self.apiv3_key = settings.wechatpay_apiv3_key
        self.appid = settings.wechatpay_appid
        
        # 加载微信支付平台公钥
        self.public_key = self.load_key('/home/jingrow/jingrow-bench/apps/jcloud/jcloud/api/payment/wechatpay_public_key.pem')
        self.public_key_id = settings.wechatpay_public_key_id
        # 配置选项，直接定义默认值
        self.partner_mode = False  # 默认直连商户模式
        self.proxy = None  # 默认无代理
        self.timeout = (1, 2)  # 设置连接超时为10秒，读取超时为30秒

        # 日志记录器
        self.logger = jingrow.logger("wechatpay", file_count=5)

        # 初始化微信支付
        self.wxpay = WeChatPay(
            wechatpay_type=WeChatPayType.NATIVE,
            mchid=self.mchid,
            private_key=self.private_key,
            cert_serial_no=self.cert_serial_no,
            apiv3_key=self.apiv3_key,
            appid=self.appid,
            notify_url=self.notify_url,
            logger=self.logger,
            partner_mode=self.partner_mode,
            proxy=self.proxy,
            timeout=self.timeout,
            public_key=self.public_key,
            public_key_id=self.public_key_id
        )

    def load_key(self, filename):
        with open(filename, 'r') as f:
            return f.read()

    def generate_payment_url(self, order_id, amount, subject, team_name, notify_url=None):
        # 使用传入的通知URL或默认的通知URL
        callback_url = notify_url or self.notify_url
        
        try:
            code, message = self.wxpay.pay(
                description=subject,
                out_trade_no=order_id,
                amount={'total': int(round(float(amount) * 100))},
                pay_type=WeChatPayType.NATIVE,
                attach=str(team_name)
            )
            if code in range(200, 300):
                result = json.loads(message)
                return result.get('code_url')                 
        except Exception as e:
            jingrow.throw(f"微信支付URL生成失败: {str(e)}")
