# models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from gvsdsdk.model_base import QModel


# ==================== 用户主表（已废弃，迁移至 gvsdsdk.User） ====================
class UserMain(AbstractBaseUser, QModel):
    # ID字段
    id = models.AutoField(primary_key=True, verbose_name='主键ID')
    yonghuid = models.CharField(max_length=7, unique=True, db_index=True, verbose_name='用户ID')

    # 微信相关字段
    openid = models.CharField(max_length=64, unique=True, db_index=True, verbose_name='微信OpenID')
    unionid = models.CharField(max_length=64, null=True, blank=True, db_index=True, verbose_name='微信UnionID')

    # 基础信息字段
    #tupian_url = models.CharField(max_length=500, null=True, blank=True, verbose_name='商品图片URL')  # 用CharField
    avatar = models.CharField(max_length=500, null=True, blank=True,default='a_long/morentouxiang.jpg', verbose_name='头像')  # 用CharField
    phone = models.CharField(max_length=11, blank=True, null=True, verbose_name='手机号')
    shoujihao_renzheng = models.BooleanField(default=False, verbose_name='手机号是否已认证')
    password = models.CharField(max_length=200, null=True, blank=True, verbose_name='密码')
    zhifu = models.CharField(max_length=500, null=True, blank=True, verbose_name='收款码图片')  # 用CharField
    skzhanghao = models.CharField(max_length=11, blank=True, null=True, verbose_name='收款账号')
    ip = models.CharField(max_length=50, blank=True, null=True, verbose_name='来访用户ip')
    last_login_time = models.DateTimeField(null=True, blank=True, verbose_name='最后登录时间')


    # 用户类型字段
    user_type = models.CharField(
        max_length=10,
        choices=[
            ('normal', '普通用户'),
            ('dashou', '打手'),
            ('shop', '商家'),
            ('guanshi', '管事'),
            ('admin', '管理员')
        ],
        default='normal',
        verbose_name='用户类型'
    )

    # 状态和时间字段
    #is_active = models.BooleanField(default=True, verbose_name='是否激活')
    #last_login = models.DateTimeField(blank=True, null=True, verbose_name='最后登录时间')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    # 邀请码字段
    #yaoqingma = models.CharField(max_length=20, blank=True, null=True, verbose_name='邀请码')

    # 只需要添加这3行
    USERNAME_FIELD = 'openid'  # 用openid作为用户名
    REQUIRED_FIELDS = ['yonghuid']  # 必填字段

    class Meta:
        managed = False
        db_table = 'user_main'
        verbose_name = '用户主表'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['yonghuid']),
            models.Index(fields=['openid']),
            #models.Index(fields=['phone']),
            models.Index(fields=['user_type']),
            #models.Index(fields=['CreateTime']),
        ]

    def __str__(self):
        return f'{self.yonghuid}'



# 新增服务号用户表
class OfficialAccountUser(QModel):
    unionid = models.CharField(max_length=64, null =True,db_index=True, verbose_name='UnionID')
    official_openid = models.CharField(max_length=64, db_index=True, unique=True, verbose_name='服务号OpenID')
    subscribe_time = models.DateTimeField(auto_now_add=True, verbose_name='关注时间')
    is_subscribed = models.BooleanField(default=True, verbose_name='是否关注')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'official_account_user'
        verbose_name = '服务号用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.unionid[:8]}... (关注: {self.is_subscribed})"        


# ==================== 老板扩展表 ====================
class UserBoss(QModel):
    user = models.OneToOneField('users.User', on_delete=models.CASCADE, related_name='BossProfile',
                                verbose_name='关联用户', db_column='UserUUID')
    nickname = models.CharField(max_length=50, verbose_name='老板昵称')
    zonge = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='消费总额')
    alldingdan = models.IntegerField(default=0, verbose_name='订单总数')
    alltui = models.IntegerField(default=0, verbose_name='退款总数')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'user_boss'
        verbose_name = '老板扩展表'
        verbose_name_plural = verbose_name
        indexes = [models.Index(fields=['user']), ]


