from django.db import models
from apps.system.models import User
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

class Category(models.Model):
    name = models.CharField(max_length=50, verbose_name="分类名称")
    color = models.CharField(max_length=50, verbose_name="颜色类名", help_text="例如: bg-blue-100 text-blue-600")
    
    class Meta:
        verbose_name = "课程分类"
        verbose_name_plural = verbose_name
        
    def __str__(self):
        return self.name

class Project(models.Model):
    title = models.CharField(max_length=100, verbose_name="项目名称")
    category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="所属分类", related_name="projects")
    image = models.URLField(verbose_name="封面图片URL", default="https://images.unsplash.com/photo-1526379095098-d400fd0bf935")
    detail = models.TextField(verbose_name="项目详情", blank=True, default="")
    students = models.IntegerField(default=0, verbose_name="学习人数")
    rating = models.DecimalField(max_digits=3, decimal_places=1, default=5.0, verbose_name="评分")
    duration = models.CharField(max_length=20, verbose_name="时长", default="4 周")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "项目课程"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

class Coupon(models.Model):
    STATUS_CHOICES = (
        ('available', '可领取'),
        ('claimed', '已领取'),
        ('used', '已使用'),
        ('expired', '已过期'),
    )
    ISSUE_CHOICES = (
        ('manual', '手动发放'),
        ('registration', '注册赠送'),
        ('project', '指定项目'),
    )
    
    amount = models.CharField(max_length=10, verbose_name="面额")
    unit = models.CharField(max_length=10, verbose_name="单位", default="元")
    title = models.CharField(max_length=50, verbose_name="优惠券标题")
    desc = models.CharField(max_length=100, verbose_name="描述")
    expiry = models.DateField(verbose_name="过期时间")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='available', verbose_name="状态")
    issue_type = models.CharField(max_length=20, choices=ISSUE_CHOICES, default='manual', verbose_name="发放类型")
    applicable_projects = models.ManyToManyField(Project, blank=True, related_name="coupons", verbose_name="适用项目")
    
    # UI样式字段
    color = models.CharField(max_length=100, verbose_name="渐变色类名", default="from-blue-500 to-cyan-400")
    bgStart = models.CharField(max_length=50, verbose_name="背景起始色", default="from-blue-50")
    bgEnd = models.CharField(max_length=50, verbose_name="背景结束色", default="to-cyan-50")
    shadow = models.CharField(max_length=50, verbose_name="阴影类名", default="shadow-blue-100")

    class Meta:
        verbose_name = "优惠券"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

class Banner(models.Model):
    image = models.URLField(verbose_name="图片URL")
    project = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="关联项目")
    link = models.CharField(max_length=200, blank=True, null=True, verbose_name="跳转链接")
    sort_order = models.IntegerField(default=0, verbose_name="排序")
    is_active = models.BooleanField(default=True, verbose_name="是否启用")

    class Meta:
        verbose_name = "轮播图"
        verbose_name_plural = verbose_name
        ordering = ['sort_order']

    def __str__(self):
        return f"Banner {self.id}"

class Student(models.Model):
    name = models.CharField(max_length=50, verbose_name="学员姓名")
    phone = models.CharField(max_length=20, verbose_name="联系电话")
    age = models.IntegerField(verbose_name="年龄", null=True, blank=True)
    education = models.CharField(max_length=50, verbose_name="学历", null=True, blank=True)
    address = models.CharField(max_length=200, verbose_name="地址", null=True, blank=True)
    avatar = models.URLField(verbose_name="头像URL", default="https://images.unsplash.com/photo-1535713875002-d1d0cf377fde")
    
    # 统计数据
    learning_count = models.IntegerField(default=0, verbose_name="在学课程数")
    coupon_count = models.IntegerField(default=0, verbose_name="优惠券数")
    study_hours = models.IntegerField(default=0, verbose_name="学习时长(小时)")
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="录入时间")

    class Meta:
        verbose_name = "学员信息"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

class StudentCoupon(models.Model):
    STATUS_CHOICES = (
        ('assigned', '已分配'),
        ('used', '已使用'),
        ('expired', '已过期'),
    )
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="student_coupons", verbose_name="学员")
    coupon = models.ForeignKey(Coupon, on_delete=models.CASCADE, related_name="assignments", verbose_name="优惠券")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='assigned', verbose_name="状态")
    assigned_at = models.DateTimeField(auto_now_add=True, verbose_name="分配时间")
    used_at = models.DateTimeField(null=True, blank=True, verbose_name="使用时间")

    class Meta:
        verbose_name = "学员优惠券"
        verbose_name_plural = verbose_name
        ordering = ['-assigned_at']

    def __str__(self):
        return f"{self.student.name} - {self.coupon.title}"

