# -*- coding: utf-8 -*-

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User

from ucenter.models import UserValidate
from adminpanel.models import Group

from utils.common import modelExtend


class Userdetail(models.Model):
    uservalidate = models.ForeignKey(UserValidate, verbose_name="用户")
    group = models.ForeignKey(Group, verbose_name="组")

    # add columns when you need

    GENDERCHOICES = ((0, _('--')), (1, _(u'男')), (2, _(u'女')))
    gender = models.PositiveSmallIntegerField(_('gender'), choices=GENDERCHOICES, blank=True, null=True)

    phone = models.CharField(max_length=45, blank=True, null=True)
    location = models.CharField(max_length=255, blank=True, null=True)
    realname = models.CharField(max_length=18, blank=True, null=True)
    idcard = models.CharField(max_length=18, blank=True, null=True)
    postcode = models.CharField(max_length=6, blank=True, null=True)
    companyname = models.CharField(max_length=50,  blank=True, null=True)
    contactaddress = models.CharField(max_length=50,  blank=True, null=True)
    industry = models.CharField(max_length=50,  blank=True, null=True)
    remark = models.TextField(blank=True, null=True)

    def __unicode__(self):
        return "%s @ %s" % (self.uservalidate.user.username, self.group.name)


class Info(models.Model):
    '''
        账户信息

        @ 2015-09-19 Neo

        关键逻辑：
            money 包含前台充值、后台线下转账资金、系统赠送。

            reward 字段记录系统赠送余额。（所有扣费，系统赠送的汇智币有限扣除）
    '''
    user = models.ForeignKey(User, verbose_name="用户")
    money = models.DecimalField(max_digits=20, decimal_places=4, default=0, verbose_name="汇智币")
    reward = models.DecimalField(max_digits=20, decimal_places=4, default=0, verbose_name="系统赠送")
    arrearageTime = models.DateTimeField(blank=True, null=True, verbose_name="最近一次欠费时间")

    objects = modelExtend()

    def __unicode__(self):
        return "money: %d" % (self.money)

    @staticmethod
    def jsonable(lists):
        return [{
            'id': l.pk,
            'username': l.user.username,
            'money': round(l.money, 2),
            'reward': round(l.reward, 2),
        } for l in lists]


class Task(models.Model):
    ''' 账户task  '''
    objects = modelExtend()

    user = models.ForeignKey(User, verbose_name="用户", related_name="task_user")
    initiator = models.ForeignKey(User, verbose_name="task发起人", related_name="task_initiator")
    money = models.DecimalField(max_digits=20, decimal_places=4, verbose_name="汇智币")

    statusChoices = ((1, u"未成交"), (2, u"已成交"))
    status = models.IntegerField(choices=statusChoices, verbose_name="支付状态")

    typeChoices = (('recharge', u"充值"), ('deduct', u'扣款'), ('withdraw', u'提现'), ('offline', u'线下转账'), ('reward', u'系统赠送'))
    type = models.CharField(max_length=200, choices=typeChoices, verbose_name="任务类型")

    otherId = models.CharField(max_length=25, verbose_name="外部id", null=True)  # 充值 => '', 扣款 => Proof.id

    payment = models.CharField(max_length=200, null=True, verbose_name="支付方式")
    tradecode = models.CharField(max_length=200, null=True, verbose_name="支付单号")
    remark = models.CharField(max_length=200, null=True, verbose_name="支付说明")

    createTime = models.DateTimeField(verbose_name="创建时间")
    updateTime = models.DateTimeField(blank=True, null=True, verbose_name="更新时间")

    def __unicode__(self):
        return "money: %d, type: %s" % (self.money, self.get_type_display())

    @staticmethod
    def jsonable(lists):
        result = []
        for l in lists:
            uv = UserValidate.objects.get(user=l.user)
            ud = Userdetail.objects.get(uservalidate=uv)
            result.append({
                'id': l.pk,
                'username': l.user.username,
                'realname': ud.realname,
                'companyname': ud.companyname,
                'initiator': l.initiator.username,
                'money': float(l.money),
                'type': l.type,
                'typeShow': l.get_type_display(),
                'status': l.status,
                'statusShow': l.get_status_display(),
                'payment': l.payment if l.payment else '',
                'tradecode': l.tradecode if l.tradecode else '',
                'remark': l.remark if l.remark else '',
                'createTime': l.createTime.strftime("%Y-%m-%d %H:%M:%S"),
                'updateTime': l.updateTime.strftime("%Y-%m-%d %H:%M:%S")
            })
        return result


class Flow(models.Model):
    '''
        资金流水

        @ 2015-09-19 Neo

        关键逻辑：
            reward 字段记录扣除的系统赠送。

    '''
    objects = modelExtend()

    user = models.ForeignKey(User, verbose_name="用户", related_name="flow_user")

    typeChoices = (('recharge', u"充值"), ('deduct', u'扣款'), ('withdraw', u'提现'), ('offline', u'线下转账'), ('reward', u'系统赠送'))
    type = models.CharField(max_length=200, choices=typeChoices, verbose_name="流水类型")

    task = models.ForeignKey(Task, verbose_name="任务")

    money = models.DecimalField(max_digits=20, decimal_places=4, verbose_name="汇智币")     # 该字段存在正负。正值为流入，负值为流出。
    reward = models.DecimalField(default=0, max_digits=20, decimal_places=4, verbose_name="系统赠送")     # 该字段存在正负。正值为流入，负值为流出。

    createTime = models.DateTimeField(verbose_name="流水创建时间")

    def __unicode__(self):
        return "money: %d, type: %s" % (self.money, self.get_type_display())

    @staticmethod
    def jsonable(lists):
        return [{
            'id': l.pk,
            'type': l.type,
            'typeShow': l.get_type_display(),
            'money': float(l.money),
            'createTime': l.createTime.strftime("%Y-%m-%d %H:%M:%S")
        } for l in lists]