# ==================== 点单端 C 用户邀请 ====================
class YonghuCYaoqing(QModel):
    """点单端用户邀请关系（邀请码 / 邀请人 / 邀请人数）"""
    user = models.OneToOneField(
        'users.User',
        on_delete=models.CASCADE,
        related_name='CYaoqingProfile',
        verbose_name='关联用户',
        db_column='UserUUID',
    )
    yaoqingma = models.CharField(max_length=20, null=True, blank=True, db_index=True, verbose_name='邀请码')
    invite_qrcode_url = models.CharField(max_length=500, null=True, blank=True, verbose_name='邀请小程序码URL')
    yaogingshuliang = models.IntegerField(default=0, verbose_name='邀请人数')
    yaoqingren = models.CharField(max_length=7, null=True, blank=True, db_index=True, verbose_name='邀请人UserUID')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'yonghu_c_yaoqing'
        verbose_name = '点单端用户邀请'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user']),
            models.Index(fields=['yaoqingma']),
            models.Index(fields=['yaoqingren']),
        ]


# ==================== 打手扩展表 ====================
class UserDashou(QModel):
    user = models.OneToOneField('users.User', on_delete=models.CASCADE, related_name='DashouProfile',
                                verbose_name='关联用户', db_column='UserUUID')
    nicheng = models.CharField(max_length=50, null=True,  verbose_name='打手昵称')
    chenghao = models.CharField(max_length=50, null=True,verbose_name='打手称号')
    zhuangtai = models.IntegerField(default=1, verbose_name='打手状态')
    zaixianzhuangtai = models.IntegerField(default=1, verbose_name='打手在线状态')
    zhanghaozhuangtai = models.IntegerField(default=1, verbose_name='打手账号状态')
    fengjin_yuanyin = models.CharField(max_length=200, blank=True, default='', verbose_name='封禁原因')
    jieshao = models.TextField(null=True, verbose_name='打手介绍')
    jiedanzongliang = models.IntegerField(default=0, verbose_name='接单总量')
    chengjiaozongliang = models.IntegerField(default=0, verbose_name='成交单总量')
    tuikuanliang = models.IntegerField(default=0, verbose_name='退款订单总量')
    yue = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='可提现余额')
    zonge = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='打单赚取总额')
    dianhua = models.CharField(max_length=20, null=True, verbose_name='打手电话')
    wechat = models.CharField(max_length=50,null=True, verbose_name='打手微信号')
    yaoqingren = models.CharField(max_length=7,null=True, db_index=True, verbose_name='邀请人ID')
    jinrijiedan = models.IntegerField(default=0, verbose_name='今日接单数量')
    jinrishouyi = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='今日收益金额')
    jinyuejiedan = models.IntegerField(default=0, verbose_name='今月接单数量')
    jinyueshouyi = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='今月收益金额')
    jifen = models.IntegerField(default=0, verbose_name='打手积分')
    yajin= models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='打手押金')
    # 资金冻结池 + 风险快照（冻结功能；未开启俱乐部保持 0，不影响现网）
    dongjie_yue = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='冻结资金池')
    risk_fine_rate = models.DecimalField(max_digits=8, decimal_places=6, default=0, verbose_name='窗口罚款率')
    risk_complaint_rate = models.DecimalField(max_digits=8, decimal_places=6, default=0, verbose_name='窗口投诉率')
    risk_completed_orders = models.IntegerField(default=0, verbose_name='窗口完成单量')
    risk_valid_invites = models.IntegerField(default=0, verbose_name='窗口有效邀请数')
    risk_stat_at = models.DateTimeField(null=True, blank=True, verbose_name='风险快照时间')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    last_tixian_date = models.DateField(null=True, blank=True, verbose_name='最近提现日期')  # 用于重置今日提现金额
    jinritixian_jine = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='今日已提现金额')
    kaioi_ewai_xiane = models.BooleanField(default=False, verbose_name='是否开启额外提现限额')  # True=开启额外限额
    ewai_xiane = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='额外提现限额(元)')

    class Meta:
        db_table = 'user_dashou'
        verbose_name = '打手扩展表'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user']),
            #models.Index(fields=['zhuangtai']),
            models.Index(fields=['yaoqingren']),
            #models.Index(fields=['nicheng']),

        ]