@receiver(post_save, sender=StudentCoupon)
def update_student_coupon_count_on_save(sender, instance, created, **kwargs):
    student = instance.student
    student.coupon_count = StudentCoupon.objects.filter(student=student).count()
    student.save(update_fields=['coupon_count'])

@receiver(post_delete, sender=StudentCoupon)
def update_student_coupon_count_on_delete(sender, instance, **kwargs):
    student = instance.student
    student.coupon_count = StudentCoupon.objects.filter(student=student).count()
    student.save(update_fields=['coupon_count'])

class Activity(models.Model):
    title = models.CharField(max_length=100, verbose_name="活动名称")
    cover_image = models.URLField(verbose_name="封面图片", default="https://images.unsplash.com/photo-1511632765486-a01980e01a18")
    description = models.TextField(verbose_name="活动详情")
    start_time = models.DateTimeField(verbose_name="开始时间")
    end_time = models.DateTimeField(verbose_name="结束时间")
    location = models.CharField(max_length=200, verbose_name="活动地点")
    max_participants = models.IntegerField(default=50, verbose_name="最大报名人数")
    current_participants = models.IntegerField(default=0, verbose_name="当前报名人数")
    status = models.CharField(max_length=20, choices=(('upcoming', '即将开始'), ('ongoing', '进行中'), ('ended', '已结束')), default='upcoming', verbose_name="状态")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "演出活动"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

class Showcase(models.Model):
    title = models.CharField(max_length=100, verbose_name="节目名称")
    description = models.TextField(verbose_name="节目介绍", blank=True)
    media_type = models.CharField(max_length=10, choices=(('image', '图片'), ('video', '视频')), default='image', verbose_name="媒体类型")
    media_url = models.URLField(verbose_name="媒体链接")
    cover_image = models.URLField(verbose_name="封面图片", blank=True, null=True)
    related_activity = models.ForeignKey(Activity, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="关联活动")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="发布时间")

    class Meta:
        verbose_name = "精彩节目"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

class Exam(models.Model):
    title = models.CharField(max_length=100, verbose_name="考试名称")
    description = models.TextField(verbose_name="考试说明")
    exam_date = models.DateTimeField(verbose_name="考试时间")
    level = models.CharField(max_length=50, verbose_name="考级等级")
    fee = models.DecimalField(max_digits=8, decimal_places=2, default=0.00, verbose_name="报名费")
    deadline = models.DateTimeField(verbose_name="报名截止时间")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="发布时间")

    class Meta:
        verbose_name = "考级报名"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

class StudentHonor(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="honors", verbose_name="学员")
    title = models.CharField(max_length=100, verbose_name="荣誉标题")
    image = models.URLField(verbose_name="证书/奖状图片", blank=True, null=True)
    date_awarded = models.DateField(verbose_name="获奖日期")
    description = models.TextField(verbose_name="荣誉描述", blank=True)

    class Meta:
        verbose_name = "个人荣誉"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.student.name} - {self.title}"

class StudentLevel(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="levels", verbose_name="学员")
    level = models.CharField(max_length=50, verbose_name="获得等级")
    exam = models.ForeignKey(Exam, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="关联考试")
    date_passed = models.DateField(verbose_name="通过日期")
    certificate_image = models.URLField(verbose_name="证书图片", blank=True, null=True)

    class Meta:
        verbose_name = "考级证书"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.student.name} - {self.level}"

class CourseRegistration(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="course_registrations", verbose_name="学员")
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="registrations", verbose_name="课程")
    status = models.CharField(max_length=20, choices=(('pending', '待确认'), ('confirmed', '已报名'), ('cancelled', '已取消')), default='pending', verbose_name="状态")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="报名时间")

    class Meta:
        verbose_name = "课程报名"
        verbose_name_plural = verbose_name

class ActivityRegistration(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="activity_registrations", verbose_name="学员")
    activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name="registrations", verbose_name="活动")
    status = models.CharField(max_length=20, choices=(('pending', '待确认'), ('confirmed', '已报名'), ('cancelled', '已取消')), default='pending', verbose_name="状态")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="报名时间")

    class Meta:
        verbose_name = "活动报名"
        verbose_name_plural = verbose_name

class ExamRegistration(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="exam_registrations", verbose_name="学员")
    exam = models.ForeignKey(Exam, on_delete=models.CASCADE, related_name="registrations", verbose_name="考试")
    status = models.CharField(max_length=20, choices=(('pending', '待缴费'), ('paid', '已缴费'), ('cancelled', '已取消')), default='pending', verbose_name="状态")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="报名时间")

    class Meta:
        verbose_name = "考级报名记录"
        verbose_name_plural = verbose_name

