#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   RobertDing
#   E-mail  :   robertdingx@gmail.com
#   Date    :   16/07/18 14:05:45
#   Desc    :   轮询小赢接口
#

from datetime import datetime

from celery import shared_task
from django.conf import settings

from gm_types.gaia import XIAOYING_INSTALLMENT_STATUS

from pay.models import Installment
from pay.tool.installment import Client, InstallmentError
from pay.tool.support_tool import send_email


@shared_task
def get_installment_repay_status():
    installments = Installment.objects.filter(
        first_repay_time__isnull=True,
        partner=settings.PARTNER_XY,
        status=XIAOYING_INSTALLMENT_STATUS.MONEY_SUCCESS)
    for item in installments:
        try:
            detail = Client(item.borrower.third_uid).loan_detail(item.third_loan_order_id)
        except InstallmentError:
            continue
        if not detail['repayPlanItems']:
            continue
        repay = filter(lambda x: int(x['period']) == 1, detail['repayPlanItems'])[0]
        repay_time = datetime.fromtimestamp(int(repay['planRepayDate']))
        item.first_repay_time = repay_time
        if not item.third_loan_id:
            item.third_loan_id = detail['loanId']
        item.save()


@shared_task
def monitor_xiaoying_lend_loan_callback():
    exception_status = {
        XIAOYING_INSTALLMENT_STATUS.WAIT_LEND: u'没有小赢放款回调',
        XIAOYING_INSTALLMENT_STATUS.BORROW_FAIL: u'小赢放款失败',
    }
    subject = '小赢分期确认借款状态警报'
    tmp = u'结算单ID: {}, 借款单ID: {}, 当前状态: {}'
    installments = Installment.objects.filter(
        partner=settings.PARTNER_XY, status__in=exception_status.keys())
    if not installments.exists():
        return
    body = "\n".join([
        tmp.format(x.settlement_id, x.third_loan_order_id, exception_status[x.status])
        for x in installments
    ])

    return send_email(
        from_email=settings.PAY_EMAIL_USER,
        to_email_list=settings.XIAOYING_EXCEPTION_STATUS_EMAIL_LIST,
        subject=subject,
        body=body)
