# -*- coding: UTF-8 -*-
import tablib
from django.core.management import BaseCommand
from .utils import get_mail
from pay.models import Statement
from maidan.models import MaidanStatement
from gm_types.trade import STATEMENT_STATUS
from gm_types.gaia import MAIDAN_STATEMENT_STATUS


def tablib_create(statements, body, is_normal=True):
    error_message = ''
    dt_result = tablib.Dataset()
    dt_result.headers = [
        u'医生ID', u'结算对象', u'结算周期', u'结算金额', u'结算状态',
        u'开户银行', u'户名', u'账号'
    ]
    print 'start'
    for statement in statements.iterator():
        try:
            x = (
                statement.doctor_id,
                statement.doctor.name,
                statement.statement_date,
                statement.settle_amount if is_normal else statement.settle_amount_cent/100,
                STATEMENT_STATUS.getDesc(statement.status) if is_normal else MAIDAN_STATEMENT_STATUS.getDesc(statement.status),
                statement.account.bank if is_normal else statement.doctor.merchant.account.bank,
                statement.account.account_name if is_normal else statement.doctor.merchant.account.account_name,
                u' {}'.format(statement.account.account_number if is_normal else statement.doctor.merchant.account.account_number),
            )
            dt_result.append(x)
            print statement.id
        except Exception as e:
            message = '{},{}'.format(statement.id, e.message)
            print message
            error_message += message + '\n'
            continue
    get_mail(u'{}.xlsx'.format(body), body, u'chenfeifei@gmei.com', dt_result.xlsx).send()
    get_mail(u'{}.csv'.format(body), body, u'chenfeifei@gmei.com', dt_result.csv).send()
    get_mail(u'{}_error.txt'.format(body), u'{}_error'.format(body), u'chenfeifei@gmei.com', error_message).send()
    print 'end'


class Command(BaseCommand):
    """
        python manage.py dump_20170705_statement
    """

    def handle(self, *args, **options):
        statements_1 = Statement.objects.filter(status__in=[STATEMENT_STATUS.CHECKED, STATEMENT_STATUS.DEFEAT],
                                                statement_date__lt=201705)
        tablib_create(statements_1, u'5月份以前后台状态为医生已确认财务打款失败')
        statements_2 = Statement.objects.filter(status=STATEMENT_STATUS.SETTLED, statement_date=201705)
        tablib_create(statements_2, u'5月份已结算')
        statements_3 = Statement.objects.filter(status=STATEMENT_STATUS.SETTLED,
                                                updated_at__range=['2017-05-01', '2017-07-05'])
        tablib_create(statements_3, u'5月1日至7月5日后台对账单标记已结算的明细列表')
        maidan_statements = MaidanStatement.objects.filter(status=MAIDAN_STATEMENT_STATUS.SETTLED,
                                                           updated_at__range=['2017-05-01', '2017-07-05'])
        tablib_create(maidan_statements, u'5月1日至7月5日后台买单对账单标记已结算的明细列表', False)
        print u'ALL DONE!'
