# coding=utf-8
from __future__ import unicode_literals, absolute_import
import json
import datetime
from django.conf import settings

from rpc.decorators import bind, bind_context
from rpc.tool.log_tool import yinuo_logger
from rpc.all import get_rpc_remote_invoker

from api.models import Order
from api.tool.user_tool import get_user_from_context
from pay.models import PolicyHolder
from pay.models import YinuoOrder
from pay.manager.purchase_manager import ConvertNotifyData


@bind('pay/insurance/yinuo_notify')
def pay_insurance_yinuo_notify(trade_data):
    trade_data = ConvertNotifyData(trade_data)
    yinuo_logger.info(trade_data)
    yinuo_id = trade_data.id
    yinuo = YinuoOrder.objects.get(yinuo_id=yinuo_id)
    yinuo.premium = int(float(trade_data.premium))
    yinuo.credential_id = trade_data.credential_id
    yinuo.confirmed_at = datetime.datetime.strptime(trade_data.confirmed_at, "%Y-%m-%d %H:%M:%S")
    yinuo.paid_at = datetime.datetime.strptime(trade_data.paid_at, "%Y-%m-%d %H:%M:%S")
    yinuo.created_at = datetime.datetime.strptime(trade_data.created_at, "%Y-%m-%d %H:%M:%S")
    yinuo.save()
    return


@bind_context('pay/insurance/policyholder', login_required=True)
def pay_insurance_plicyholder(ctx, id_card=None, name=None):
    # 这段逻辑上线之后只保留获取一诺保额的作用
    user = get_user_from_context(ctx)
    has_bought_insurance = Order.objects.filter(user=user, yinuo_order__isnull=False).exists()

    if id_card is None and name is None:  # get
        try:
            holder = PolicyHolder.objects.get(user=user)
        except PolicyHolder.DoesNotExist:
            holder = None
    if id_card and name:  # create or update
        holder, _created = PolicyHolder.objects.get_or_create(user=user)
        holder.id_card = id_card
        holder.name = name
        holder.save()

    return {
        'has_bought_insurance': has_bought_insurance,
        'id_card': holder.id_card if holder else None,
        'name': holder.name if holder else None,
        'premium': settings.YINUO_PREMIUM,
    }