# ==================== 商家扩展表 ====================
class UserShangjia(QModel):
    user = models.OneToOneField('users.User', on_delete=models.CASCADE, related_name='ShopProfile',
                                verbose_name='关联用户', db_column='UserUUID')
    nicheng = models.CharField(max_length=50, unique=True, db_index=True, verbose_name='商家昵称')
    zhuangtai = models.IntegerField(choices=[(0, '待审核'), (1, '正常'), (2, '禁用')], default=1,
                                    verbose_name='商家状态')
    fengjin_yuanyin = models.CharField(max_length=200, blank=True, default='', verbose_name='封禁原因')
    dianhua = models.CharField(max_length=20,null=True,verbose_name='商家电话')
    wechat = models.CharField(max_length=50, null=True, verbose_name='商家微信号')
    fabu = models.IntegerField(default=0, verbose_name='发布订单总数量')
    tuikuan = models.IntegerField(default=0, verbose_name='退款订单总量')
    yue = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='商家余额')
    chengjiao = models.IntegerField(default=0, verbose_name='商家成交订单总量')
    jinridingdan = models.IntegerField(default=0, verbose_name='商家今日订单总量')
    jinriliushui = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='商家今日流水')
    jinyuedingdan = models.IntegerField(default=0, verbose_name='商家今月订单总量')
    jinyueliushui = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='商家今月流水')
    is_youzhi_shangjia = models.BooleanField(default=False, verbose_name='优质商家')
    is_teyue_shangjia = models.BooleanField(default=False, verbose_name='特约商家')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'user_shangjia'
        verbose_name = '商家扩展表'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user']),
            models.Index(fields=['nicheng']),
        ]


# ==================== 管事扩展表 ====================
class UserGuanshi(QModel):
    user = models.OneToOneField('users.User', on_delete=models.CASCADE, related_name='GuanshiProfile',
                                verbose_name='关联用户', db_column='UserUUID')
    yaoqingren = models.CharField(max_length=7,null=True, db_index=True, verbose_name='邀请人ID')                            
    yaoqingma =  models.CharField(max_length=20,null=True,db_index=True, verbose_name='邀请码')
    invite_qrcode_url = models.CharField(max_length=500, null=True, blank=True, verbose_name='邀请码二维码图片URL')
    dianhua = models.CharField(max_length=20,null=True, verbose_name='管事电话')
    wechat = models.CharField(max_length=50,null=True, verbose_name='管事微信号')
    yaogingshuliang = models.IntegerField(default=0, verbose_name='邀请打手总数')
    zhuangtai = models.IntegerField(choices=[(0, '禁用'), (1, '正常')], default=1, verbose_name='管事状态')
    fengjin_yuanyin = models.CharField(max_length=200, blank=True, default='', verbose_name='封禁原因')
    jinrichongzhi = models.IntegerField(default=0, verbose_name='今日充值打手数量')
    jinyuechongzhi = models.IntegerField(default=0, verbose_name='今月充值打手数量')
    chongzhifenrun = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='充值分佣总额')
    yue = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='可提现余额')
    dongjie_yue = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='冻结资金池')
    risk_fine_rate = models.DecimalField(max_digits=8, decimal_places=6, default=0, verbose_name='窗口罚款率')
    risk_complaint_rate = models.DecimalField(max_digits=8, decimal_places=6, default=0, verbose_name='窗口投诉率')
    risk_completed_orders = models.IntegerField(default=0, verbose_name='窗口完成单量')
    risk_valid_invites = models.IntegerField(default=0, verbose_name='窗口有效邀请数')
    risk_stat_at = models.DateTimeField(null=True, blank=True, verbose_name='风险快照时间')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    # 新增：首次分红金额（针对特殊用户）
    fenhong_yici = models.DecimalField(max_digits=10,decimal_places=2,default=0.00,verbose_name='首次分红金额')

    # 新增：二次分红开关
    fenghong_erci_enabled = models.BooleanField(default=False,verbose_name='开启二次分红')

    # 新增：二次分红金额
    fenghong_erci = models.DecimalField(max_digits=10,decimal_places=2,default=0.00,verbose_name='二次分红金额')


    last_tixian_date = models.DateField(null=True, blank=True, verbose_name='最近提现日期')
    jinritixian_jine = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='今日已提现金额')
    kaioi_ewai_xiane = models.BooleanField(default=False, verbose_name='是否开启额外提现限额')
    ewai_xiane = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='额外提现限额(元)')

    class Meta:
        db_table = 'user_guanshi'
        verbose_name = '管事扩展表'
        verbose_name_plural = verbose_name
        indexes = [models.Index(fields=['user']),
                   models.Index(fields=['yaoqingma']),
                   ]




