# coding=utf-8
from __future__ import absolute_import
from django.db.models import Q
from gm_types.gaia import ORDER_STATUS, MAIDAN_REVIEW_STATUS, MAIDAN_STATEMENT_STATUS

from maidan.models import (
    MaidanOrder, MaidanSetting, MaidanSettingApply, MaidanStatement, MaidanPayment
)
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB


class MaiDanOrderDB(DataBuilder):
    def getval_status_name(self, obj):
        return ORDER_STATUS.getDesc(obj.status)


@DB
class MaiDanOrderDQ(DataSQLQuery):
    model = MaidanOrder
    data_model = MaiDanOrderDB

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


class MaiDanSettingDB(DataBuilder):
    def getval_doctor_discount_rate(self, obj):
        return '{}%'.format(obj.doctor_discount_rate)

    def getval_discount_rate(self, obj):
        return '{}%'.format(obj.discount_rate)

    def getval_gengmei_offers_rate(self, obj):
        return '{}%'.format(obj.gengmei_offers_rate)

    def getval_doctor__hospital__name(self, obj):
        if obj.doctor and obj.doctor.hospital:
            return obj.doctor.hospital.name
        else:
            return u''


@DB
class MaiDanSettingDQ(DataSQLQuery):
    model = MaidanSetting
    data_model = MaiDanSettingDB


class MaiDanSettingApplyDB(DataBuilder):
    def getval_last_modify_time(self, obj):
        if obj.last_modify_time:
            return str(obj.last_modify_time)[0:19]

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

    def getval_doctor__hospital__name(self, obj):
        if obj.doctor and obj.doctor.hospital:
            return obj.doctor.hospital.name
        else:
            return u''


@DB
class MaiDanSettingApplyDQ(DataSQLQuery):
    model = MaidanSettingApply
    data_model = MaiDanSettingApplyDB
    init_q = Q(last_modify_time__isnull=False)

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


class MaidanStatementDB(DataBuilder):
    def getval_status_type(self, obj):
        return MAIDAN_STATEMENT_STATUS.getDesc(obj.status)


@DB
class MaidanStatementDQ(DataSQLQuery):
    model = MaidanStatement
    data_model = MaidanStatementDB


@DB
class MaidanPaymentDQ(DataSQLQuery):
    model = MaidanPayment
