from django.db import models
from gvsdsdk.model_base import QModel


# ==================== 1. 角色表 ====================
class Role(QModel):
    """角色表"""
    role_id = models.AutoField(primary_key=True, verbose_name='角色ID')
    role_code = models.CharField(max_length=50, unique=True, db_index=True, verbose_name='角色编码')
    role_name = models.CharField(max_length=50, verbose_name='角色名称')
    description = models.CharField(max_length=200, blank=True, default='', verbose_name='角色描述')

    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'role'
        verbose_name = '角色'
        verbose_name_plural = '角色'
        managed = True
        indexes = [
            models.Index(fields=['role_code']),
        ]

    def __str__(self):
        return self.role_name


# ==================== 2. 权限表 ====================
class Permission(QModel):
    """权限表"""
    perm_id = models.AutoField(primary_key=True, verbose_name='权限ID')
    perm_code = models.CharField(max_length=100, unique=True, db_index=True, verbose_name='权限编码')
    perm_name = models.CharField(max_length=100, verbose_name='权限名称')
    description = models.CharField(max_length=200, blank=True, default='', verbose_name='权限描述')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'permission'
        verbose_name = '权限'
        verbose_name_plural = '权限'
        managed = True
        indexes = [
            models.Index(fields=['perm_code']),
        ]

    def __str__(self):
        return f"{self.perm_name} ({self.perm_code})"


# ==================== 3. 角色-权限关联表 ====================
class RolePermission(QModel):
    """角色权限关联表"""
    id = models.AutoField(primary_key=True)
    role = models.ForeignKey(Role, on_delete=models.CASCADE, db_index=True, verbose_name='角色')
    permission = models.ForeignKey(Permission, on_delete=models.CASCADE, db_index=True, verbose_name='权限')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'role_permission'
        verbose_name = '角色权限关联'
        verbose_name_plural = '角色权限关联'
        managed = True
        unique_together = [['role', 'permission']]

    def __str__(self):
        return f"{self.role.role_name} -> {self.permission.perm_name}"


# ==================== 4. 用户-角色关联表 ====================
class UserRole(QModel):
    """用户角色关联表"""
    id = models.AutoField(primary_key=True)
    account_id = models.CharField(max_length=11, db_index=True, verbose_name='账号ID')
    role = models.ForeignKey(Role, on_delete=models.CASCADE, db_index=True, verbose_name='角色')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'user_role'
        verbose_name = '用户角色关联'
        verbose_name_plural = '用户角色关联'
        managed = True
        unique_together = [['account_id', 'role']]

    def __str__(self):
        return f"{self.account_id} -> {self.role.role_name}"


# ==================== 5. 异常用户日志 ====================
class AbnormalUserLog(QModel):
    """记录恶意尝试越权操作的用户信息"""
    account_id = models.CharField(max_length=20, db_index=True, verbose_name='账号ID（phone）')
    ip_address = models.GenericIPAddressField(null=True, blank=True, verbose_name='IP地址')
    real_ip = models.GenericIPAddressField(null=True, blank=True, verbose_name='真实IP（穿透代理后）')
    x_forwarded_for = models.CharField(max_length=255, blank=True, default='', verbose_name='X-Forwarded-For')
    user_agent = models.CharField(max_length=500, blank=True, default='', verbose_name='User-Agent')
    request_method = models.CharField(max_length=10, blank=True, default='', verbose_name='请求方法')
    request_path = models.CharField(max_length=500, blank=True, default='', verbose_name='请求路径')
    request_params = models.TextField(blank=True, default='', verbose_name='请求参数（GET/POST）')
    request_body = models.TextField(blank=True, default='', verbose_name='请求体（原始）')
    request_headers = models.TextField(blank=True, default='', verbose_name='请求头（JSON格式）')
    attempt_type = models.CharField(max_length=50, blank=True, default='', verbose_name='攻击类型')
    detail = models.TextField(blank=True, default='', verbose_name='详细描述')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'abnormal_user_log'
        verbose_name = '异常用户日志'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['account_id']),
            models.Index(fields=['ip_address']),
            models.Index(fields=['CreateTime']),
        ]

    def __str__(self):
        return f"{self.account_id} @ {self.ip_address} - {self.CreateTime}"