class UserZuzhang(QModel):
    """组长扩展表（与UserMain一对一关联）"""
    user = models.OneToOneField(
        'users.User',
        on_delete=models.CASCADE,
        related_name='ZuzhangProfile',
        verbose_name='关联用户',
        db_index=True,
        db_column='UserUUID'
    )
    # 组长邀请码
    yaoqingma = models.CharField(max_length=20, null=True, db_index=True, verbose_name='组长邀请码')
    # 分佣总额
    fenyong_zonge = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='分佣总额(元)')
    # 可提现金额
    ketixian_jine = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='可提现金额(元)')
    dongjie_yue = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='冻结资金池')
    risk_fine_rate = models.DecimalField(max_digits=8, decimal_places=6, default=0, verbose_name='窗口罚款率')
    risk_complaint_rate = models.DecimalField(max_digits=8, decimal_places=6, default=0, verbose_name='窗口投诉率')
    risk_completed_orders = models.IntegerField(default=0, verbose_name='窗口完成单量')
    risk_valid_invites = models.IntegerField(default=0, verbose_name='窗口有效邀请数')
    risk_stat_at = models.DateTimeField(null=True, blank=True, verbose_name='风险快照时间')
    # 邀请总数
    yaoqing_zongshu = models.IntegerField(default=0, verbose_name='邀请总数')
    # 今日分佣
    jinri_fenyong = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='今日分佣(元)')
    # 今月分佣
    jinyue_fenyong = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='今月分佣(元)')
    # 账号状态
    zhuangtai = models.IntegerField(choices=[(0, '禁用'), (1, '正常')], default=1, verbose_name='账号状态')
    fengjin_yuanyin = models.CharField(max_length=200, blank=True, default='', verbose_name='封禁原因')
    # 推广海报相对URL
    haibao_url = models.CharField(max_length=500, null=True, blank=True, verbose_name='推广海报相对URL')
    # 今日提现
    jinri_tixian = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='今日提现金额(元)')
    # 最后提现时间
    last_tixian_time = models.DateTimeField(null=True, blank=True, verbose_name='最后提现时间')
    # 额外提现限额
    ewai_tixian_xiane = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='额外提现限额(元)')
    # 是否开启额外提现
    kaioi_ewai_tixian = models.BooleanField(default=False, verbose_name='开启额外提现')
    # 是否开启额外分红
    kaioi_ewai_fenhong = models.BooleanField(default=False, verbose_name='开启额外分红')
    # 额外分红金额
    ewai_fenhong_jine = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, verbose_name='额外分红金额(元)')
    # 创建时间
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    # 更新时间
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'user_zuzhang'
        verbose_name = '组长扩展表'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user']),
            models.Index(fields=['yaoqingma']),
        ]

    def __str__(self):
        return f"组长 {self.user.UserUID}"                   

