# dengji/services.py
import logging
from django.db import transaction, IntegrityError
from django.utils import timezone
from .models import DashouBiaoxian


logger = logging.getLogger(__name__)

def record_dashou_biaoxian(dingdan_id, dashou_id, xingwei, **kwargs):
    """
    统一记录打手订单表现
    :param dingdan_id: 订单ID
    :param dashou_id: 打手ID
    :param xingwei: 行为类型 1-抢单 2-提交订单 3-结算
    :param kwargs: 可选字段(与模型字段同名):
        jiedan_time, tijiao_time,
        bankuai, shangxian_sudu, fuwu_taidu, fanche_cishu
    注意：不管是哪种行为，dingdan_id 和 dashou_id 都是必传的，
          如果没传时间且业务需要时间，则自动取当前时间。
    """
    try:
        # ----- 抢单：创建记录 -----
        if xingwei == 1:
            jiedan_time = kwargs.get('jiedan_time') or timezone.now()
            bankuai = kwargs.get('bankuai')  # 可为 None

            # 避免重复创建（同一订单只会有一条表现记录）
            obj, created = DashouBiaoxian.objects.get_or_create(
                dingdan_id=dingdan_id,
                dashou_id=dashou_id,
                defaults={
                    'bankuai': bankuai,
                    'jiedan_time': jiedan_time,
                }
            )
            if not created:
                logger.info(f"表现记录已存在，跳过创建: dingdan={dingdan_id}, dashou={dashou_id}")
            else:
                logger.info(f"创建抢单表现记录: dingdan={dingdan_id}, dashou={dashou_id}")

        # ----- 提交订单：更新提交时间 -----
        elif xingwei == 2:
            tijiao_time = kwargs.get('tijiao_time') or timezone.now()
            # 只更新已存在的记录，找不到就直接跳过
            updated = DashouBiaoxian.objects.filter(
                dingdan_id=dingdan_id,
                dashou_id=dashou_id
            ).update(tijiao_time=tijiao_time)
            if updated:
                logger.info(f"更新提交时间: dingdan={dingdan_id}, dashou={dashou_id}")
            else:
                logger.info(f"无对应记录，跳过提交时间更新: dingdan={dingdan_id}, dashou={dashou_id}")

        # ----- 结算：更新评价信息 -----
        elif xingwei == 3:
            # 构建要更新的字段，只更新 kwargs 中传入的非 None 字段
            update_fields = {}
            for field in ['shangxian_sudu', 'fuwu_taidu', 'fanche_cishu']:
                val = kwargs.get(field)
                if val is not None:
                    update_fields[field] = val
            # 如果还传了板块也可以更新
            bankuai = kwargs.get('bankuai')
            if bankuai is not None:
                update_fields['bankuai'] = bankuai

            if update_fields:
                updated = DashouBiaoxian.objects.filter(
                    dingdan_id=dingdan_id,
                    dashou_id=dashou_id
                ).update(**update_fields)
                if updated:
                    logger.info(f"更新评价信息: dingdan={dingdan_id}, dashou={dashou_id}, fields={update_fields}")
                else:
                    logger.info(f"无对应记录，跳过评价更新: dingdan={dingdan_id}, dashou={dashou_id}")
            else:
                logger.info(f"结算时未传入任何评价字段，跳过更新")

        else:
            logger.warning(f"未知的行为类型: {xingwei}")

    except IntegrityError as e:
        # 唯一约束冲突（get_or_create 理论上已处理，但并发时仍可能撞上）
        logger.warning(f"表现记录写入冲突，可能并发创建: {e}")
    except Exception as e:
        # 无论发生什么错误，都不影响主流程
        logger.error(f"记录打手表现异常: dingdan={dingdan_id}, dashou={dashou_id}, xingwei={xingwei}, error={e}", exc_info=True)