# coding=utf-8
from __future__ import unicode_literals
import json
import math
import datetime
from celery import shared_task

from doctor.views.budan import get_all_doctors
from hippo.models import Merchant
from pay.tool.support_tool import send_email
from django.conf import settings
from django.db import transaction
from gm_types.gaia import ORDER_STATUS, MAIDAN_STATEMENT_STATUS
from api.models import Doctor
from django.db.models import Q
from maidan.models.statement import MaidanStatement, MaidanOrderStatementRelationship
from maidan.models.order import MaidanOrder
from pay.tool.time_tool import DatetimeTool
from api.tool.log_tool import logging_exception


def _send_statement_alert(total_count, failed_count):
    dt_str = datetime.datetime.now().strftime("%Y-%m")
    subject = '{dt_str} 月 医生买单对账单详情'.format(dt_str=dt_str)
    body = '总计 {total_count} 个\n失败 {failed_count} 个'.format(
        total_count=total_count,
        failed_count=failed_count
    )
    send_email(
        from_email=settings.PAY_EMAIL_USER,
        to_email_list=settings.PAY_EMAIL_STATEMENT_ALERT_LIST,
        subject=subject,
        body=body
    )


def _send_error_detail(doctor_id, error_msg):
    dt_str = datetime.datetime.now().strftime("%Y-%m")
    subject = '{dt_str} 月 {doctor_id} 医生 买单对账单生成错误'.format(
        dt_str=dt_str,
        doctor_id=doctor_id
    )
    body = error_msg
    send_email(
        from_email=settings.PAY_EMAIL_USER,
        to_email_list=settings.PAY_EMAIL_STATEMENT_ALERT_LIST,
        subject=subject,
        body=body
    )


def create_one_statement(doctor, last_month_dt):
    print doctor.id, doctor.name, last_month_dt, doctor.user.id
    statement_date = last_month_dt.strftime("%Y%m")
    last_month_dt = DatetimeTool(last_month_dt)
    with transaction.atomic():
        time_query = Q(payment_time__gte=last_month_dt.get_first_day_month()) & Q(
            payment_time__lte=last_month_dt.get_last_day_month())
        # 真医生
        # 当月尚未生成此医生订单
        assert doctor.user is not None
        try:
            return MaidanStatement.objects.get(doctor=doctor, statement_date=statement_date)
        except MaidanStatement.DoesNotExist:
            pass
        statement = MaidanStatement.create(doctor=doctor, statement_date=statement_date)
        # 已支付 # 未结算 # 当月
        total_discount = original_amount = settle_amount = 0
        doctor_ids, _ = get_all_doctors(doctor)
        orders = MaidanOrder.objects.filter(
            status=ORDER_STATUS.PAID, doctor_id__in=doctor_ids, is_settled=False
        ).filter(time_query)
        # print orders.query
        for order in orders:
            settle_amount += order.settle_price_cent  # 结算金额总额
            original_amount += order.payment_cent  # 实际支付总额
            total_discount += order.discount_cent
            MaidanOrderStatementRelationship.objects.create(statement=statement, order=order)

        statement.original_amount_cent = original_amount
        statement.settle_amount_cent = int(settle_amount / 100) * 100
        total_discount = int(total_discount) / 100
        statement.total_discount = math.ceil(total_discount)
        if not orders.count():
            statement.status = MAIDAN_STATEMENT_STATUS.VOID
        statement.save()


@shared_task
def create_all_statements(last_month_dt):
    # merchants = Doctor.objects.filter(is_merchant=True, user_id__isnull=False)
    merchants = Merchant.objects.filter(is_online=True, doctor__user_id__isnull=False)
    total_count = failed_count = 0
    dt = DatetimeTool()
    # last_month_dt = dt.get_first_day_month(d_months=-1)
    for merchant in merchants:
        total_count += 1
        create_one_statement(merchant.doctor, last_month_dt)
        # _send_error_detail(doctor.id, error_msg)
    return total_count, failed_count