class UserShenheguan(QModel):
    """审核官扩展表（与UserMain一对一关联）"""
    user = models.OneToOneField('users.User', on_delete=models.CASCADE, related_name='ShenheguanProfile', verbose_name='关联用户', db_index=True, db_column='UserUUID')
    zhuangtai = models.IntegerField(choices=[(0, '禁用'), (1, '正常')], default=1, verbose_name='账号状态')
    shenhe_zhuangtai = models.IntegerField(choices=[(0, '空闲'), (1, '审核中')], default=0, verbose_name='审核官状态')
    is_renzheng = models.BooleanField(default=False, verbose_name='是否认证')
    shenhe_zongshu = models.IntegerField(default=0, verbose_name='审核总数')
    tongguo_zongshu = models.IntegerField(default=0, verbose_name='通过总数')
    yue = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='可提现余额')
    zonge = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='赚取总额')
    dongjie_yue = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='冻结资金池')
    risk_fine_rate = models.DecimalField(max_digits=8, decimal_places=6, default=0, verbose_name='窗口罚款率')
    risk_complaint_rate = models.DecimalField(max_digits=8, decimal_places=6, default=0, verbose_name='窗口投诉率')
    risk_completed_orders = models.IntegerField(default=0, verbose_name='窗口完成单量')
    risk_valid_invites = models.IntegerField(default=0, verbose_name='窗口有效邀请数')
    risk_stat_at = models.DateTimeField(null=True, blank=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_shenheguan'
        verbose_name = '审核官扩展表'
        verbose_name_plural = verbose_name
        indexes = [models.Index(fields=['user'])]


# ==================== 管理员扩展表 ====================
class AdminProfile(QModel):
    user = models.OneToOneField('users.User', on_delete=models.CASCADE, related_name='AdminProfile',
                                verbose_name='关联用户', db_column='UserUUID')
    password = models.CharField(max_length=255, verbose_name='密码')
    wechat = models.CharField(max_length=50, blank=True, verbose_name='管理员微信')
    yaoqingma = models.CharField(max_length=20, null=True, db_index=True,verbose_name='管理员邀请码')  # 🟢 新增字段
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'admin_profile'
        verbose_name = '管理员扩展表'
        verbose_name_plural = verbose_name
        indexes = [models.Index(fields=['user']), ]


class UserKefu(QModel):
    user = models.OneToOneField('users.User', on_delete=models.CASCADE, related_name='KefuProfile', verbose_name='关联用户', db_column='UserUUID')
    nicheng = models.CharField(max_length=50, verbose_name='客服昵称')
    erjimima = models.CharField(max_length=128, verbose_name='二级密码')
    zhuangtai = models.IntegerField(choices=[(0, '禁用'), (1, '正常')], default=1, verbose_name='客服状态')
    jinrichuli = models.IntegerField(default=0, verbose_name='今日处理订单数')
    jinyuechuli = models.IntegerField(default=0, verbose_name='本月处理订单数')
    zongchuli = models.IntegerField(default=0, verbose_name='累计处理订单数')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'user_kefu'
        verbose_name = '客服扩展表'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user']),
            models.Index(fields=['zhuangtai']),
        ]

    def __str__(self):
        return f"{self.nicheng} ({self.user.UserUID})"        




class Tixianjilu(QModel):
    id = models.AutoField(primary_key=True, verbose_name='提现记录ID')
    club_id = models.CharField(max_length=16, default='xq', db_index=True, verbose_name='俱乐部ID')
    yonghuid = models.CharField(max_length=7, db_index=True, verbose_name='提现用户ID')
    avatar = models.CharField(max_length=500, null=True, blank=True, verbose_name='头像')  # 用CharField
    phone = models.CharField(max_length=11, blank=True, null=True, verbose_name='手机号')
    nicheng = models.CharField(max_length=50, null=True, verbose_name='打手昵称')
    leixing = models.PositiveIntegerField(null=True, blank=True, verbose_name='提现类型1:打手佣金2：管事分红')
    zhifu = models.CharField(max_length=500, null=True, blank=True, verbose_name='收款码图片')  # 用CharField
    skzhanghao = models.CharField(max_length=11, blank=True, null=True,  verbose_name='收款账号')
    jine = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='提现金额')
    # 状态与平台：用整数表示，具体含义由业务逻辑定义
    zhuangtai = models.IntegerField(default=1, null=True, blank=True, db_index=True, verbose_name='提现状态1:审核2：成功3：失败')
    fangshi = models.IntegerField(null=True, blank=True,db_index=True, verbose_name='收款方式1:微信2：支付宝')
    shenheid = models.CharField(max_length=11, null=True, db_index=True, verbose_name='审核用户ID')
    bhliyou = models.TextField(null=True, blank=True, verbose_name='驳回理由')
    # ---------- 自动提现审核新流程关联字段（旧数据为空，兼容历史记录） ----------
    shenhe_jilu_id = models.IntegerField(
        null=True, blank=True, db_index=True,
        verbose_name='关联提现审核记录ID(TixianShenheJilu.id)'
    )
    shenhe_danhao = models.CharField(
        max_length=32, null=True, blank=True, 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 = 'tixianjilu'
        verbose_name = '提现记录表'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['club_id', 'zhuangtai']),
            models.Index(fields=['yonghuid']),
            models.Index(fields=['zhuangtai']),
            models.Index(fields=['shenheid']),
            models.Index(fields=['fangshi']),
            models.Index(fields=['shenhe_danhao']),
            models.Index(fields=['shenhe_jilu_id']),
        ]






