# coding=utf-8
from django.db import models
from django.conf import settings
from django.utils import timezone
from apps.commodity.models import Commodity
from apps.option.models import Config, Student,Classes
from apps.upload.models import Upload
from utils.exceptions import CustomError
from apps.base import Formater
from apps.account.models import CustomerWechat
from django.contrib.auth import get_user_model
User = get_user_model()
from apps.option.models import CommodityLevel, School

class Coupon(models.Model):

    name = models.CharField(max_length=50, verbose_name='优惠券名称', unique=True, null=True)
    amount = models.BigIntegerField(verbose_name=u"优惠券金额", default=0)

    category = models.CharField(max_length=200, verbose_name='使用分类', null=True,)
    school = models.CharField(max_length=200, verbose_name='使用学校', null=True,)
    create_time = models.DateTimeField(verbose_name=u"创建时间", default=timezone.now)
    create_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u'创建人', related_name='coupon_create_user',
                             on_delete=models.PROTECT, editable=False)
    begin_date = models.DateField(verbose_name=u"开始时间", null=True)
    end_date = models.DateField(verbose_name=u"结束时间", null=True)
    enable = models.BooleanField(verbose_name=u"是否在用", default=True)
    count = models.IntegerField(verbose_name=u"使用数量", default=0)

    class Meta:
        db_table = "coupon"
        verbose_name = u"优惠券"
        ordering = ('-id',)
        default_permissions = ()
        permissions = [
            ('view_coupon', u'查看'),
            ('add_coupon', u'添加修改'),
        ]

class Pay(models.Model):
    WAIT = 0
    PAY = 1
    UNDO = 2
    STATUS_CHOICES = (
        (WAIT, u'待付款'),
        (PAY, u'已付款'),
        (UNDO, u'已取消'),
    )
    CUSTOMER = 1
    TYPE_CHOICES = (
        (CUSTOMER, u'客户'),
    )

    pay_no = models.CharField(max_length=25, verbose_name='支付单号', unique=True, null=True)
    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, verbose_name='状态', default=WAIT)
    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, verbose_name='类别', default=CUSTOMER)
    precreate_amount = models.BigIntegerField(verbose_name=u"预支付金额")
    create_time = models.DateTimeField(verbose_name=u"创建时间", default=timezone.now)
    amount = models.BigIntegerField(verbose_name=u"支付金额", null=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u'下单人', related_name='pay_user',
                             on_delete=models.PROTECT)
    pay_time = models.DateTimeField(verbose_name=u"创建时间", null=True)

    class Meta:
        db_table = "pay"
        verbose_name = u"支付信息"
        ordering = ('-id',)
        default_permissions = ()

    def payClosed(self):
        if self.status != Pay.WAIT:
            return

        self.status = Pay.UNDO
        self.save()

    def paySuccess(self, pay_amount):
        if self.status != Pay.WAIT:
            return

        self.status = Pay.PAY
        self.amount = Formater.formatPrice(pay_amount)
        self.pay_time = timezone.now()
        self.save()
        order = Order.objects.filter(pay=self).first()
        if order:
            order.status = Order.FINISH
            order.actual_amount = self.amount
            order.save()
            if order.coupon:
                order.coupon.count += 1
                order.coupon.save()

    @staticmethod
    def getByNo(pay_no):
        instance = Pay.objects.filter(pay_no=pay_no).first()
        if not instance:
            raise CustomError(u'未找到相应的支付单号！')
        return instance

    # 小程序支付
    @staticmethod
    def wechatAppPay(user, amount, type=1):
        item = Pay._precreatePay(
            user,
            amount,
            type,
        )
        return item

    @staticmethod
    def _precreatePay(user, amount, type):

        pay_no = '{0}{1}'.format(user.id, timezone.now().strftime('%y%m%d%H%M%S'))
        pay = Pay.objects.create(
            pay_no=pay_no,
            status=Pay.WAIT,
            precreate_amount=amount,
            user=user,
            type=type,
        )
        return pay

class Order(models.Model):
    WAIT_PAY = 1
    FINISH = 2
    CANCEL = 3
    STATUS_CHOICES = (
        (WAIT_PAY, u'待付款'),
        (FINISH, u'已完成'),
        (CANCEL, u'已取消'),
    )

    ONLINE_PAY = 1
    PAYMENT_CHOICES = (
        (ONLINE_PAY, u'在线支付'),
    )

    no = models.CharField(max_length=50, verbose_name=u'订单号', blank=True)
    pay = models.ForeignKey(Pay, verbose_name='支付信息', on_delete=models.PROTECT, null=True, editable=False)
    coupon = models.ForeignKey(Coupon, verbose_name='优惠券', editable=False, on_delete=models.PROTECT, null=True)
    commodity = models.ForeignKey(Commodity, verbose_name='商品', on_delete=models.PROTECT, null=True)

    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, verbose_name=u"订单状态", default=WAIT_PAY)
    notes = models.CharField(max_length=500, verbose_name=u"备注", null=True)
    create_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='order_create_user', verbose_name=u"添加人",
                                    on_delete=models.PROTECT, editable=False)
    create_time = models.DateTimeField(verbose_name=u'添加时间', auto_now_add=True, editable=False)
    student = models.ForeignKey(Student, verbose_name=u'学生', related_name='customer_order_student',
                                on_delete=models.PROTECT, null=True)

    count = models.BigIntegerField(verbose_name=u'数量', default=0)
    total_amount = models.BigIntegerField(verbose_name=u'总金额', editable=False, default=0)
    coupon_deduction = models.BigIntegerField(verbose_name=u'优惠券抵扣', editable=False, default=0)
    actual_amount = models.BigIntegerField(verbose_name=u'实付金额', editable=False, default=0)

    class Meta:
        db_table = "order"
        verbose_name = u"订单管理"
        ordering = ('-id',)
        default_permissions = ()
        permissions = [
            ('view_order', u'查看'),
        ]

    def get_no(self):
        now = timezone.now()
        no = '%s%s%s' % ('C', self.create_user.id, now.strftime('%Y%m%d%H%M%S%f'))
        return no

    @staticmethod
    def get_instance_by_id(id):
        try:
            id = int(id)
        except:
            raise CustomError('无效的订单ID')
        instance = Order.objects.filter(pk=id).first()
        if not instance:
            raise CustomError('未找到对应的订单')
        return instance

class ShoppingCart(models.Model):
    commodity = models.ForeignKey(Commodity, verbose_name='产品', on_delete=models.PROTECT)
    quantity = models.PositiveIntegerField(verbose_name="数量", default=1)
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    create_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='shopping_cart_create_user',
                                    verbose_name=u"下单人",
                                    on_delete=models.PROTECT, editable=False)

    class Meta:
        db_table = "shopping_cart"
        verbose_name = "购物车"
        ordering = ['-id', ]
        default_permissions = ()
