from django.db import models, transaction
from apps.utils.models import CommonADModel, BaseModel, CommonBDModel
from apps.system.models import User
from django.core.validators import RegexValidator
from datetime import datetime
from rest_framework.exceptions import ParseError
# Create your models here.


MTASK_CREATED = 10
MTASK_ASSGINED = 20
MTASK_STOP = 34
MTASK_SUBMIT = 40
MTASK_STATES = (
        (MTASK_CREATED, '创建中'),
        (MTASK_ASSGINED, '已下达'),
        (MTASK_STOP, '已停止'),
        (MTASK_SUBMIT, '已提交')
    )
phone_validator = RegexValidator(r'^1[3456789]\d{9}$', '手机号码格式不正确')


class Mroom(CommonADModel):
    """TN: 会议室基本信息"""
    name = models.CharField('会议室名称', max_length=50, unique=True)
    location = models.CharField('位置', max_length=100)
    capacity = models.PositiveIntegerField('容纳人数')


class MroomBooking(CommonBDModel):
    """TN: 会议室预定信息"""
    # belong_dept 是预定部门
    title = models.CharField('会议主题', max_length=100)
    ticket = models.ForeignKey('wf.ticket', verbose_name='关联会议室',
                               on_delete=models.SET_NULL, related_name='mrooms_ticket', null=True, blank=True, db_constraint=False)
    note = models.TextField('备注', null=True, blank=True)
    participant_count = models.PositiveIntegerField('参会人数', default=0)
    key_participants = models.TextField("主要参会领导", null=True, blank=True)


class MroomSlot(BaseModel):
    """TN: 会议室时段"""
    mroom = models.ForeignKey(Mroom, on_delete=models.CASCADE, related_name="slot_m")
    booking = models.ForeignKey(MroomBooking, on_delete=models.CASCADE, related_name="slot_b")
    mdate = models.DateField('会议日期', db_index=True)
    slot = models.PositiveIntegerField('时段', help_text='0-47')
    is_inuse = models.BooleanField('是否占用', default=True)


class VehicleReg(CommonADModel):
    """TN: 车辆台账"""
    name = models.CharField('车辆名称', max_length=50)
    brand = models.CharField('品牌', max_length=50, null=True, blank=True)
    plate = models.CharField('车牌号', max_length=50)
    km = models.PositiveIntegerField('行驶里程', default=0)

class VehicleUse(CommonBDModel):
    """TN: 用车记录"""
    location = models.CharField('出发地点', null=True, blank=True, max_length=100)
    via = models.CharField('途经地点', null=True, blank=True, max_length=100)
    destination = models.CharField('到达地点', null=True, blank=True, max_length=100)
    start_km = models.PositiveIntegerField('出发公里数', null=True, blank=True)
    end_km = models.PositiveIntegerField('归还公里数', default=0)
    actual_km = models.PositiveIntegerField('实际行驶公里数', editable=False)
    is_city = models.BooleanField('是否市内用车', default=True)
    reason = models.CharField('用车事由', max_length=100)
    reception = models.CharField('接待人', max_length=50, blank=True, null=True)
    ticket = models.ForeignKey('wf.ticket', verbose_name='关联工单',
                               on_delete=models.SET_NULL, related_name='vehicle_ticket', null=True, blank=True, db_constraint=False)
    def save(self, *args, **kwargs):
        if self.start_km is not None:
            self.start_km = int(self.start_km)
        if self.end_km is not None:
            self.end_km = int(self.end_km)
            if self.start_km <= self.end_km:
                self.actual_km = self.end_km - self.start_km
            else:
                raise ParseError(f'归还公里数不能小于出发公里数, 出发公里数组为 {self.start_km} km')
        else:
            self.actual_km = 0
        return super().save(*args, **kwargs)

class VehicleSlot(BaseModel):
    vehreg = models.ForeignKey(VehicleReg, on_delete=models.CASCADE, related_name="slot_record")
    vehicle_use = models.ForeignKey(VehicleUse, on_delete=models.CASCADE, related_name="slot_vehicle")
    vdate = models.DateField('使用日期', db_index=True)
    slot = models.PositiveIntegerField('时段', help_text='0-47')
    is_inuse = models.BooleanField('是否占用', default=True)