class TixianShenheJilu(QModel):
    """
    提现审核记录表（自动打款新流程）
    状态码与前端 TX_STATUS / Tixianjilu.zhuangtai 完全对标：
        1=审核中  2=提现成功(已收款)  3=提现失败  4=审核成功  5=审核失败  6=待收款
    """
    # 审核单号（唯一，前端字段 shenhe_danhao）
    shenhe_danhao = models.CharField(
        max_length=32, unique=True, db_index=True, verbose_name='审核单号'
    )
    club_id = models.CharField(max_length=16, default='xq', db_index=True, verbose_name='俱乐部ID')
    yonghuid = models.CharField(max_length=7, db_index=True, verbose_name='用户ID')
    # 提现类型：1打手佣金 2管事分红 3组长分红 4考核官分佣 5打手押金 6商家余额
    leixing = models.PositiveSmallIntegerField(db_index=True, verbose_name='提现类型')
    zhuangtai = models.IntegerField(
        default=1, db_index=True,
        verbose_name='审核状态(1审核中2提现成功3提现失败4审核成功5审核失败6待收款)'
    )
    # 金额：shenqing_jine=申请扣款金额；shijidaozhang=实际打款到账金额
    shenqing_jine = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='申请提现金额(扣款额)')
    shouxufei = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='手续费')
    shijidaozhang = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='实际到账金额')
    feilv = models.DecimalField(max_digits=5, decimal_places=4, default=0, verbose_name='手续费率')
    # 审核/驳回
    bhliyou = models.TextField(null=True, blank=True, verbose_name='驳回/失败原因')
    bo_hui_ren_id = models.CharField(
        max_length=11, null=True, blank=True, db_index=True, verbose_name='驳回人用户ID'
    )
    shenhe_ren_id = models.CharField(
        max_length=11, null=True, blank=True, db_index=True, verbose_name='审核通过操作人ID'
    )
    # 关联提现记录表主键
    tixianjilu_id = models.IntegerField(null=True, blank=True, db_index=True, verbose_name='关联Tixianjilu.id')
    # 最近一次打款单号（仅作记录，不唯一；同一审核单可多次收款产生多条打款记录）
    tixian_auto_id = models.CharField(
        max_length=32, null=True, blank=True, db_index=True,
        verbose_name='最近一次打款单号(非唯一，重试收款会更新)'
    )
    fail_reason = models.TextField(null=True, blank=True, verbose_name='微信打款失败原因')
    # 打款方式：1=手动打款  2=自动打款（微信商家转账）
    dakuan_mode = models.PositiveSmallIntegerField(
        default=1, db_index=True, verbose_name='打款方式(1手动2自动)'
    )
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'tixian_shenhe_jilu'
        verbose_name = '提现审核记录'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['yonghuid', 'zhuangtai']),
            models.Index(fields=['yonghuid', 'leixing']),
            models.Index(fields=['shenhe_danhao']),
        ]

    def __str__(self):
        return f'{self.shenhe_danhao}({self.yonghuid})'



class TixianAutoRecord(QModel):
    """
    自动提现记录表（微信自动打款）
    """
    id = models.BigAutoField(primary_key=True)
    tixian_id = models.CharField(
        max_length=32,
        unique=True,
        db_index=True,
        verbose_name='提现订单号(自定义)'
    )
    club_id = models.CharField(max_length=16, default='xq', db_index=True, verbose_name='俱乐部ID')
    yonghuid = models.CharField(max_length=7, db_index=True, verbose_name='用户ID')
    leixing = models.IntegerField(verbose_name='提现类型 1打手 2管事')
    jine = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='申请提现金额')
    shouxufei = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='手续费')
    shijidaozhang = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='实际到账金额')
    feilv = models.DecimalField(max_digits=5, decimal_places=4, verbose_name='费率')
    zhuangtai = models.IntegerField(
        default=0,
        choices=[(0, '处理中'), (1, '成功'), (2, '失败')],
        verbose_name='状态'
    )
    wechat_transfer_no = models.CharField(
        max_length=64,
        null=True,
        blank=True,
        verbose_name='微信转账单号'
    )
    wechat_package = models.TextField(
        null=True,
        blank=True,
        verbose_name='微信返回的package_info(JSON)'
    )
    fail_reason = models.TextField(null=True, blank=True, verbose_name='失败原因')
    # 关联提现审核单号（新流程必填，旧数据为空）
    shenhe_danhao = models.CharField(
        max_length=32, null=True, blank=True, 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 = 'tixian_auto_record'
        verbose_name = '自动提现记录'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['tixian_id']),
            models.Index(fields=['yonghuid']),
            models.Index(fields=['zhuangtai']),
        ]

    def __str__(self):
        return f"{self.tixian_id} - {self.get_zhuangtai_display()}"





