from some_sdk.xingyun_sdk.session import get_logged_in_client
from some_sdk.xingyun_sdk.biz.by_user import get_user_order
from .wechat_sdk import get_external_group_chat_info
from app.models.weixin import WeixinUser

# 首次调用：登录并创建 client
client = get_logged_in_client()

def get_user_order_list(group_name: str="", keyword: str="", regrex: str=None, userIds: list = None):
    result = get_user_order(client, keyword=keyword, group_name=group_name, regrex=regrex, userIds=userIds)
    if not result:
        return {}

    order_list = result.pop("order_list", [])
    print(f'在群聊 {result["group_name"]} 中的客户 {result["name"]}({result["keyword"]}) 有订单数: {len(order_list)}')

    subTradeNo_list = []
    for order in order_list:
        result_order = dict(tradeNo='', tradeTime=order.get("tradeTime", ''), payTime=order.get("payTime", ''))
        orderList = order.get("orderList", [])

        for item in orderList:
            result_order['shopName'] = order.get("shopName", "")
            result_order['goodsName'] = item.get("goodsName", "")
            result_order['actuPayment'] = order.get("actuPayment", "")
            result_order['goodsCount'] = order.get("goodsCount", "")
            result_order['tradeNo'] = item.get("subTradeNo", "")
            result_order['pic'] = item.get("pic", "")
            result_order['other_status'] = order.get("orderStatus", 0)
            result_order['other_status_name'] = order.get("status_name", "")
            subTradeNo_list.append(result_order.copy())

    import json; print(json.dumps(subTradeNo_list, indent=4, ensure_ascii=False))
    result['order_list'] = subTradeNo_list
    return result

async def get_user_order_list_by_chatid(chat_id: str):
    group_chat_info = await get_external_group_chat_info(chat_id)
    external_member_list = group_chat_info.get('external_member_list', [])

    trade_list = []
    group_chat_info['trade_list'] = trade_list

    invitor = group_chat_info.get('owner')
    qiwei_kefu = await WeixinUser.filter(userid=invitor).first()
    print(f'邀请人：{invitor} {qiwei_kefu.username} {qiwei_kefu.crmid}')

    group_name = group_chat_info.get('name')
    # if not group_name:
    #     group_name = '未知群聊'

    print(f'群聊名称{group_name}，有{len(external_member_list)}位客户', flush=True)
    for user in external_member_list:
        print(f'正在处理客户：{user.get("name")}', flush=True)
        result = get_user_order_list(group_name=group_name, keyword=user.get('name'), userIds=[qiwei_kefu.crmid] if qiwei_kefu.crmid else None)
        if not result:
            continue

        trade_list.append(result)
    
    return group_chat_info

if __name__ == "__main__":
    get_user_order("fuyixuan0628-印刷vip客户服务群", "去看海吗")
    get_user_order("小旋honey-印刷vip客户服务群@喜印说", "宇宙大女神")

