# coding=utf-8
from datetime import datetime
from django.db import transaction

from api.models import AlipayAccoutMaintenance
from rpc.decorators import bind_context
from rpc.tool.datatables import DataTable
from ..queries.alipayaccount import AlipayAccountDQ

alipayaccount_pre = 'hera/alipayaccount'


@bind_context(alipayaccount_pre + '/query')
def alipayaccount_query(ctx, options):
    """
    支付宝账号维护列表
    """
    dtobj = AlipayAccountDQ()
    return dtobj.process(**options)


@bind_context(alipayaccount_pre + '/list')
def alipayaccount_datatable(ctx, req_data):
    """
    支付宝账号维护列表
    """
    dtobj = DataTable(AlipayAccoutMaintenance)
    return dtobj.process(req_data)


@bind_context(alipayaccount_pre + '/create')
@transaction.atomic
def alipay_account(ctx, alipayaccounts):
    """
    批量添加支付宝账号信息
    :param alipayaccounts: 支付宝账号信息列表
    """
    try:
        for item in alipayaccounts:
            print (AlipayAccoutMaintenance.objects.filter(account=item['account']).count())
            if AlipayAccoutMaintenance.objects.filter(account=item['account']).count() == 0:
                AlipayAccoutMaintenance.objects.create(account=item['account'], name=item['name'])
            else:
                if AlipayAccoutMaintenance.objects.filter(account=item['account'], name=item['name']).count() == 0:
                    AlipayAccoutMaintenance.objects.filter(account=item['account']).update(
                        name=item['name'],
                        updated_time=datetime.now()
                    )
    except Exception as e:
        raise e
