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


class YonghuPingzheng(QModel):
    id = models.AutoField(primary_key=True, verbose_name='自增主键ID')
    yonghu = models.CharField(
        max_length=7,
        unique=True,  # 确保一个用户只有一条凭证记录
        db_index=True,
        verbose_name='关联用户ID'
    )
    zhanghao = models.CharField(max_length=50, unique=True, db_index=True, verbose_name='登录账号')
    mima = models.CharField(max_length=255, verbose_name='密码')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'yonghu_pingzheng'
        verbose_name = '用户认证凭证'
        verbose_name_plural = verbose_name


class Dianpu(QModel):
    id = models.AutoField(primary_key=True, verbose_name='店铺自增ID')
    pingzheng = models.OneToOneField(
        'shop.YonghuPingzheng',  # 同应用内可简写，但完整路径更清晰
        on_delete=models.CASCADE,
        db_index=True,
        verbose_name='关联用户凭证'
    )
    dianpu_mingcheng = models.CharField(max_length=50, verbose_name='店铺名称')
    dianpu_touxiang = models.CharField(max_length=500, null=True, blank=True, verbose_name='店铺头像URL')

    lianxi_dianhua = models.CharField(max_length=20, null=True, blank=True, verbose_name='联系电话')
    weixinhao = models.CharField(max_length=50, null=True, blank=True, verbose_name='微信号')
    zhuangtai = models.IntegerField(choices=[(0, '封禁'), (1, '正常')], default=1, verbose_name='店铺状态')
    bangding_yonghushu = models.PositiveIntegerField(default=0, verbose_name='绑定用户总数')
    erweima_url = models.CharField(max_length=500, null=True, blank=True, verbose_name='店铺二维码相对URL')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    kaiqi_shouyi_choucheng = models.BooleanField(default=False, verbose_name='是否开启店铺订单收益抽成')
    shouyi_choucheng_feilv = models.DecimalField(max_digits=5, decimal_places=4, null=True, blank=True, default=0.0000,
                                                 verbose_name='店铺订单收益抽成费率（小数，如0.1000=10%）')
    ketixian_yue = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='店铺可提现余额')
    zhengqu_zonge = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='店铺赚取总额')
    meiri_tixian_xiane = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0.00,
                                             verbose_name='店铺每日提现限额')
    kaiqi_meiri_xiane = models.BooleanField(default=False, verbose_name='是否开启每日提现限额')


    yaoqing_dianpu_id = models.PositiveIntegerField(null=True, blank=True, db_index=True,
                                                    verbose_name='邀请人店铺ID(上级)')
    fenhong_choucheng_feilv = models.DecimalField(max_digits=5, decimal_places=4, null=True, blank=True, default=0.0500,
                                                  verbose_name='上级分红抽成费率(默认5%)')
    shangji_fenhong_leiji = models.DecimalField(max_digits=12, decimal_places=2, default=0.00,
                                                verbose_name='作为上级累计获得分红')
    shangji_ketixian_fenhong = models.DecimalField(max_digits=12, decimal_places=2, default=0.00,
                                                   verbose_name='作为上级可提现分红余额')
    club_id = models.CharField(
        max_length=16, default='xq', db_index=True, verbose_name='所属俱乐部',
        help_text='店铺按俱乐部隔离；历史数据默认星阙 xq',
    )

    class Meta:
        db_table = 'dianpu'
        verbose_name = '平台商家店铺'
        verbose_name_plural = verbose_name





class DianpuMorenPeizhi(QModel):
    id = models.PositiveSmallIntegerField(primary_key=True, default=1, editable=False)
    moren_choucheng_feilv = models.DecimalField(max_digits=5, decimal_places=4, default=0.1000, verbose_name='默认订单抽成费率（小数，0.1000=10%）')
    moren_tixian_xiane = models.DecimalField(max_digits=10, decimal_places=2, default=1000.00, verbose_name='默认可提现限额')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'dianpu_moren_peizhi'
        verbose_name = '店铺默认配置'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"默认配置 - 费率:{self.moren_choucheng_feilv} 限额:{self.moren_tixian_xiane}"

    def save(self, *args, **kwargs):
        self.id = 1
        super().save(*args, **kwargs)





