# coding=utf-8
from django.db import models
from django.conf import settings
from django.utils import timezone
from utils.exceptions import CustomError
from apps.base import Formater
from apps.option.models import Balance
from apps.log.models import BizLog
from django.contrib.auth import get_user_model
User = get_user_model()

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

            if order.package:
                desc = '充值{}元,赠送{}元'.format(Formater.formatPriceShow(order.package.amount),
                                            Formater.formatPriceShow(order.package.give_amount))
                Balance.update_balance(order.create_user, order.package.amount+order.package.give_amount, desc)
            order.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 Package(models.Model):
    create_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='package_create_user', verbose_name=u"添加人",
                                    on_delete=models.PROTECT, editable=False)
    create_time = models.DateTimeField(verbose_name=u'添加时间', auto_now_add=True, editable=False)
    amount = models.BigIntegerField(verbose_name=u'充值金额', default=0)
    give_amount = models.BigIntegerField(verbose_name=u'赠送余额', default=0)

    class Meta:
        db_table = "package"
        verbose_name = u"套餐"
        ordering = ('-id',)
        default_permissions = ()
        permissions = [
        ]

class Order(models.Model):
    WAIT_PAY = 1
    FINISH = 2
    CANCEL = 3
    STATUS_CHOICES = (
        (WAIT_PAY, u'待付款'),
        (FINISH, u'已完成'),
        (CANCEL, 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)
    package = models.ForeignKey(Package, verbose_name='套餐', on_delete=models.PROTECT, null=True, editable=False)

    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, verbose_name=u"订单状态", default=WAIT_PAY)
    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)
    total_amount = models.BigIntegerField(verbose_name=u'总金额', default=0)
    balance_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 = [
        ]

    def get_no(self):
        now = timezone.now()
        no = '%s%s' % (self.create_user.id, now.strftime('%Y%m%d%H%M%S'))
        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

