# coding=utf-8
from api.models import CouponInfo
from api.models import Settlement
from rpc.tool.error_code import CODES
from rpc.tool.error_code import gen


def is_my_coupon(user, couponinfo_id, select_for_update=False):
    if couponinfo_id:
        try:
            coupon_info = (CouponInfo.objects.select_for_update() if select_for_update else
                           CouponInfo.objects) \
                .select_related('coupon').get(pk=couponinfo_id)
            if coupon_info.user != user:
                raise gen(CODES.NO_PERMISSION)
        except CouponInfo.DoesNotExist:
            raise gen(CODES.COUPON_DOES_NOT_EXIST)
    else:
        return None
    return coupon_info


def check_coupon_user_then_select_for_update_all_couponinfo(user_id, couponinfo_ids):
    if len(couponinfo_ids) == 0:
        raise gen(CODES.COUPON_DOES_NOT_EXIST)

    # 不要删除此行!!!
    all_couponinfos = list(CouponInfo.objects.select_for_update().filter(id__in=couponinfo_ids))
    all_couponinfos = list(CouponInfo.objects.filter(id__in=couponinfo_ids).select_related('coupon'))

    not_user_coupon = any([ci.user_id != user_id for ci in all_couponinfos])
    if not_user_coupon:
        raise gen(CODES.NO_PERMISSION)

    if len(couponinfo_ids) != len(all_couponinfos):
        raise gen(CODES.COUPON_DOES_NOT_EXIST)

    return all_couponinfos


def is_my_settlement(user, settlement_id):
    try:
        settlement = Settlement.objects.get(pk=settlement_id)
        if settlement.person.user != user:
            raise gen(CODES.NO_PERMISSION)
    except Settlement.DoesNotExist:
        raise gen(CODES.SETTLEMENT_DOES_NOT_EXIST)
    else:
        return settlement


def is_my_statement(user, statement_id):
    from pay.models import Statement
    try:
        statement = Statement.objects.get(pk=statement_id)
        if statement.doctor.user != user:
            raise gen(CODES.NO_PERMISSION)
    except Statement.DoesNotExist:
        raise gen(CODES.STATEMENT_NOT_EXIST)
    else:
        return statement
