"""rank.views.kaoheguan - auto-generated by split script."""
import json
import logging
from decimal import Decimal
from django.db import models, transaction
from django.db.models import F
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from ..utils import get_tag_fee, create_shenhe_jilu, validate_shenheguan
from ..models import (
    YonghuChenghao, Chenghao, KaoheCishuFeiyong, KaoheJujueJilu,
    KaoheguanBankuai, Bankuai, ShenheJilu, KaoheJiluFeiyong
)
from users.models import UserShenheguan, UserDashou
from users.business_models import User
from products.models import ShangpinLeixing




logger = logging.getLogger(__name__)


KAOHEGUAN_INVITE_CODE = 'KHG2026VIP'


class KaoheguanRegisterView(APIView):
    """
    考核官注册接口
    POST /dengji/khgzc
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            yonghu = request.user
            invite_code = request.data.get('inviteCode', '').strip()

            if not invite_code:
                return Response({'code': 400, 'msg': '邀请码不能为空'})
            if invite_code != KAOHEGUAN_INVITE_CODE:
                return Response({'code': 400, 'msg': '邀请码错误'})

            kg = UserShenheguan.objects.filter(user=yonghu).first()
            if kg:
                if kg.zhuangtai == 1:
                    return Response({'code': 200, 'msg': '您已是考核官', 'data': self._build_data(kg)})
                else:
                    return Response({'code': 400, 'msg': '账号已被封禁'})

            with transaction.atomic():
                kg = UserShenheguan.objects.create(
                    user=yonghu,
                    zhuangtai=1,
                    shenhe_zhuangtai=0,
                    shenhe_zongshu=0,
                    tongguo_zongshu=0,
                    yue=0.00,
                    zonge=0.00
                )
            return Response({'code': 200, 'msg': '注册成功', 'data': self._build_data(kg)})

        except Exception as e:
            logger.error(f"考核官注册失败: {e}", exc_info=True)
            return Response({'code': 500, 'msg': '服务器内部错误'})

    def _build_data(self, kg):
        bankuai_qs = KaoheguanBankuai.objects.filter(kaoheguan_id=kg.user.UserUID).select_related('bankuai')
        bankuai_list = [{'bankuai_id': b.bankuai.bankuai_id, 'mingcheng': b.bankuai.mingcheng} for b in bankuai_qs]
        return {
            'zhuangtai': kg.zhuangtai,
            'shenhe_zongshu': kg.shenhe_zongshu,
            'tongguo_zongshu': kg.tongguo_zongshu,
            'yue': str(kg.yue),
            'zonge': str(kg.zonge),
            'shenhe_zhuangtai': kg.shenhe_zhuangtai,
            'bankuai_list': bankuai_list,
            'kaoheguanstatus': 1
        }


class KaoheguanRefreshView(APIView):
    """
    考核官数据刷新接口
    POST /dengji/khgsx
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            yonghu = request.user
            kg = UserShenheguan.objects.filter(user=yonghu).first()
            if not kg:
                return Response({'code': 400, 'msg': '您还未注册考核官'})

            if kg.zhuangtai != 1:
                return Response({'code': 200, 'data': {'zhuangtai': kg.zhuangtai, 'kaoheguanstatus': 0}})

            # 查询所属板块
            bankuai_qs = KaoheguanBankuai.objects.filter(kaoheguan_id=kg.user.UserUID).select_related('bankuai')
            bankuai_list = [{'bankuai_id': b.bankuai.bankuai_id, 'mingcheng': b.bankuai.mingcheng} for b in bankuai_qs]

            # 统计待审核 / 审核中的记录数量
            pending_count = ShenheJilu.objects.filter(
                shenheguan_id=yonghu.UserUID,
                zhuangtai=0   # 审核中
            ).count()

            data = {
                'zhuangtai': kg.zhuangtai,
                'shenhe_zongshu': kg.shenhe_zongshu,
                'tongguo_zongshu': kg.tongguo_zongshu,
                'yue': str(kg.yue),
                'zonge': str(kg.zonge),
                'shenhe_zhuangtai': kg.shenhe_zhuangtai,
                'bankuai_list': bankuai_list,
                'kaoheguanstatus': 1,
                'is_renzheng': kg.is_renzheng,                 # 🆕 是否认证
                'pending_shenhe_count': pending_count           # 🆕 审核中数量
            }
            return Response({'code': 200, 'data': data})

        except Exception as e:
            logger.error(f"考核官刷新失败: {e}", exc_info=True)
            return Response({'code': 500, 'msg': '服务器内部错误'})


class KaoheFreeApplyView(APIView):
    """免费申请考核（首次/再次，费用为0时调用）"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            user = request.user
            tag_id = request.data.get('tag_id')
            game_nick = request.data.get('game_nick', '').strip()
            remark = request.data.get('remark', '').strip()
            reapply = request.data.get('reapply', False)
            jilu_id = request.data.get('jilu_id') if reapply else None
            shenheguan_id = request.data.get('shenheguan_id', '').strip()  # 新增

            if not tag_id or not game_nick:
                return Response({'code': 400, 'msg': '标签ID和游戏昵称必填'})

            # 校验费用是否为0
            try:
                chenghao = Chenghao.objects.get(id=tag_id)
            except Chenghao.DoesNotExist:
                return Response({'code': 400, 'msg': '标签不存在'})

            # 计算本次次数
            if reapply and jilu_id:
                last_record = ShenheJilu.objects.filter(
                    jilu_id=jilu_id, shenqingren_id=user.UserUID, zhuangtai=2
                ).first()
                if not last_record:
                    return Response({'code': 400, 'msg': '原记录不存在或状态不是未通过'})
                new_cishu = last_record.cishu + 1
            else:
                max_cishu = ShenheJilu.objects.filter(
                    shenqingren_id=user.UserUID, chenghao=chenghao, zhuangtai__in=[1,2]
                ).aggregate(max=models.Max('cishu'))['max'] or 0
                new_cishu = max_cishu + 1

            fee = get_tag_fee(chenghao, new_cishu)
            if fee > 0:
                return Response({'code': 400, 'msg': '您有未通过的记录请查看并重考'})

            # 新增：如果指定了考核官，进行合法性校验
            if shenheguan_id:
                valid, err = validate_shenheguan(shenheguan_id, chenghao.bankuai, fee, user)
                if not valid:
                    return Response({'code': 400, 'msg': err})

            # 调用公共创建逻辑
            success, msg, record = create_shenhe_jilu(
                user, tag_id, game_nick, remark, reapply, jilu_id,
                shenheguan_id=shenheguan_id   # 新增参数
            )
            if success:
                return Response({'code': 0, 'msg': msg, 'data': {'jilu_id': record.jilu_id}})
            else:
                return Response({'code': 400, 'msg': msg})
        except Exception as e:
            return Response({'code': 500, 'msg': str(e)}, status=500)
