# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
import json
from django.db.models import Q, F
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from django.contrib.auth.models import User

from api.models import CashBackOrder, Doctor, Hospital
from pay.models import WechatRefund
from gm_types.gaia import NEW_CASH_BACK_STATUS, ORDER_STATUS, PAYMENT_CHANNEL
from ..models import UserPerm
from ..utils import check_business, check_operate, operate_business


class CashbackDB(DataBuilder):
    def getval_gm_send_refund_no(self, obj):
        from utils.order import get_refund_no
        return get_refund_no(obj.order)

    def getval_service_name(self, obj):
        return obj.order.service.name

    def getval_service(self, obj):
        return obj.order.service.id

    def getval_user_name(self, obj):
        return obj.order.user.last_name

    def getval_user(self, obj):
        return obj.order.user.id

    def getval_item(self, obj, default='非多属性美购'):
        try:
            return obj.order.service.items.get(key=obj.order.service_item_key).items_name
        except:
            return ''

    def getval_hospital_name(self, obj, default=''):
        return obj.order.service.doctor.hospital.name

    def getval_status(self, obj):
        return NEW_CASH_BACK_STATUS.getDesc(obj.status)

    def getval_diary_id(self, obj, default=''):
        return obj.order.diary.id

    def getval_diary(self, obj, default=''):
        return obj.order.diary.title

    def getval_diary_name(self, obj, default=''):
        return obj.order.diary.name

    def getval_doctor_name(self, obj):
        return obj.order.service.doctor.name

    def getval_doctor(self, obj):
        return obj.order.service.doctor.id

    def getval_hospital(self, obj):
        return obj.order.service.doctor.hospital.id

    def getval_num(self, obj):
        return '{}/{}'.format(obj.topic_cash_back_num, obj.topic_cash_back_limit)

    def getval_sell_doctor_name(self, obj):
        id = json.loads(obj.order.service_snapshot).get(u"doctor", None)
        try:
            return Doctor.objects.get(id=id).name
        except:
            return ''

    def getval_sell_hospital_name(self, obj):
        id = json.loads(obj.order.service_snapshot).get(u"hospital", None)
        try:
            return Hospital.objects.get(id=id).name
        except:
            return ''

    def getval_order__servicesnapshot__doctor__business_partener__username(self, obj):
        return obj.order.servicesnapshot.doctor.business_partener.username

    def getval_order__payment_channel(self, obj):
        return PAYMENT_CHANNEL.getDesc(obj.order.payment_channel)

    def getval_order__status(self, obj):
        return ORDER_STATUS.getDesc(obj.order.status)

    def getval_error_code(self, obj):
        if obj.order.payment_channel == PAYMENT_CHANNEL.WECHAT:
            wechat_refund = WechatRefund.objects.get(order_no=obj.order_id)
            return wechat_refund.err_code
        else:
            return ''


@DB
class CashbackDQ(DataSQLQuery):
    model = CashBackOrder
    data_model = CashbackDB

    def init_query(self, qs):
        return qs.annotate(num=F(u'topic_cash_back_limit') - F(u'topic_cash_back_num'))

    def filter_check_groups(self, srch_key, srch_val, regex=False):
        user = User.objects.get(id=srch_val)
        groups = user.belong_groups.values_list('name', flat=True)
        if check_business(groups):
            # 判断是商务并且非商务leader
            members = UserPerm.members(user)
            return Q(order__service__doctor__business_partener__in=members)
        elif check_operate(srch_val):
            business_ids = operate_business(srch_val)
            return Q(order__service__doctor__business_partener__id__in=business_ids)
        else:
            return Q()

    def filter_num(self, srch_key, srch_val, regex=False):
        if int(srch_val):
            return Q(topic_cash_back_limit__lte=F(u'topic_cash_back_num'))
        else:
            return Q(topic_cash_back_limit__gt=F(u'topic_cash_back_num'))

    def filter_created_at(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_updated_at(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_cashbacked_at(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_doctor_name(self, srch_key, srch_val, regex=False):
        return Q(order__service__doctor__name__contains=srch_val)

    def filter_hospital_name(self, srch_key, srch_val, regex=False):
        return Q(order__service__doctor__hospital__name__contains=srch_val)

    def filter_service_name(self, srch_key, srch_val, regex=False):
        return Q(order__service__name__contains=srch_val)

    def filter_address(self, srch_key, srch_val, regex=False):
        return Q(order__address__contains=srch_val)

    def filter_user_name(self, srch_key, srch_val, regex=False):
        return Q(order__user__last_name__contains=srch_val)

    def filter_phone(self, srch_key, srch_val, regex=False):
        return Q(order__phone__contains=srch_val)

    def filter_payment_channel(self, srch_key, srch_val, regex=False):
        return Q(order__payment_channel=srch_val)

    def filter_order__servicesnapshot__doctor__business_partener__username(self, srch_key, srch_val, regex=False):
        return Q(order__servicesnapshot__doctor__business_partener__username__contains=srch_val)


from api.models import Android
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB

@DB
class AndroidDQ(DataSQLQuery):
    model = Android
