#coding=utf-8

from rest_framework import serializers
from django.db.models import Q

from apps import base
from apps.account.models import User
from apps.base import Formater
from apps.exceptions import CustomError
from apps.foundation.models import BizLog
from apps.finance.models import FinanceCategory, FinancePurpose, dbFinanceIncome
from apps.serializer_errors import dump_serializer_errors
from libs.booleancharfield import AmountShowCharField

class FinanceCategorySerializer(serializers.ModelSerializer):
    enabled_text = serializers.SerializerMethodField()

    class Meta:
        model = FinanceCategory
        fields = '__all__'

    def get_enabled_text(self, obj):
        if obj.enabled:
            return u'是'
        return u'否'

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instance = FinanceCategory.getById(id)
        else:
            instance = None
        serializer = FinanceCategorySerializer(instance, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        validated_data['create_user'] = self.user
        instance = FinanceCategory.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加财务收支类别[%s]，id=%d" % (instance.name, instance.id),
            validated_data
        )
        return instance

    def update(self, instance, validated_data):
        instance = super(FinanceCategorySerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改财务收支类别[%s]，id=%d" % (instance.name, instance.id),
            validated_data
        )
        return instance

    def validSave(self):
        if self.is_valid():
            return self.save()
        else:
            raise CustomError(dump_serializer_errors(self))


class FinancePurposeSerializer(serializers.ModelSerializer):
    category_text = serializers.CharField(source='category.name', read_only=True)
    type_text = serializers.CharField(source='get_type_display', read_only=True)
    enabled_text = serializers.SerializerMethodField()

    def get_enabled_text(self, obj):
        if obj.enabled:
            return u'是'
        return u'否'

    class Meta:
        model = FinancePurpose
        fields = '__all__'

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instance = FinancePurpose.getById(id)
        else:
            instance = None
        serializer = FinancePurposeSerializer(instance, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        validated_data['create_user'] = self.user
        instance = FinancePurpose.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加财务收支用途[%s]，id=%d" % (instance.name, instance.id),
            validated_data
        )
        return instance

    def update(self, instance, validated_data):
        instance = super(FinancePurposeSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改财务收支用途[%s]，id=%d" % (instance.name, instance.id),
            validated_data
        )
        return instance

    def validSave(self):
        if self.is_valid():
            return self.save()
        else:
            raise CustomError(dump_serializer_errors(self))


class FinanceIncomeSerializer(serializers.ModelSerializer):
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    type_text = serializers.CharField(source='get_type_display', read_only=True)
    check_status_text = serializers.CharField(source='get_check_status_display', read_only=True)
    account_text = serializers.CharField(source='account.name', read_only=True)
    purpose_text = serializers.CharField(source='purpose.name', read_only=True)
    check_user_text = serializers.CharField(source='check_user.name', read_only=True)
    category = serializers.IntegerField(source='purpose.category.id', read_only=True)
    amount = AmountShowCharField()
    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    check_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)

    class Meta:
        model = dbFinanceIncome
        fields = '__all__'

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instance = dbFinanceIncome.getById(id)
        else:
            instance = None
        serializer = FinanceIncomeSerializer(instance, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        validated_data['create_user'] = self.user
        validated_data['department'] = self.user.department
        instance = dbFinanceIncome.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加收支单[%s]，id=%d" % (instance.no, instance.id),
            validated_data
        )
        return instance

    def update(self, instance, validated_data):
        instance = super(FinanceIncomeSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改收支单[%s]，id=%d" % (instance.no, instance.id),
            validated_data
        )
        return instance

    def validate(self, data):
        data['amount'] = Formater.formatAmount(data['amount'])
        return data

    def validSave(self):
        if self.is_valid():
            return self.save()
        else:
            raise CustomError(dump_serializer_errors(self))
