from django.db import models
from django.db.models.base import Model
import django.utils.timezone as timezone
from django.db.models.query import QuerySet
from apps.system.models import CommonAModel, CommonBModel, Organization, User, Dict, File
from utils.model import SoftModel, BaseModel
from simple_history.models import HistoricalRecords
from apps.mtm.models import Material
from apps.pm.models import SubProductionPlan


class WareHouse(CommonAModel):
    """
    仓库信息
    """
    number = models.CharField('仓库编号', max_length=20, unique=True)
    name = models.CharField('仓库名称', max_length=20, unique=True)
    place = models.CharField('具体地点', max_length=50)
    class Meta:
        verbose_name = '仓库信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

class Inventory(BaseModel):
    """
    库存物料
    """
    material = models.ForeignKey(Material, on_delete=models.CASCADE, verbose_name='物料信息')
    count = models.IntegerField('仓库物料存量', default=0)
    warehouse = models.ForeignKey(WareHouse, on_delete=models.CASCADE, verbose_name='所在仓库')
    class Meta:
        verbose_name = '库存表'
        verbose_name_plural = verbose_name

class MaterialBatch(BaseModel):
    """
    物料批次
    """
    material = models.ForeignKey(Material, on_delete=models.CASCADE, verbose_name='物料信息')
    warehouse = models.ForeignKey(WareHouse, on_delete=models.CASCADE, verbose_name='所在仓库')
    count = models.IntegerField('存量', default=0)
    batch = models.CharField('批次号', max_length=100, null=True, blank=True)
    expiration_date = models.DateField('有效期', null=True, blank=True)
    class Meta:
        verbose_name = '库存表'
        verbose_name_plural = verbose_name



class FIFO(CommonAModel):
    """
    出入库记录
    """
    type_choices = (
        (1, '生产领料'),
        (2, '销售提货'),
        (3, '采购入库'),
        (4, '生产入库')
    )
    type = models.IntegerField('出入库类型', default=1)
    operator = models.ForeignKey(User, verbose_name='操作人', on_delete=models.CASCADE)
    subproduction_plan = models.ForeignKey(SubProductionPlan, verbose_name='关联子生产计划', on_delete=models.DO_NOTHING, null=True, blank=True)

# class FIFODetail(CommonAModel):
#     """
#     领料详细记录
#     """

class Product(CommonAModel):
    """
    具体产品
    """
    number = models.CharField('物品编号', unique=True, null=True, blank=True, max_length=50)
    material = models.ForeignKey(Material, verbose_name='物料类型', on_delete=models.CASCADE)
    warehouse = models.ForeignKey(WareHouse, on_delete=models.CASCADE, verbose_name='所在仓库')
    batch = models.CharField('所属批次号', max_length=100, null=True, blank=True)
    fifos = models.JSONField('关联出入库记录', default=list, blank=True)

    