# ==================== 6. 商家每日统计 ====================
class MerchantDailyStats(QModel):
    """商家每日统计表（原 ShangjiaRiTongji）"""
    club_id = models.CharField(max_length=16, default='xq', db_index=True, verbose_name='俱乐部ID')
    MerchantID = models.CharField(
        max_length=7, db_index=True, db_column='yonghuid', verbose_name='商家用户ID')
    Date = models.DateField(
        db_index=True, db_column='riqi', verbose_name='日期')

    # 派发统计
    AssignedOrderCount = models.IntegerField(
        default=0, db_column='paifa_dingdan_shu', verbose_name='派发订单总数')
    AssignedAmount = models.DecimalField(
        max_digits=12, decimal_places=2, default=0.00,
        db_column='paifa_jine', verbose_name='派发订单总金额')

    # 结算统计
    SettledOrderCount = models.IntegerField(
        default=0, db_column='jiesuan_dingdan_shu', verbose_name='结算订单总数')
    SettledAmount = models.DecimalField(
        max_digits=12, decimal_places=2, default=0.00,
        db_column='jiesuan_jine', verbose_name='结算总金额')

    # 退款统计
    RefundOrderCount = models.IntegerField(
        default=0, db_column='tuikuan_dingdan_shu', verbose_name='退款订单总数')
    RefundAmount = models.DecimalField(
        max_digits=12, decimal_places=2, default=0.00,
        db_column='tuikuan_jine', verbose_name='退款总金额')

    class Meta:
        db_table = 'shangjia_ri_tongji'
        verbose_name = '商家每日统计'
        unique_together = [['club_id', 'MerchantID', 'Date']]
        indexes = [
            models.Index(fields=['Date', '-AssignedAmount']),
            models.Index(fields=['Date', '-SettledAmount']),
            models.Index(fields=['Date', '-AssignedOrderCount']),
        ]

    def __str__(self):
        return f"商家{self.MerchantID} {self.Date}"


# ==================== 7. 打手每日统计 ====================
class PlayerDailyStats(QModel):
    """打手每日统计表（原 DashouRiTongji）"""
    club_id = models.CharField(max_length=16, default='xq', db_index=True, verbose_name='俱乐部ID')
    PlayerID = models.CharField(
        max_length=7, db_index=True, db_column='yonghuid', verbose_name='打手用户ID')
    Date = models.DateField(
        db_index=True, db_column='riqi', verbose_name='日期')

    # 接单统计
    AcceptedOrderTotal = models.IntegerField(
        default=0, db_column='jiedan_zongliang', verbose_name='接单总量')
    CompletedOrderTotal = models.IntegerField(
        default=0, db_column='chengjiao_zongliang', verbose_name='成交单总量')

    # 金额统计
    AcceptedAmount = models.DecimalField(
        max_digits=12, decimal_places=2, default=0.00,
        db_column='jiedan_zonge', verbose_name='接单总金额')
    CompletedAmount = models.DecimalField(
        max_digits=12, decimal_places=2, default=0.00,
        db_column='chengjiao_zonge', verbose_name='成交总金额')

    # 退款统计
    RefundCount = models.IntegerField(
        default=0, db_column='tuikuan_liang', verbose_name='退款订单量')
    RefundAmount = models.DecimalField(
        max_digits=12, decimal_places=2, default=0.00,
        db_column='tuikuan_jine', verbose_name='退款总金额')

    class Meta:
        db_table = 'dashou_ri_tongji'
        verbose_name = '打手每日统计'
        unique_together = [['club_id', 'PlayerID', 'Date']]
        indexes = [
            models.Index(fields=['Date', '-AcceptedOrderTotal']),
            models.Index(fields=['Date', '-CompletedOrderTotal']),
            models.Index(fields=['Date', '-AcceptedAmount']),
            models.Index(fields=['Date', '-CompletedAmount']),
        ]

    def __str__(self):
        return f"打手{self.PlayerID} {self.Date}"


# ==================== 8. 组长每日统计 ====================
class LeaderDailyStats(QModel):
    """组长每日统计表（原 ZuzhangRiTongji）"""
    club_id = models.CharField(max_length=16, default='xq', db_index=True, verbose_name='俱乐部ID')
    LeaderID = models.CharField(
        max_length=7, db_index=True, db_column='yonghuid', verbose_name='组长用户ID')
    Date = models.DateField(
        db_index=True, db_column='riqi', verbose_name='日期')

    InvitedManagerCount = models.IntegerField(
        default=0, db_column='yaoqing_guanshi_shu', verbose_name='邀请管事总数')
    TotalIncome = models.DecimalField(
        max_digits=12, decimal_places=2, default=0.00,
        db_column='shouru_zonge', verbose_name='收入总额（分佣）')
    CommissionAmount = models.DecimalField(
        max_digits=12, decimal_places=2, default=0.00,
        db_column='fenyong_jine', verbose_name='分佣金额')

    class Meta:
        db_table = 'zuzhang_ri_tongji'
        verbose_name = '组长每日统计'
        unique_together = [['club_id', 'LeaderID', 'Date']]
        indexes = [
            models.Index(fields=['Date', '-InvitedManagerCount']),
            models.Index(fields=['Date', '-TotalIncome']),
        ]

    def __str__(self):
        return f"组长{self.LeaderID} {self.Date}"


