#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   zhangxiaolin
#   E-mail  :   petelin1120@gmail.com
#   Date    :   17/11/1 11:53
#   Desc    :   ...
from __future__ import unicode_literals

from celery import shared_task
from django.conf import settings
from gm_types.trade import STATEMENT_STATUS

from maidan.models import MaidanStatement
from pay.models import Statement
from pay.models.statementall import StatementAll
from pay.models.statementalloperation import CreateOp
from pay.tool.support_tool import send_email
from api.models import Doctor
from pay.tool.time_tool import DatetimeTool
from api.tool.log_tool import logging_exception
from maidan.tasks import statement_task
from pay.tasks import statement_task as service_statement_task


def create_one_statement(merchant, last_month_dt):
    statement_date = last_month_dt.strftime("%Y%m")
    assert merchant.user is not None
    try:
        statement = StatementAll.objects.get(doctor=merchant, statement_date=statement_date)
        return statement
    except StatementAll.DoesNotExist:
        pass
    service_statement = Statement.objects.get(doctor=merchant, statement_date=statement_date)
    maidan_statement = MaidanStatement.objects.get(doctor=merchant, statement_date=statement_date)
    statement = StatementAll.objects.create(doctor=merchant, statement_date=statement_date,
                                            status=STATEMENT_STATUS.APPLIED,
                                            service_statement=service_statement,
                                            maidan_statement=maidan_statement)
    CreateOp(statement).do()
    return statement


@shared_task
def create_all_statements(before_m=1):
    """确保该任务可以重复执行"""
    last_month_dt = DatetimeTool().get_first_day_month(d_months=-before_m)
    print last_month_dt
    # 生成买单结算单
    m_total_count, m_failed_count = statement_task.create_all_statements(last_month_dt)
    # 生成美购结算单
    s_total_count, s_failed_count = service_statement_task.create_all_statements(last_month_dt)

    # create total statement
    merchants = Doctor.objects.filter(is_merchant=True, user_id__isnull=False)
    total_count = failed_count = 0
    for merchant in merchants:
        total_count += 1
        statementall = create_one_statement(merchant, last_month_dt)

    # send mail
    subject = "{}月医生总结算单".format(last_month_dt)
    body = "美购对账单总共{}, 失败{}.买单对账单总共{}, 失败{}, 总对账单总共{}, 失败{}".format(
        s_total_count, s_failed_count,
        m_total_count, m_failed_count,
        total_count, failed_count
    )
    send_email(
        from_email=settings.PAY_EMAIL_USER,
        to_email_list=settings.PAY_EMAIL_STATEMENT_ALERT_LIST,
        subject=subject,
        body=body
    )
