from django.db import models
from django.utils import timezone
from django.utils.timezone import localtime


# Create your models here.

class Order(models.Model):
    # 本实验orderID由系统生成，这边缺省默认主键id
    store = models.ForeignKey(to='store.Store', on_delete=models.CASCADE)
    user = models.ForeignKey(to='user.User', on_delete=models.CASCADE)
    sumPrice = models.DecimalField('订单总金额', max_digits=10, decimal_places=2)
    shippingAddress = models.TextField('发货地址', default='')
    receivingAddress = models.TextField('收货地址', default='')

    valid = models.BooleanField('订单是否有效', default=True)
    paid = models.BooleanField('是否已付款', default=False)
    state = models.CharField('订单状态', max_length=10, default='未付款')
    complete = models.BooleanField('交易是否结束', default=False)

    generateDate = models.DateTimeField('订单生成时间', auto_now_add=True)
    paymentDate = models.DateTimeField('订单付款时间', null=True)
    shippingDate = models.DateTimeField('订单发货时间', null=True)
    completeDate = models.DateTimeField('订单完成时间', null=True)

    class Meta:
        db_table = 'order'

    def info_simple_json(self):
        return {
            'order_id': self.id,
            'user_id': self.user.username,
            'store_id': self.store.storeName,
            'sum_price': self.sumPrice,
            'paid': self.paid,
            'state': self.state,
            'generate_date': localtime(self.generateDate).strftime("%Y-%m-%d %H:%M:%S") if self.generateDate else '',
        }

    def info_json(self):
        return {
            'order_id': self.id,
            'user_id': self.user.username,
            'store_id': self.store.storeName,
            'state': self.state,
            'sum_price': self.sumPrice,
            'shipping_address': self.shippingAddress,
            'receiving_address': self.receivingAddress,
            'generate_date': localtime(self.generateDate).strftime("%Y-%m-%d %H:%M:%S") if self.generateDate else '',
            'payment_date': localtime(self.paymentDate).strftime("%Y-%m-%d %H:%M:%S") if self.paymentDate else '',
            'shipping_date': localtime(self.shippingDate).strftime("%Y-%m-%d %H:%M:%S") if self.shippingDate else '',
            'complete_date': localtime(self.completeDate).strftime("%Y-%m-%d %H:%M:%S") if self.completeDate else '',
            'books': [{
                'book_id': book.book.bookID,
                'title': book.title,
                'count': book.count,
                'books_price': book.booksPrice,
            } for book in OrderBook.objects.filter(order=self)]
        }


class OrderBook(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    book = models.ForeignKey(to='store.Book', on_delete=models.CASCADE)
    title = models.CharField('书名', max_length=50)
    count = models.IntegerField('书本数量', default=1)
    booksPrice = models.DecimalField('书本总金额', max_digits=10, decimal_places=2)

    class Meta:
        db_table = 'orderbook'