# ==================== 9. 管事每日统计 ====================
class ManagerDailyStats(QModel):
    """管事每日统计表（原 GuanshiRiTongji）"""
    club_id = models.CharField(max_length=16, default='xq', db_index=True, verbose_name='俱乐部ID')
    ManagerID = models.CharField(
        max_length=7, db_index=True, db_column='yonghuid', verbose_name='管事用户ID')
    Date = models.DateField(
        db_index=True, db_column='riqi', verbose_name='日期')

    InvitedPlayerCount = models.IntegerField(
        default=0, db_column='yaoqing_dashou_shu', verbose_name='邀请打手总数')
    RechargedPlayerCount = models.IntegerField(
        default=0, db_column='chongzhi_dashou_shu', verbose_name='充值打手数量')
    TotalIncome = models.DecimalField(
        max_digits=12, decimal_places=2, default=0.00,
        db_column='shouru_zonge', verbose_name='收入总额')

    class Meta:
        db_table = 'guanshi_ri_tongji'
        verbose_name = '管事每日统计'
        unique_together = [['club_id', 'ManagerID', 'Date']]
        indexes = [
            models.Index(fields=['Date', '-InvitedPlayerCount']),
            models.Index(fields=['Date', '-RechargedPlayerCount']),
            models.Index(fields=['Date', '-TotalIncome']),
        ]

    def __str__(self):
        return f"管事{self.ManagerID} {self.Date}"


# ==================== 10. 管事续费每日统计 ====================
class ManagerRenewalDailyStats(QModel):
    """管事续费每日统计表（原 GuanshiXufeiRiTongji）"""
    club_id = models.CharField(max_length=16, default='xq', db_index=True, verbose_name='俱乐部ID')
    ManagerID = models.CharField(
        max_length=7, db_index=True, db_column='yonghuid', verbose_name='管事用户ID')
    Date = models.DateField(
        db_index=True, db_column='riqi', verbose_name='日期')

    RenewalTotal = models.IntegerField(
        default=0, db_column='xufei_zongshu', verbose_name='今日续费总数')
    RenewalRevenue = models.DecimalField(
        max_digits=12, decimal_places=2, default=0.00,
        db_column='xufei_shouyi', verbose_name='续费收益金额')

    class Meta:
        db_table = 'guanshi_xufei_ri_tongji'
        verbose_name = '管事续费每日统计'
        unique_together = [['club_id', 'ManagerID', 'Date']]
        indexes = [
            models.Index(fields=['Date', '-RenewalTotal']),
            models.Index(fields=['Date', '-RenewalRevenue']),
        ]

    def __str__(self):
        return f"管事续费{self.ManagerID} {self.Date}"


# ==================== 11. 提现每日统计 ====================
class WithdrawalDailyStats(QModel):
    """每日提现统计表（原 TixianRiTongji），按俱乐部+身份统计当天提现到账总额"""
    club_id = models.CharField(max_length=16, default='xq', db_index=True, verbose_name='俱乐部ID')
    Date = models.DateField(
        db_index=True, db_column='riqi', verbose_name='日期')
    WithdrawalType = models.IntegerField(
        choices=[(1, '打手'), (2, '管事'), (3, '组长'),
                 (4, '考核官'), (5, '打手押金'), (6, '商家余额')],
        db_column='leixing', verbose_name='用户类型')
    total_amount = models.DecimalField(
        max_digits=12, decimal_places=2, default=0.00, verbose_name='当天提现总额(元)')

    class Meta:
        db_table = 'tixian_ri_tongji'
        verbose_name = '每日提现统计'
        unique_together = [['club_id', 'Date', 'WithdrawalType']]
        indexes = [
            models.Index(fields=['club_id', 'Date', 'WithdrawalType']),
            models.Index(fields=['Date', 'WithdrawalType']),
        ]

    def __str__(self):
        return f"{self.Date} - {self.get_WithdrawalType_display()} 提现总额: {self.total_amount}"


# ==================== 兼容别名（供逐步迁移） ====================
ShangjiaRiTongji = MerchantDailyStats
DashouRiTongji = PlayerDailyStats
ZuzhangRiTongji = LeaderDailyStats
GuanshiRiTongji = ManagerDailyStats
GuanshiXufeiRiTongji = ManagerRenewalDailyStats
TixianRiTongji = WithdrawalDailyStats
