#coding=utf-8
from django.contrib.auth.models import User
from django.core.management import BaseCommand
from openpyxl import load_workbook

from api.models import Order, gen, CODES, ORDER_STATUS, GROUPBUY_STATUS, Doctor
from api.view.order import validate_order, _send_notification_message
from hippo.utils import merchant_doctors
from services.doctor_notify_service import DoctorNotifyService


class Command(BaseCommand):
    """
    批量验证订单
    python manage.py batch_validate_orders
    """
    def handle(self, *args, **options):
        workbook = load_workbook('./yishengyue_orders_validate.xlsx', read_only=True, data_only=True)
        for item in workbook['validate_order']:
            order_id = item[0].value
            doctor_id = item[10].value
            print(order_id, doctor_id)
            """添加refound 为了确定来源,退款和验证都调用这个接口,只有退款才需要减少退款单小数点"""
            # user = get_user_from_context(ctx)
            # doctor = Doctor.objects.get(user=user)
            try:
                order = Order.objects.get(id=order_id)
                """
                获取对应的doctor和user
                """
                doctor = Doctor.objects.get(id=doctor_id)
                user = User.objects.get(id=doctor.user_id)
            except Order.DoesNotExist:
                continue

            # if order.password != password:
            #     return gen(CODES.ORDER_VALIDATE_FAILED)
            #
            # elif password and len(password) == 10:
            #     try:
            #         order = Order.objects.get(password=password)
            #     except Order.DoesNotExist:
            #         return gen(CODES.ORDER_VALIDATE_FAILED)
            # else:
            #     return gen(CODES.ORDER_VALIDATE_FAILED)

            if order.service.doctor != doctor:
                if merchant_doctors(doctor.id) is None or (order.service.doctor not in merchant_doctors(doctor.id)):
                     continue
            if order.validated:
                continue

            if order.status == ORDER_STATUS.REFUNDED:
                continue

            can_validate_groupbuy_status = (GROUPBUY_STATUS.NOT_GROUPBUY, GROUPBUY_STATUS.GROUPBUY_SUCCESSED)
            if order.groupbuy_status not in can_validate_groupbuy_status:
                continue

            validate_order(order, user)
            _send_notification_message(order, doctor)

            ss = DoctorNotifyService.get_service(order.service.doctor_id)
            ss.notify_verify_order(order)

            # 数据埋点, http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=23892080
            # ctx.logger.app(**validate_order_log(order_id=order.id))

            # 更改订单是否已读状态 用于订单列表红点的展示
            try:
                order.read = False
                order.save()
            except:
                pass

            # add 医生版实时小红点数量
            # if is_refund:  # 如果来自于退款验证则通知
            #     notify("refund/delete", doctor_id=doctor.id)