#!/usr/bin/env python
# coding=utf-8

from django.db.models import Q
from gm_types.doctor import COUPON_FILTER_STATUS

from api.tool.coupon_tool import get_coupon_info_for_doctor_send_coupon
from api.tool.user_tool import get_doctor_from_context
from hippo.models import Doctor
from hippo.utils import get_doctors
from api.models import Coupon, CouponInfo, OrderCouponInfo, CouponGift, ChannelGift
from rpc.tool.error_code import CODES, gen
from rpc.decorators import bind_context

from gm_types.gaia import COUPON_STATUS, COUPON_DISTRIBUTION_STATUS, COUPON_GIFT_TYPES


@bind_context('doctor/coupon/create_or_update', login_required=True)
def create_or_update(ctx, coupon_info):
    """
        创建 （更新coupon中有id）美券
    """
    if 'doctor_id' in coupon_info and coupon_info.get("doctor_id"):
        doctor = Doctor.objects.get(id=coupon_info.pop('doctor_id',None))
    else:
        doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)
    # 区分保存(可编辑)还是生效(不可编辑)
    distribution_status = coupon_info.get('distribution_status')
    if distribution_status not in [COUPON_DISTRIBUTION_STATUS.DRAFT, COUPON_DISTRIBUTION_STATUS.OPEN]:
        return gen(CODES.NO_PERMISSION)

    coupon_id = coupon_info.get('id')
    if coupon_id:
        # 更新coupon
        coupon = Coupon.objects.get(id=coupon_id)
        # 医生只能修改自己的美券
        if coupon.doctor_id != doctor.id:
            return gen(CODES.NO_PERMISSION)
        Coupon.objects.update_doctor_coupon(coupon, doctor, coupon_info)
        # 上面步骤操作了coupon update, 不要再用coupon.save()了
    else:
        # 创建
        coupon = Coupon.objects.create_doctor_coupon(doctor, coupon_info)
    return {'id': coupon.id}


@bind_context('doctor/coupon/list', login_required=True)
def coupon_list(ctx, filter_status=COUPON_FILTER_STATUS.ALL, doctor_id=None, coupon_name=None, start_num=0,
                count=10, only_count=False):
    """
        医生我的美券列表
    """
    doctor = get_doctor_from_context(ctx)
    doctor_ids = []
    if doctor.is_merchant:
        doctor_ids.extend(get_doctors(doctor.id, only_doctor_id=True))
    else:
        doctor_ids.append(doctor.id)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)
    coupon_set = Coupon.objects.doctor_coupon_list(doctor_ids, filter_status, doctor_id, coupon_name)
    data = {
        'total': coupon_set.count(),
    }
    if not only_count:
        coupons = []
        for coupon in coupon_set[start_num: start_num + count]:
            coupons.append(coupon.listitem_for_doctor())
        data['coupons'] = coupons
    return data


