# app/api/wechat.py
from fastapi import APIRouter, Depends
from app.controllers.msg import msg_controller
from app.controllers.weixin.customer import weixin_customer_controller
from app.schemas.msg import MsgNewOrder, MsgFilter, MsgUpdate
from app.http_base import unified_resp
from app.schemas.apis import Paginate
from tortoise.expressions import Q
from ..weixin.base import get_weixin_user

import logging
logger = logging.getLogger(__name__)

router = APIRouter(prefix='/msg')

# 群聊入口
@router.post("/new_order", summary="通过群ID获取到群信息以及同步数据到本地")
@unified_resp
async def create_new_order(msg: MsgNewOrder):

    if msg.buyer_id.startswith('*******'):
        return {"msg": "不支持的客户类型"}
    
    if msg.buyer_nick:
        weixin_customer = await weixin_customer_controller.model.filter(taobao_name=msg.buyer_nick).first()
    elif msg.buyer_id:
        weixin_customer = await weixin_customer_controller.model.filter(weixin_id=msg.buyer_id).first()
    else:
        return {"msg": "buyer_id or buyer_nick is required"}
    
    if not weixin_customer:
        return {"msg": "当前客户未绑定微信账号"}
    
    logger.info(f'用户新订单: {msg}')

    order_id = msg.order_id

    await msg_controller.new_order(order_id, weixin_customer, is_refund=msg.is_refund)
    await msg_controller.sync_msg()
    return {"msg": "success"}


@router.get("/fill_customer_info", summary="填充客户信息")
@unified_resp
async def fill_customer_info():
    await msg_controller.fill_customer_info()
    return {"msg": "success"}

@router.get("/list", summary="通过群ID获取到群信息以及同步数据到本地")
@unified_resp
async def list_msg(paginate: Paginate = Depends(), order: str = "-id", msg_filter: MsgFilter = Depends(), weixin_user: dict = Depends(get_weixin_user)):
    print('paginate', paginate.page, paginate.page_size)
    print('msg_filter', msg_filter)
    print('weixin_user', weixin_user.username, weixin_user.userid)
    # q = Q(owner_id='11')
    q = Q(owner_id=weixin_user.userid)
    if msg_filter.type is not None:
        q &= Q(type=msg_filter.type)
    if msg_filter.is_read is not None:
        q &= Q(is_read=msg_filter.is_read)
        if msg_filter.is_read:
            order = '-read_at'
        
    if msg_filter.is_refund is not None:
        q &= Q(detail__contains={"is_refund": 1 if msg_filter.is_refund else 0})
    
    total, msg_list = await msg_controller.list(paginate.page, paginate.page_size, order=[order], search=q)
    return {"count": total, "lists": [ await msg.to_dict() for msg in msg_list]}

@router.post("/set_read", summary="设置消息为已读")
@unified_resp
async def set_read(msg: MsgUpdate, weixin_user: dict = Depends(get_weixin_user)):
    await msg_controller.set_read(msg.id)
    return {"msg": "success"}

@router.get("/get_order_user_days_before", summary="获取指定天数前的订单用户")
@unified_resp
async def get_order_user_days_before():
    return await msg_controller.get_order_user_days_before(2)