class DianpuShouzhiMeiriTongji(QModel):
    dianpu_id = models.PositiveIntegerField(db_index=True, verbose_name='店铺ID')
    riqi = models.DateField(db_index=True, verbose_name='统计日期')
    nian = models.PositiveSmallIntegerField(verbose_name='年份')
    yue = models.PositiveSmallIntegerField(verbose_name='月份')
    ri = models.PositiveSmallIntegerField(verbose_name='日')
    xiadan_zongliang = models.PositiveIntegerField(default=0, verbose_name='下单总量')
    xiadan_zonge = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='下单总额')
    chengjiao_zongliang = models.PositiveIntegerField(default=0, verbose_name='成交总量')
    chengjiao_zonge = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='成交总额')
    tuikuan_zongliang = models.PositiveIntegerField(default=0, verbose_name='退款总量')
    tuikuan_zonge = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='退款总额')
    shouyi_zonge = models.DecimalField(max_digits=12, 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='更新时间')

    shangji_fenhong_cishu = models.PositiveIntegerField(default=0, verbose_name='作为上级获得分红次数')
    shangji_fenhong_zonge = models.DecimalField(max_digits=12, decimal_places=2, default=0.00,
                                                verbose_name='作为上级获得分红总额')

    # ---------- 作为下级，给上级的分红记录 ----------
    shangji_id = models.PositiveIntegerField(null=True, blank=True, verbose_name='当天对应的上级店铺ID（若无则为空）')
    gei_shangji_cishu = models.PositiveIntegerField(default=0, verbose_name='给上级分红次数')
    gei_shangji_zonge = models.DecimalField(max_digits=12, decimal_places=2, default=0.00,
                                            verbose_name='给上级分红总额')


    class Meta:
        db_table = 'dianpu_shouzhi_meiri_tongji'
        verbose_name = '店铺每日收支统计'
        verbose_name_plural = verbose_name
        unique_together = [['dianpu_id', 'riqi']]
        indexes = [
            models.Index(fields=['dianpu_id', 'riqi']),
            models.Index(fields=['nian', 'yue', 'ri']),
        ]

    def __str__(self):
        return f"店铺ID:{self.dianpu_id} - {self.riqi}"

    def clean(self):
        if self.riqi:
            self.nian = self.riqi.year
            self.yue = self.riqi.month
            self.ri = self.riqi.day
        super().clean()

    def save(self, *args, **kwargs):
        self.clean()
        super().save(*args, **kwargs)



class YonghuDianpuBangding(QModel):
    id = models.AutoField(primary_key=True, verbose_name='绑定自增ID')
    yonghu = models.ForeignKey(
        'users.User',
        on_delete=models.CASCADE,
        db_column='UserUUID',
        db_index=True,
        verbose_name='用户ID'
    )
    dianpu = models.ForeignKey('Dianpu', on_delete=models.CASCADE, db_index=True, verbose_name='关联店铺ID')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'yonghu_dianpu_bangding'
        verbose_name = '用户店铺绑定关系'
        verbose_name_plural = verbose_name
        unique_together = [['yonghu', 'dianpu']]


class ShangpinLeixingDianpu(QModel):
    """
    店铺级商品类型映射表
    与公共商品类型表 ShangpinLeixing 强制关联，用于店铺自定义类型
    """
    id = models.AutoField(primary_key=True, verbose_name='类型自增ID')
    dianpu = models.ForeignKey(
        'shop.Dianpu',
        on_delete=models.CASCADE,
        db_index=True,
        verbose_name='所属店铺'
    )
    # 🔥 强制映射到公共商品类型，不可为空
    gonggong_leixing = models.ForeignKey(
        'products.ShangpinLeixing',
        on_delete=models.CASCADE,
        db_index=True,
        verbose_name='映射的公共商品类型'
    )
    jieshao = models.CharField(max_length=45, verbose_name='类型介绍')
    tupian_url = models.CharField(max_length=500, null=True, blank=True, verbose_name='类型图片URL')
    paixu = models.IntegerField(default=0, verbose_name='排序权重')
    shangjia_zhuangtai = models.BooleanField(default=True, verbose_name='是否上架')
    fengjin_zhuangtai = models.BooleanField(default=False, verbose_name='是否封禁')
    shenhe_zhuangtai = models.BooleanField(default=False, verbose_name='平台审核状态',help_text='True=审核通过，False=未审核')

    class Meta:
        db_table = 'shangdian_shangpin_leixing'
        verbose_name = '店铺商品类型映射'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['dianpu']),
            models.Index(fields=['gonggong_leixing']),
        ]

    def __str__(self):
        return f"{self.dianpu.dianpu_mingcheng} - {self.jieshao}"





class DianpuShangpinShenheShezhi(QModel):
    """点单展示 / 店铺商品审核：按俱乐部各一条。"""
    club_id = models.CharField(
        max_length=16, unique=True, default='xq', db_index=True,
        verbose_name='所属俱乐部',
    )
    kaiqi_shenhe = models.BooleanField(default=False, verbose_name='是否开启商品审核模式')
    # True=未绑店且无打手等身份只看审核专用；False=未绑店一律看正常公共商品
    zhi_kan_shenhe = models.BooleanField(default=True, verbose_name='是否只看审核商品')
    CreateTime = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    UpdateTime = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'dianpu_shangpin_shenhe_shezhi'
        verbose_name = '商品审核模式配置'
        verbose_name_plural = verbose_name
