#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   zoumingzhe
#   E-mail  :   zoumingzhe@igengmei.com
#   Date    :   18/6/15 17:00
#   Desc    :   尾款支付管理
import datetime

from django.db import IntegrityError
from django.db import models, transaction
from rpc.tool.error_code import CODES, gen
from gm_types.pay import CHANNEL, SUFPAY_STATUS
from pay.tool import random_tool
from ..models import HospitalPay
from api.models import Order

def get_or_create_hospital_pay(order):
    if getattr(order, 'hospital_pay', None):
        return order.hospital_pay.id
    else:
        with transaction.atomic():
            hospital_pay_id = None
            while True:
                try:
                    hospital_pay_id = random_tool.generate_id(id_length=12)
                    hospital_pay = HospitalPay.objects.create(
                        id=hospital_pay_id,
                        order_id=order.id,
                        total_fee=int(order.hospital_payment * 100),
                        status=SUFPAY_STATUS.PAYING,
                    )
                    break
                except IntegrityError:
                    pass
        return hospital_pay_id