from django.db import models
from apps.utils.models import CommonBModel, BaseModel, CommonBDModel
from apps.mtm.models import Material

# Create your models here.


class Customer(CommonBModel):
    """
    客户信息
    """
    name = models.CharField('客户名称', max_length=50, unique=True)
    address = models.CharField('详细地址', max_length=20, blank=True, null=True)
    contact = models.CharField('联系人', max_length=20)
    contact_phone = models.CharField(
        '联系电话', max_length=11, unique=True, null=True)
    description = models.CharField('描述', max_length=200, blank=True, null=True)

    class Meta:
        verbose_name = '客户信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Contract(CommonBModel):
    """
    合同信息
    """
    name = models.CharField('合同名称', max_length=100)
    number = models.CharField('合同编号', max_length=100, unique=True)
    amount = models.IntegerField('合同金额', default=0)
    customer = models.ForeignKey(Customer, verbose_name='关联客户',
                                 on_delete=models.CASCADE, related_name='contract_customer')
    sign_date = models.DateField('签订日期')
    description = models.CharField('描述', max_length=200, blank=True, null=True)

    class Meta:
        verbose_name = '合同信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Order(CommonBModel):
    """
    订单信息
    """
    ORDER_CREATE = 10
    ORDER_SUBMITED = 20
    ORDER_DOING = 30
    ORDER_DELIVERED = 40
    ORDER_STATES = (
        (10, '创建中'),
        (20, '已提交'),
        (30, '进行中'),
        (40, '已交付')
    )
    state = models.PositiveSmallIntegerField(
        '订单状态', default=ORDER_CREATE, choices=ORDER_STATES, help_text=str(ORDER_STATES))
    number = models.CharField('订单编号', max_length=100, unique=True)
    customer = models.ForeignKey(
        Customer, verbose_name='客户', on_delete=models.CASCADE)
    contract = models.ForeignKey(
        Contract, verbose_name='所属合同', null=True, blank=True, on_delete=models.SET_NULL)
    delivery_date = models.DateField('截止交货日期')
    items = models.ManyToManyField(
        Material, verbose_name='订单明细', through='sam.orderitem', blank=True)
    submit_time = models.DateTimeField('提交时间', null=True, blank=True)

    class Meta:
        verbose_name = '订单信息'
        verbose_name_plural = verbose_name


class OrderItem(BaseModel):
    """
    订单明细
    """
    order = models.ForeignKey(
        Order, verbose_name='关联订单', on_delete=models.CASCADE, related_name='item_order')
    material = models.ForeignKey(
        Material, verbose_name='所需产品', on_delete=models.CASCADE, related_name='orderitem_material')
    count = models.PositiveIntegerField('所需数量', default=1)
    delivered_count = models.PositiveIntegerField('已交货数量', default=0)
    utask = models.ForeignKey('pm.utask', verbose_name='关联生产大任务',
                              on_delete=models.SET_NULL, null=True, blank=True)
