from django.db import models
from decimal import Decimal


# Create your models here.

class User(models.Model):
    username = models.CharField('用户名', max_length=10, unique=True)
    password = models.CharField('密码', max_length=20)
    avatar = models.ImageField('头像', upload_to='avatar/', default='avatar/default.png')
    gender = models.CharField('性别', max_length=10, default='未设置')
    phoneNumber = models.CharField('手机号码', max_length=11, default='')
    email = models.EmailField('邮箱', default='')
    balance = models.DecimalField('余额', max_digits=12, decimal_places=2, default=Decimal('0.00'))
    registerDate = models.DateField('创建时间', auto_now_add=True)

    class Meta:
        db_table = 'user'

    def info_json(self):
        return {
            'user_id': self.username,
            'avatar': self.avatar.url,
            'gender': self.gender,
            'phone_number': self.phoneNumber,
            'email': self.email,
            'balance': self.balance,
            'register_date': self.registerDate,

            'address': [{
                'address_id': address.id,
                'name': address.name,
                'phone_number': address.phoneNumber,
                'address': address.address,
            } for address in Address.objects.filter(user=self)],
        }


class Address(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField('收货人姓名', max_length=20)
    phoneNumber = models.CharField('手机号码', max_length=11)
    address = models.TextField('收货地址')

    class Meta:
        db_table = 'address'
