# coding=utf-8
from gm_types.gaia import REFUND_STATUS, ORDER_STATUS, PAYMENT_CHANNEL

from api.models import RefundOrder
from pay.models import WechatRefund
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery


class RefundOrderErrorDB(DataBuilder):
    """
    退款单异常实体返回数据格式
    """

    # def getval_optype(self, obj):
    #     if obj.optype == ORDER_OPERATION_TYPE.REFUNDED:
    #         return u'标记状态:已退款'
    #     elif obj.optype == ORDER_OPERATION_TYPE.CASHBACKED:
    #         return u'标记状态:已返现'
    def getval_status(self, obj):
        return REFUND_STATUS.getDesc(obj.status)

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

    def getval_created_at(self, obj):
        return str(obj.created_at)[0:19]

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


class RefundOrderErrorDQ(DataSQLQuery):
    """
    退款单异常实体产生过滤
    """
    model = RefundOrder
    data_model = RefundOrderErrorDB

    def build_queryset(self, search=None, filters=None, nfilters=None, orders=None):
        # 剔除过期退款的
        qs = super(RefundOrderErrorDQ, self).build_queryset(search, filters, nfilters, orders).exclude(stale=True)
        return qs
