from app.core.crud import CRUDBase
from app.schemas.msg import (
    ActionCreate,
    ActionUpdate,
)
from app.models.automation import Action, ActionType
from app.models.weixin import WeixinCustomer, CustomerGroup, WeixinGroupChat, WeixinUser
from some_sdk.lintao_sdk.biz.by_order import get_order_relative_user
from some_sdk.services.binder import lintao_client
from app.controllers.weixin.customer import weixin_customer_controller
from datetime import datetime

import logging
logger = logging.getLogger(__name__)

class ActionController(CRUDBase[Action, ActionCreate, ActionUpdate]):
    def __init__(self):
        super().__init__(model=Action)

    async def new_action(self, type: ActionType, user, done=False, **kwargs):
        action = ActionCreate(userid=user.userid, username=f'{user.username}({user.english_name})', done=done, type=type, detail=kwargs)
        return await self.create(action)
    
    async def check_create_group_action_is_done(self, group_info, shop_name: str = None):
        name = group_info.get('name')
        chat_id = group_info.get('chat_id')

        # 完成建群操作
        create_group_action = await self.model.filter(type=ActionType.CREATE_GROUP, done=False, detail__contains={"group_name": name}).order_by('-id').first()
        if not create_group_action: return 

        create_group_action_detail = create_group_action.detail
        create_group_action_detail.update({
            "chat_id": chat_id,
        })

        create_group_action.done = True
        create_group_action.done_at = datetime.now()
        create_group_action.result = group_info
        create_group_action.detail = create_group_action_detail
        await create_group_action.save()

        # 完成建群操作后，将群成员添加到客户群中
        weixin_group = await WeixinGroupChat.filter(chat_id=chat_id).first()
        if not weixin_group: return

        staff = await WeixinUser.filter(userid=create_group_action.userid).first()

        external_user_ids = create_group_action.detail.get('external_user_ids') or []
        for userid in external_user_ids:
            customer = await WeixinCustomer.filter(weixin_id=userid).first()
            if not customer: continue

            membership = await CustomerGroup.create(
                staff_userid=create_group_action.userid,
                customer_userid=customer.weixin_id,
                group_chatid=chat_id,
                staff=staff,
                customer=customer,
                group=weixin_group,
                shop_name=shop_name,
                order_id=create_group_action.detail.get('order_id'),
                join_time=create_group_action.created_at,
            )
            logger.info(f'【建群成功】保存客户的群聊 {name}({chat_id}) 信息')
    
    async def check_remark_action_is_done(self):
        actions = await self.model.filter(done=False, type=ActionType.WRITE_REMARK)
        logger.info(f'检查备注操作是否完成，监控列表中：共有{len(actions)}条')

        update_list = []
        for action in actions:
            action_info = action.detail
            order_id = action_info.get("order_id")
            remark = action_info.get("remark")
            if not order_id: continue
            
            done = False
            action_result = []

            if remark:
                async for order in get_order_relative_user(lintao_client, trade_no=order_id):

                    try:
                        await weixin_customer_controller.remark_order(order, remark=remark)
                        if order.get('title'):
                            logger.info(f'【监控列表中，订单被领单】重新为订单 {order.get("trade_no")} 打上备注 {remark}')
                            # 未领单的订单，需要添加到监控列表中进行监控，防止被刷掉
                            done = True
                            action_result.append({
                                "trade_no": order.get("trade_no"),
                                "title": order.get("title"),
                                "remark": remark,
                            })
                    except Exception as e:
                        logger.exception(f'【监控列表中，订单被领单】重新为订单为订单 {order.get("trade_no")} 打上备注 {remark} 失败，异常: {e}')

            if done or not remark:
                action.done = True
                action.done_at = datetime.now()
                action.result = action_result
                update_list.append(action)

        if update_list:
            await self.model.bulk_update(update_list, fields=['done', 'result', 'done_at'])
                

action_controller = ActionController()