# yonghu/models.py
class Xiugaijilu(QModel):
    id = models.AutoField(primary_key=True, verbose_name='记录ID')
    yonghuid = models.CharField(max_length=7, verbose_name='被修改用户ID')
    xiugaiid = models.CharField(max_length=30, verbose_name='修改人账号ID')
    leixing = models.IntegerField(verbose_name='被修改用户类型')

    # 打手相关金钱字段
    xiugaitijiao = models.DecimalField(max_digits=12, decimal_places=2, default=0.00,
                                       verbose_name='修改后的打手提现金额')
    xiugaitijiaoq = models.DecimalField(max_digits=12, decimal_places=2, default=0.00,
                                        verbose_name='修改前的打手提现金额')

    # 打手积分
    jifen = models.IntegerField(default=0, verbose_name='修改后的打手积分')
    yjifen = models.IntegerField(default=0, verbose_name='修改前的打手积分')

    # 打手押金
    yajin = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='修改后的打手押金')
    yyajin = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='修改前的打手押金')

    # 商家余额
    shangjiayue = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='修改后的商家余额')
    shangjiayueq = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='修改前的商家余额')

    # 管事余额
    guanshiyue = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='修改后的管事余额')
    guanshiyueq = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='修改前的管事余额')

    # 会员相关
    huiyuants = models.IntegerField(default=0, verbose_name='添加会员天数')
    huiyuan_id = models.CharField(max_length=6, null=True, blank=True, verbose_name='会员ID')

    # 其他字段
    qitashuoming = models.TextField(null=True, blank=True, verbose_name='其他说明')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'xiugaijilu'
        verbose_name = '修改记录表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"修改记录-用户{self.yonghuid}"


class DashouZengsongHuiyuan(QModel):
    """
    后台赠送会员（免费接单资格），与 Huiyuangoumai 购买会员完全分离。
    仅用于抢单/抢单池资格；不参与提现正式会员校验。
    """
    id = models.AutoField(primary_key=True, verbose_name='记录ID')
    yonghu_id = models.CharField(max_length=7, db_index=True, verbose_name='打手用户ID')
    huiyuan_id = models.CharField(max_length=6, db_index=True, verbose_name='会员ID')
    daoqi_time = models.DateTimeField(db_index=True, verbose_name='到期时间')
    song_ren = models.CharField(max_length=30, verbose_name='赠送人账号')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='赠送时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'dashou_zengsong_huiyuan'
        verbose_name = '打手赠送会员'
        verbose_name_plural = verbose_name
        unique_together = [['yonghu_id', 'huiyuan_id']]
        indexes = [
            models.Index(fields=['yonghu_id', 'huiyuan_id']),
            models.Index(fields=['yonghu_id', 'daoqi_time']),
        ]

    def __str__(self):
        return f"赠送会员-用户{self.yonghu_id}-会员{self.huiyuan_id}"


# yonghu/models.py - 新增排行榜模型
class RankingRecord(QModel):
    # id: 主键ID
    id = models.AutoField(primary_key=True, verbose_name='ID')
    
    # zhouqi: 周期类型，1=日榜，2=月榜
    zhouqi = models.IntegerField(choices=[(1, '日榜'), (2, '月榜')], verbose_name='周期类型')
    
    # tongji_date: 统计日期（日榜存具体日期，月榜存月份第一天）
    tongji_date = models.DateField(db_index=True, verbose_name='统计日期')
    
    # shenfen: 用户身份，2=打手，3=管事，4=商家（1=普通用户不统计）
    shenfen = models.IntegerField(choices=[(2, '打手'), (3, '管事'), (4, '商家')], verbose_name='用户身份')
    
    # yonghuid: 用户ID（冗余存储，避免连表查询）
    yonghuid = models.CharField(max_length=7, db_index=True, verbose_name='用户ID')
    
    # paiming: 排名（从1开始）
    paiming = models.IntegerField(verbose_name='排名')
    
    # zhizhi: 指标数值（打手：收益金额，管事：充值人数，商家：流水金额）
    zhizhi = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='指标值')
    
    # nicheng: 用户昵称
    nicheng = models.CharField(max_length=50, null=True,verbose_name='用户昵称')
    
    # avatar: 用户头像URL
    avatar = models.CharField(max_length=500, blank=True, null=True, verbose_name='头像')
    
    # chuangjian_time: 记录创建时间
    chuangjian_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'ranking_record'
        verbose_name = '排行榜记录'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['zhouqi', 'tongji_date', 'shenfen', 'paiming']),
            models.Index(fields=['yonghuid', 'zhouqi']),
            models.Index(fields=['tongji_date']),
        ]
        unique_together = [['zhouqi', 'tongji_date', 'shenfen', 'paiming']]
    
    def __str__(self):
        zhouqi_str = '日' if self.zhouqi == 1 else '月'
        shenfen_map = {2: '打手', 3: '管事', 4: '商家'}
        return f"{self.tongji_date} {zhouqi_str}榜 {shenfen_map.get(self.shenfen)} 第{self.paiming}名"