class LendingSeal(CommonBDModel):
    """TN: 印章外出用印信息"""

    seal = models.JSONField('印章信息',default=list ,help_text='[公章，法人章，财务章，合同章，业务章，其他章]')
    seal_other = models.CharField('其他印章', max_length=50, blank=True, null=True)
    filename = models.TextField('文件名称')
    file = models.TextField('文件内容')
    file_count = models.PositiveIntegerField('用印份数')
    is_lending= models.BooleanField('是否借出', default=False)
    contacts = models.CharField('联系方式', max_length=50, validators=[phone_validator], blank=True, null=True)
    lending_date = models.DateField('借出日期', blank=True, null=True)
    return_date = models.DateField('拟归还日期', blank=True, null=True)
    actual_return_date = models.DateField('实际归还日期', blank=True, null=True)
    reason = models.CharField('借用理由', max_length=100,  blank=True, null=True)
    final_file = models.CharField('终版文件路径', max_length=200, null=True, blank=True)
    ticket = models.ForeignKey('wf.ticket', verbose_name='关联工单',
                               on_delete=models.SET_NULL, related_name='seal_ticket', null=True, blank=True, db_constraint=False)
    note = models.TextField('备注', null=True, blank=True)

class FileRecord(CommonBDModel):
    """TN: 档案台账"""
    name = models.CharField('资料名称', max_length=100)
    number = models.CharField('档案编号', max_length=50, null=True, blank=True)
    counts = models.CharField('文件份数', max_length=10, null=True, blank=True)
    location = models.CharField('存放位置', max_length=100, null=True, blank=True)
    contacts = models.CharField('存档人电话',  max_length=50, validators=[phone_validator], blank=True, null=True)
    reciver = models.CharField('接收人（综合办）', max_length=50, null=True, blank=True)
    remark = models.TextField('备注', max_length=200, null=True, blank=True)

class BorrowRecord(CommonBDModel):
    """TN: 借阅、复印、查阅记录"""
    borrow_file = models.ManyToManyField(FileRecord, related_name="borrow_records")
    borrow_date = models.DateField('借阅日期',  null=True, blank=True)
    return_date = models.DateField('归还日期',  null=True, blank=True)
    count = models.PositiveIntegerField('借阅份数', null=True, blank=True)
    contacts = models.CharField('借阅人电话', max_length=50, validators=[phone_validator], null=True, blank=True)
    remark = models.JSONField('用途', default=list, help_text=str(['借阅', '复印', '查阅']))
    ticket = models.ForeignKey('wf.ticket', verbose_name='关联工单',
                               on_delete=models.SET_NULL, related_name='borrow_ticket', null=True, blank=True, db_constraint=False)


class Publicity(CommonBDModel):
    """TN: 公示栏"""
    number = models.CharField('记录编号', max_length=50, blank=True, null=True)
    title = models.CharField('送审稿件标题', max_length=100)
    participants = models.CharField('所有撰稿人', max_length=50)
    pub_dept = models.CharField('部室/研究院', null=True, blank=True, max_length=50)
    pfile = models.CharField('稿件路径', null=True, blank=True, max_length=100)
    level = models.JSONField('涉密等级', default=list, help_text=str(['重要', '一般', '非涉密']))
    content = models.JSONField('稿件内容涉及', default=list, help_text=str([
            "武器装备科研生产综合事项",
            "其它"
        ]))
    other_content = models.CharField('其它内容', max_length=100, blank=True, null=True)
    report_purpose = models.CharField('宣传报道目的', max_length=100, blank=True, null=True)
    channel = models.JSONField('发布渠道', default=list, help_text=str(['互联网', '信息平台', '官微', '公开发行物', '其它']))
    other_channel = models.CharField('其它渠道', max_length=50, blank=True, null=True)
    report_name = models.CharField('报道名称', max_length=50, blank=True, null=True)
    review = models.JSONField('第一撰稿人自审', default=list, help_text=str(['内容不涉及国家秘密和商业秘密，申请公开', '内容涉及国家秘密，申请按涉密渠道发布']), null=True,blank=True)
    dept_opinion = models.CharField('部门负责人意见', max_length=100, blank=True, null=True)
    disposal_method = models.CharField('处理方式', max_length=50, blank=True, null=True)
    secret_level = models.CharField('秘密等级', max_length=50, blank=True, null=True)
    secret_period = models.CharField('秘密期限', max_length=50, blank=True, null=True)
    dept_opinion_review = models.CharField('部门审查意见', max_length=100, blank=True, null=True)
    publicity_opinion = models.CharField('宣传报道意见', max_length=100, blank=True, null=True)
    final_file = models.CharField('终版文件路径', max_length=200, null=True, blank=True)
    ticket = models.ForeignKey('wf.ticket', verbose_name='关联工单',
                               on_delete=models.SET_NULL, related_name='publicity_ticket', null=True, blank=True, db_constraint=False)

    # 记录编号自动生成
    def save(self, *args, **kwargs):
        if not self.number:
            last_number = self.__class__.objects.filter(number__startswith=f"GXKG-{datetime.now().year}-").order_by('-number').first()
            if last_number:
                try:
                    last_num = int(last_number.number.split('-')[-1])
                except ValueError:
                    last_num = 0
            else:
                last_num =0
            # 格式化编号，带补零
            self.number = f"GXKG-{datetime.now().year}-{last_num+1:02d}"
        super().save(*args, **kwargs)







