#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__: vv
# Date: 2019/11/7

from django.db import models
from django.db import transaction
from django.db import IntegrityError
from pay.tool import random_tool
from rpc.tool.log_tool import info_logger
from gm_types.gaia import DIRECTPAYTYPE, YIBAOPAY_STATUS


class MerchantPayOrder(models.Model):
    class Meta:
        db_table = 'pay_merchantpayorder'
        app_label = 'pay'
        verbose_name = u'商户充值订单'

    amount = models.FloatField('充值金额', default=0)
    merchant_id = models.BigIntegerField(u'商户id', null=True)
    pay_amount = models.FloatField('实际支付金额', default=0.0)
    paid_time = models.DateTimeField('支付完成时间', null=True)
    # 第三方支付商户id, 如app_id, open_id....
    third_app_id = models.CharField("商户编号/app_id", null=True, max_length=128)
    uniqueOrderNo = models.CharField('第三方交易流水号', null=True, max_length=128)
    update_time = models.DateTimeField(verbose_name=u'更新时间', auto_now=True)
    notify_data = models.TextField(null=True, verbose_name=u'支付通知信息(json)')
    id = models.CharField(max_length=128, verbose_name=u'充值订单id', primary_key=True)
    create_time = models.DateTimeField(verbose_name=u'订单创建时间', auto_now_add=True)
    status = models.IntegerField('支付状态', choices=YIBAOPAY_STATUS, default=YIBAOPAY_STATUS.NOT_PAY)
    paytype = models.IntegerField('支付方式', choices=DIRECTPAYTYPE, default=DIRECTPAYTYPE.BUSINESS_ONLINE_PAY)

    @staticmethod
    def create_merchantorder(merchant_id):
        while True:
            new_id = random_tool.generate_id(id_length=12)
            try:
                with transaction.atomic():
                    merchant_pay_order = MerchantPayOrder.objects.create(
                        id=new_id,
                        merchant_id=merchant_id
                    )
                    return merchant_pay_order
            except IntegrityError:
                info_logger.warning("MerchantPayOrder Create Fail, new_id: " + new_id)
                pass