# ==================== 用户敏感数据表 ====================
class UserSensitiveData(QModel):
    """用户敏感数据表——独立存储敏感信息，不继承 gvsdsdk"""
    user_uuid = models.OneToOneField(
        'users.User',
        on_delete=models.CASCADE,
        related_name='sensitive_data',
        verbose_name='关联用户',
        db_column='user_uuid_id',
    )
    password = models.CharField(max_length=200, null=True, blank=True, verbose_name='密码')
    zhifu = models.CharField(max_length=500, null=True, blank=True, verbose_name='收款码图片')
    skzhanghao = models.CharField(max_length=11, blank=True, null=True, verbose_name='收款账号')
    shoujihao_renzheng = models.BooleanField(default=False, verbose_name='手机号是否已认证')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'user_sensitive_data'
        verbose_name = '用户敏感数据'
        verbose_name_plural = verbose_name
        indexes = [models.Index(fields=['user_uuid'])]

    def __str__(self):
        return f'敏感数据-{self.user_uuid_id}'


# ==================== 管事更换组长：配额 / 记录 ====================
class GuanshiChangeLeaderQuota(QModel):
    """管事自助更换组长次数配额（按俱乐部 + 管事 UID）"""
    club_id = models.CharField(max_length=16, db_index=True, verbose_name='俱乐部ID')
    guanshi_uid = models.CharField(max_length=7, db_index=True, verbose_name='管事UserUID')
    total_quota = models.IntegerField(default=1, verbose_name='总次数')
    used_count = models.IntegerField(default=0, verbose_name='已用次数')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'guanshi_change_leader_quota'
        verbose_name = '管事换组长配额'
        verbose_name_plural = verbose_name
        unique_together = [['club_id', 'guanshi_uid']]
        indexes = [
            models.Index(fields=['club_id', 'guanshi_uid']),
        ]

    @property
    def remain_quota(self):
        return max(0, int(self.total_quota or 0) - int(self.used_count or 0))


class GuanshiChangeLeaderLog(QModel):
    """管事更换组长记录"""
    club_id = models.CharField(max_length=16, db_index=True, verbose_name='俱乐部ID')
    guanshi_uid = models.CharField(max_length=7, db_index=True, verbose_name='管事UserUID')
    guanshi_name = models.CharField(max_length=50, blank=True, default='', verbose_name='管事昵称')
    old_zuzhang_uid = models.CharField(max_length=7, blank=True, default='', verbose_name='原组长UID')
    new_zuzhang_uid = models.CharField(max_length=7, db_index=True, verbose_name='新组长UID')
    new_invite_code = models.CharField(max_length=40, blank=True, default='', verbose_name='提交的邀请码')
    source = models.CharField(max_length=20, default='miniapp', verbose_name='来源')  # miniapp / admin
    operator = models.CharField(max_length=64, blank=True, default='', verbose_name='操作人')
    CreateTime = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='更换时间')

    class Meta:
        db_table = 'guanshi_change_leader_log'
        verbose_name = '管事换组长记录'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['club_id', 'guanshi_uid', '-CreateTime']),
        ]


# === 业务用户模型注册 ===
# 导入业务子类，使 Django app registry 注册具体 User 模型（users.User）。
# 放在文件末尾以避免循环导入：此时本模块所有类已定义完毕。
from users.business_models import User as _BusinessUser  # noqa: E402,F401


