# -*- coding: UTF-8 -*-
from __future__ import unicode_literals, absolute_import, print_function

from datetime import datetime
import json
from django.db.models import Q, Sum, Count
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_types.gaia import REJECT_REASON, TRANS_STATUS
from gm_types.error import ERROR
from rpc.tool.dict_mixin import to_dict
from rpc.exceptions import GaiaRPCFaultException
from api.models import User, UserExtra
from cashback.models import *
from statistic.models import Device


class RedPacketDB(DataBuilder):
    def getval_count(self, obj):
        return CashbackManager.getRedPacketCount(obj.id)


@DB
class RedPacketDQ(DataSQLQuery):
    model = RedPacket
    data_model = RedPacketDB

    def create(self, **kwargs):
        if self.model.objects.filter(packet_type=kwargs['packet_type'], is_online=True).exists():
            self.model.objects.filter(packet_type=kwargs['packet_type'], is_online=True).update(is_online=False)
        obj = self.model.objects.create(is_online=True, **kwargs)
        return to_dict(obj)


class TransactionLogDB(DataBuilder):
    def getval_log(self, obj, need_escape=False):
        log = {}
        try:
            log_obj = CashBackAuditLog.objects.filter(transactionlog_id=obj.id).first()
            log['user_name'] = log_obj.user.last_name
            log['status'] = log_obj.status
            log['time'] = log_obj.time.strftime('%Y-%m-%d %H:%M:%S')
            log['reason'] = REJECT_REASON.getDesc(log_obj.reason)
        except:
            pass
        return json.dumps(log)

    def getval_is_suspect(self, obj):
        return CashbackManager.isSuspect(obj.user)


@DB
class TransactionLogDQ(DataSQLQuery):
    model = TransactionLog
    data_model = TransactionLogDB

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

    def filter_is_suspect(self, srch_key, srch_val, regex=False):
        if srch_val == '':
            return Q()
        objs = self.model.objects.all()
        correct_ids = []
        for obj in objs:
            if CashbackManager.isSuspect(obj.user):
                correct_ids.append(obj.user.id)
        q = Q(user_id__in=correct_ids)
        if srch_val == '1':
            return q
        else:
            return ~q

    def update(self, updates, **kwargs):
        obj = self.model.objects.get(id=kwargs['id'])
        if obj.state != TRANS_STATUS.WAIT:
            raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'已审核完成，无法再次操作', data=None)
        audit_obj = CashBackAuditLog.objects.create(
            transactionlog_id=kwargs['id'],
            user_id=updates.pop('auditor'),
            status=updates['state']
        )
        if updates['state'] == str(TRANS_STATUS.REJECT):
            audit_obj.reason=updates.pop('reason')
            audit_obj.save()
        return super(TransactionLogDQ.sqlquery, self).update(updates, **kwargs)


class RegistrationDB(DataBuilder):
    def getval_invitee_phone(self, obj):
        phone = UserExtra.objects.get(user_id=obj.invitee_id).phone
        return phone

    def getval_is_others(self, obj):
        devices = Device.objects.filter(user=obj.invitee)
        if devices:
            return CashbackManager.isLoginOthers(devices.latest('last_activity').device_id)
        return False

    def getval_device_type(self, obj):
        devices = Device.objects.filter(user=obj.invitee)
        if devices:
            return devices.latest('last_activity').model
        return u''


@DB
class RegistrationDQ(DataSQLQuery):
    model = Registration
    data_model = RegistrationDB

    def filter_is_suspect(self, srch_key, srch_val, regex=False):
        if srch_val == '':
            return Q()
        objs = self.model.objects.all()
        correct_ids = []
        for obj in objs:
            if CashbackManager.isSuspect(obj.inviter):
                correct_ids.append(obj.inviter.id)
        q = Q(inviter_id__in=correct_ids)
        if srch_val == '1':
            return q
        else:
            return ~q


class UserBalanceDB(DataBuilder):

    def getval_income(self, obj):
        return CashbackManager.getUserIncome(obj.user)

    def getval_balance(self, obj):
        return CashbackManager.getUserBalance(obj.user)

    def getval_invite_num(self, obj):
        return CashbackManager.getUserInviteNum(obj.user)

    def getval_audit(self, obj):
        return CashbackManager.getUserAudit(obj.user)

    def getval_withdraw(self, obj):
        return CashbackManager.getUserWithdraw(obj.user)

    def getval_is_suspect(self, obj):
        return CashbackManager.isSuspect(obj.user)


@DB
class UserBalanceDQ(DataSQLQuery):
    model = UserBalance
    data_model = UserBalanceDB

    def filter_is_suspect(self, srch_key, srch_val, regex=False):
        if srch_val == '':
            return Q()
        objs = self.model.objects.all()
        correct_ids = []
        for obj in objs:
            if CashbackManager.isSuspect(obj.user):
                correct_ids.append(obj.user.id)
        q = Q(user_id__in=correct_ids)
        if srch_val == '1':
            return q
        else:
            return ~q

    def order_invite_num(self, qs, field):
        qs = qs.annotate(invitenum=Count('user__inviter__id'))
        return qs, u'invitenum'
