#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
查询订单模块
"""

import json
import asyncio
from .api import YsmPayApi

async def query_order(appid, mch_orderid=None, ysm_orderid=None):
    """
    查询订单状态（异步）
    
    Args:
        appid: 支付通道ID
        mch_orderid: 商户订单号（与ysm_orderid二选一）
        ysm_orderid: 易收米订单号（与mch_orderid二选一）
        
    Returns:
        dict: 订单信息字典，包含状态等信息
              SUCCESS：支付成功
              REFUND：转入退款
              NOTPAY：未支付
              CLOSED：已关闭
    """
    # 检查参数
    if not mch_orderid and not ysm_orderid:
        raise ValueError("商户订单号和易收米订单号必须提供一个")
    
    # 构造请求数据
    data = {'appid': appid}
    
    if mch_orderid:
        data['mch_orderid'] = mch_orderid
    elif ysm_orderid:
        data['ysm_orderid'] = ysm_orderid
    
    # 请求URL
    url = 'https://www.yishoumi.cn/u/query'  # 订单查询网关
    
    try:
        # 发起请求
        response = await YsmPayApi.http_post(url, json.dumps(data))
        
        # 解析响应
        result = json.loads(response) if response else None
        
        if not result:
            raise Exception('服务器错误:' + str(response), 500)
        
        return result
    except Exception as e:
        print(f"错误码:{getattr(e, 'code', 0)}, 错误信息:{str(e)}")
        return None

async def main():
    # 示例使用
    appid = '20********'  # 支付通道ID
    
    # 查询订单
    order_info = await query_order(
        appid=appid,
        mch_orderid='20230510505610',  # 商户订单号
    )
    
    if order_info:
        print(f"订单信息: {json.dumps(order_info, ensure_ascii=False, indent=2)}")
    else:
        print("查询订单失败")

if __name__ == "__main__":
    asyncio.run(main()) 