@bind_context('doctor/coupon/get', login_required=True)
def coupon_detail(ctx, coupon_id):
    """
        获取美券 详情
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    coupon = Coupon.objects.get(id=coupon_id)
    return coupon.detail_for_doctor()


@bind_context('doctor/coupon/set_status', login_required=True)
def set_status(ctx, coupon_id, distribution_status):
    """
        操作美券状态美券
    """
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    coupon = Coupon.objects.get(id=coupon_id)
    if not (doctor.is_merchant and coupon.doctor_id  in [item.id for item in doctor.merchant_doctors()]):
    # # 医生只能修改自己的美券
    # if coupon.doctor_id != doctor.id:
        return gen(CODES.NO_PERMISSION)
    if distribution_status != COUPON_DISTRIBUTION_STATUS.CLOSED:
        return gen(CODES.NO_PERMISSION)
    Coupon.objects.close_doctor_coupon(coupon)
    return {'id': coupon.id}


@bind_context('doctor/coupon/get_can_send_coupon_list', login_required=True)
def coupon_list(ctx, doctor_ids=[]):
    """
        医生通过私信可以发送美券列表
    """

    result = get_coupon_info_for_doctor_send_coupon(doctor_ids)

    data = {
        'coupon_list': result,
    }

    return data


@bind_context('doctor/coupon/get_coupon_detail', login_required=True)
def coupon_record_detail(ctx, coupon_id, coupon_apply_status):
   
    coupon = Coupon.objects.get(id=coupon_id)
    coupon_name = coupon.name
    coupon_money = coupon.value
    coupon_range = coupon.doctor_coupon_use_type
    coupon_condition = coupon.prepay_threshold
    coupon_type = coupon.benefit_type
    coupon_start_time = coupon.start_time.strftime('%Y-%m-%d %H:%M:%S') if coupon.start_time else '' 
    coupon_end_time = coupon.end_time.strftime('%Y-%m-%d %H:%M:%S') if coupon.end_time else ''
    coupon_time_type = coupon.time_type
    coupon_countdown = coupon.countdown

    coupon_total = []
    gifts = CouponGift.objects.filter(gift_type=COUPON_GIFT_TYPES.DOCTOR, coupon=coupon_id)
    for gift in gifts:
        for channel_gift in ChannelGift.objects.filter(gift=gift):
             coupon_total.append(channel_gift.total)

    total_num = sum(coupon_total) 
    receive_num = CouponInfo.objects.filter(coupon=coupon_id, status=COUPON_STATUS.CLAIMED).count()             #领取数量
    consume_num = CouponInfo.objects.filter(coupon=coupon_id, status=COUPON_STATUS.CONSUMED).count()            #消费数量
    frozen_num = CouponInfo.objects.filter(coupon=coupon_id, status=COUPON_STATUS.FROZEN).count()               #冻结数量
    no_receive_num = total_num - receive_num - consume_num - frozen_num                                         #未领取数量

    data = {
        "coupon_id": coupon_id,
        "coupon_name": coupon_name,
        "coupon_range": coupon_range,
        "coupon_condition": coupon_condition,
        "coupon_type": coupon_type,
        "coupon_money": coupon_money,
        "coupon_apply_status": coupon_apply_status,
        "coupon_time_type": coupon_time_type,
        "coupon_start_time": coupon_start_time,
        "coupon_end_time": coupon_end_time,
        "coupon_countdown": coupon_countdown,
        "total_num": total_num,
        "receice_num": receive_num + consume_num + frozen_num,
        "no_receive_num": no_receive_num,
        "use_num": consume_num,
        "no_use_num": receive_num + frozen_num
    }
    
    return data


@bind_context('doctor/coupon/get_coupon_receive_record', login_required=True)
def coupon_recevice_record(ctx, coupon_id, sort=0, start_num=0, count=10):
    coupon_infos = CouponInfo.objects.filter(coupon=coupon_id).exclude(status=COUPON_STATUS.UNCLAIMED)

    if sort == 1:#点击领取时间，按照领取时间正排
        coupon_infos = coupon_infos.order_by("claimed_time")

    elif sort == 2:#点击使用时间，按照使用时间倒排
        coupon_infos = coupon_infos.order_by("-consumed_time")

    elif sort == 3:#点击使用时间，按照使用时间正排
        coupon_infos = coupon_infos.order_by("consumed_time")

    else:           #默认顺序为按照领取时间倒排
        coupon_infos = coupon_infos.order_by("-claimed_time")
        
    total = coupon_infos.count()

    coupon_info_list = []
    for coupon_info in coupon_infos:
        coupon_status = coupon_info.status
        order = OrderCouponInfo.objects.filter(coupon_info_id=coupon_info.id).first()
        order_id = None
        if order:
            order_id = order.order_id

        coupon_info_list.append({
            "code": coupon_info.id,
            "username": coupon_info.user.last_name,
            "coupon_receive_time": coupon_info.claimed_time.strftime('%Y-%m-%d %H:%M:%S') if coupon_info.claimed_time else '',
            "coupon_status": coupon_status,
            "coupon_use_time": coupon_info.consumed_time.strftime('%Y-%m-%d %H:%M:%S') if coupon_info.consumed_time else '',
            "order_id": order_id 
        })    

    data = {
        "coupon_info_list": coupon_info_list[start_num: start_num + count],
        "total": total
    }

    return data
