from django.db import models

# ==================== 1. 角色表 ====================
class Role(models.Model):
    """角色表"""
    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='角色描述')

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

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

        ]

    def __str__(self):
        return self.role_name


# ==================== 2. 权限表 ====================
class Permission(models.Model):
    """权限表"""
    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='权限描述')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')

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

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


# ==================== 3. 角色-权限关联表 ====================
class RolePermission(models.Model):
    """角色权限关联表"""
    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='权限')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'role_permission'
        verbose_name = '角色权限关联'
        verbose_name_plural = '角色权限关联'
        unique_together = [['role', 'permission']]   # 防止重复授权

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


# ==================== 4. 用户-角色关联表 ====================
class UserRole(models.Model):
    """用户角色关联表"""
    id = models.AutoField(primary_key=True)
    account_id = models.CharField(max_length=11, db_index=True, verbose_name='账号ID')  # 对应 UserMain 的 phone 字段
    role = models.ForeignKey(Role, on_delete=models.CASCADE, db_index=True, verbose_name='角色')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'user_role'
        verbose_name = '用户角色关联'
        verbose_name_plural = '用户角色关联'
        unique_together = [['account_id', 'role']]   # 同一用户同一角色只能有一条

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


class AbnormalUserLog(models.Model):
    """记录恶意尝试越权操作的用户信息"""
    # 账号信息
    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')

    # 地理位置信息（需借助第三方API，这里只存储请求时的IP，后续可离线解析）
    # 但我们可以存储更多请求细节
    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='详细描述')

    # 时间戳
    create_time = 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=['create_time']),
        ]

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





class ShangjiaRiTongji(models.Model):
    yonghuid = models.CharField(max_length=7, db_index=True, verbose_name='商家用户ID')
    riqi = models.DateField(db_index=True, verbose_name='日期')  # 年月日

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

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

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

    class Meta:
        db_table = 'shangjia_ri_tongji'
        verbose_name = '商家每日统计'
        unique_together = [['yonghuid', 'riqi']]  # 每人每天一条记录
        indexes = [
            models.Index(fields=['riqi', '-paifa_jine']),
            models.Index(fields=['riqi', '-jiesuan_jine']),
            models.Index(fields=['riqi', '-paifa_dingdan_shu']),
        ]





class DashouRiTongji(models.Model):
    yonghuid = models.CharField(max_length=7, db_index=True, verbose_name='打手用户ID')
    riqi = models.DateField(db_index=True, verbose_name='日期')  # 年月日

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

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

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

    class Meta:
        db_table = 'dashou_ri_tongji'
        verbose_name = '打手每日统计'
        unique_together = [['yonghuid', 'riqi']]
        indexes = [
            models.Index(fields=['riqi', '-jiedan_zongliang']),
            models.Index(fields=['riqi', '-chengjiao_zongliang']),
            models.Index(fields=['riqi', '-jiedan_zonge']),
            models.Index(fields=['riqi', '-chengjiao_zonge']),
        ]



class ZuzhangRiTongji(models.Model):
    yonghuid = models.CharField(max_length=7, db_index=True, verbose_name='组长用户ID')
    riqi = models.DateField(db_index=True, verbose_name='日期')  # 年月日

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

    # 可选明细
    fenyong_jine = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='分佣金额')

    class Meta:
        db_table = 'zuzhang_ri_tongji'
        verbose_name = '组长每日统计'
        unique_together = [['yonghuid', 'riqi']]
        indexes = [
            models.Index(fields=['riqi', '-yaoqing_guanshi_shu']),
            models.Index(fields=['riqi', '-shouru_zonge']),
        ]




class GuanshiRiTongji(models.Model):
    yonghuid = models.CharField(max_length=7, db_index=True, verbose_name='管事用户ID')
    riqi = models.DateField(db_index=True, verbose_name='日期')  # 年月日

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

    class Meta:
        db_table = 'guanshi_ri_tongji'
        verbose_name = '管事每日统计'
        unique_together = [['yonghuid', 'riqi']]
        indexes = [
            models.Index(fields=['riqi', '-yaoqing_dashou_shu']),
            models.Index(fields=['riqi', '-chongzhi_dashou_shu']),
            models.Index(fields=['riqi', '-shouru_zonge']),
        ]




class GuanshiXufeiRiTongji(models.Model):
    yonghuid = models.CharField(max_length=7, db_index=True, verbose_name='管事用户ID')
    riqi = models.DateField(db_index=True, verbose_name='日期')  # 年月日

    xufei_zongshu = models.IntegerField(default=0, verbose_name='今日续费总数')          # 续费订单数（或续费打手数）
    xufei_shouyi = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='续费收益金额')

    class Meta:
        db_table = 'guanshi_xufei_ri_tongji'
        verbose_name = '管事续费每日统计'
        unique_together = [['yonghuid', 'riqi']]
        indexes = [
            models.Index(fields=['riqi', '-xufei_zongshu']),
            models.Index(fields=['riqi', '-xufei_shouyi']),
        ]



# models.py 中添加

class TixianRiTongji(models.Model):
    """
    每日提现统计表（按身份统计当天提现总额）
    """
    riqi = models.DateField(db_index=True, verbose_name='日期')
    leixing = models.IntegerField(
        choices=[
            (1, '打手'), (2, '管事'), (3, '组长'),
            (4, '考核官'), (5, '打手押金'), (6, '商家余额'),
        ],
        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 = [['riqi', 'leixing']]  # 每天每个身份一条记录
        indexes = [models.Index(fields=['riqi', 'leixing'])]

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