# -*- coding: UTF-8 -*-

import datetime
from celery import shared_task
from api.models import Order
from hippo.models import Doctor
from api.models import ORDER_STATUS
from api.tool.datetime_tool import add_month
from rpc.tool.queryset_tool import big_qs_iter
from hera.utils import get_mail_instance


@shared_task
def check_order_merchant(month=None):
    # 检查当月验证订单的医生是否具有有效商户
    if month is None:
        month = datetime.date.today()

    month_first = datetime.date(month.year, month.month, 1)
    next_month_first = add_month(month_first, 1)
    time_range = [month_first, next_month_first]
    orders = Order.objects.filter(
        status=ORDER_STATUS.USED, is_settled=False,
        validate_time__range=time_range,
    )
    user_ids = set(orders.values_list('operate_user_id', flat=True))
    doctors = Doctor.objects.filter(user_id__in=user_ids)
    msgs = []
    for d in big_qs_iter(doctors, trace=True):
        err_msg = ''
        if d.is_merchant:
            continue
        if not d.is_merchant and not d.allow_hospital_agent:
            # 不是商户，且未托管
            err_msg = u'不是商户，且未托管'
        else:
            mch_doc = d.merchant_doctor
            if not mch_doc:
                # 机构管理者不存在
                err_msg = u'机构管理者不存在'
            else:
                if not mch_doc.is_merchant:
                    # 机构管理者不是商户
                    err_msg = u'机构管理者不是商户'
                else:
                    continue

        if err_msg:
            msg = u'{} {} {}'.format(d.id, d.name, err_msg)
            msgs.append(msg)
            print msg

    if msgs:
        sub = u'订单医生的商户检查'
        to_list = ['zhongchengyang@igengmei.com', 'yilingxiao@igengmei.com',
                   'lvguowei@igengmei.com', 'pk@igengmei.com', 'lipeng@igengmei.com']
        mail = get_mail_instance(sub, u'\n'.join(msgs), to_list)
        mail.send()
