#coding=utf-8

import datetime
from rest_framework import serializers
from apps.exceptions import CustomError
from django.db.models import Q

from apps.foundation.models import BizLog
from .models import *
from apps.serializer_errors import dump_serializer_errors
from apps.foundation.models import BizLog
from apps.customer.models import Customer
from apps.account.models import Branch
from apps import base
from libs.booleancharfield import PriceShowCharField


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

    class Meta:
        model = Branch
        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 = Branch.getById(id)
        else:
            instance = None
        serializer = BranchSerializer(instance, data=data)
        serializer.user = user
        return serializer

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

    def validate(self, data):
        if 'enabled' in data:
            data['enabled'] = True
        else:
            data['enabled'] = False
        return data


    def create(self, validated_data):
        instance = super(BranchSerializer, self).create(validated_data)
        instance.save()
        BizLog.objects.addnew(self.user, BizLog.INSERT, u"添加门店[%s],id=%s" % (instance.name, instance.id),validated_data)
        return instance

    def update(self, instance, validated_data):
        BizLog.objects.addnew(self.user, BizLog.UPDATE, u"修改门店[%s],id=%s" % (instance.name, instance.id),validated_data)
        instance = super(BranchSerializer, self).update(instance, validated_data)
        return instance


class CustomerSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)

    class Meta:
        model = Customer
        fields = '__all__'


class MemberCouponSerializer(serializers.ModelSerializer):
    activity_name = serializers.CharField(source='activity.title', read_only=True)
    coupon_name = serializers.CharField(source='coupon.name', read_only=True)
    write_off_text = serializers.SerializerMethodField()
    write_off_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)

    class Meta:
        model = MemberCoupon
        fields = '__all__'

    def get_write_off_text(self, obj):
        if obj.write_off:
            return u'是'
        return u'否'


class OrderSerializer(serializers.ModelSerializer):
    activity_name = serializers.CharField(source='activity.title', read_only=True)
    member_name = serializers.CharField(source='member.name', read_only=True)
    recommend_member_name = serializers.CharField(source='recommend_member.name', read_only=True)
    member_tel = serializers.CharField(source='member.tel', read_only=True)
    branch_name = serializers.CharField(source='branch.name', read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    delete_text = serializers.SerializerMethodField()
    split_status_text = serializers.SerializerMethodField()
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    amount = PriceShowCharField(read_only=True)
    rebate = PriceShowCharField(read_only=True)
    split_button = serializers.SerializerMethodField()

    class Meta:
        model = Order
        fields = '__all__'

    def get_delete_text(self, obj):
        if obj.delete:
            return u'是'
        return u'否'
    
    def get_split_button(self, obj):
        if obj.recommend_member and obj.rebate > 0:
            if obj.pay and obj.pay.status == Pay.CONFIRM and obj.pay.profit_sharing == "Y":
                account_detail = SplitAccountDetail.objects.filter(main_id=obj.splitaccount_id).first()
                if account_detail:
                    if account_detail.status == SplitAccountDetail.PENDING:
                        return '1'   # 显示 刷新分账结果按钮
                    elif account_detail.status == SplitAccountDetail.CLOSED or account_detail.status == SplitAccountDetail.DEFAULT:
                        return '2'   # 显示  分账按钮
                    else:
                        return ''
                return ''
            return ''
        return ''

    def get_split_status_text(self, obj):
        if obj.status == Order.FINISH:
            account_detail = SplitAccountDetail.objects.filter(main_id=obj.splitaccount_id).first()
            if account_detail:
                return SplitAccountDetail.STATUS_CHOICES[account_detail.status][1]
            return ''
        return ''

class CouponSerializer(serializers.ModelSerializer):
    branch_name = serializers.CharField(source='branch.name', read_only=True)
    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    enabled_text = serializers.SerializerMethodField()

    class Meta:
        model = Coupon
        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 = Coupon.getById(id)
        else:
            instance = None
        serializer = CouponSerializer(instance, data=data)
        serializer.user = user
        return serializer

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

    def validate(self, data):
        if 'enabled' in data:
            data['enabled'] = True
        else:
            data['enabled'] = False

        return data


    def create(self, validated_data):
        instance = super(CouponSerializer, self).create(validated_data)
        instance.save()
        BizLog.objects.addnew(self.user, BizLog.INSERT, u"添加优惠券[%s],id=%s" % (instance.name, instance.id),validated_data)
        return instance

    def update(self, instance, validated_data):
        BizLog.objects.addnew(self.user, BizLog.UPDATE, u"修改优惠券[%s],id=%s" % (instance.name, instance.id),validated_data)
        instance = super(CouponSerializer, self).update(instance, validated_data)
        return instance

class ActivitySerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    check_status_text = serializers.CharField(source='get_check_status_display', read_only=True)
    enabled_text = serializers.SerializerMethodField()
    coupons = serializers.SerializerMethodField()
    pic = serializers.SerializerMethodField()


    class Meta:
        model = Activity
        fields = '__all__'

    def get_pic(self, obj):
        if obj.pic:
            return settings.MEDIA_URL + obj.pic
        return ''

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

    def get_coupons(self, obj):
        data = []
        rows = ActivityCoupon.objects.filter(activity=obj)
        data.extend([s.id for s in rows])
        return data

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instance = Activity.getById(id)
            if not data['branch']:
                data['branch'] = instance.branch_id
        else:
            instance = None
        serializer = ActivitySerializer(instance, data=data)
        serializer.user = user
        return serializer

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

    def validate(self, data):
        if 'enabled' in data:
            data['enabled'] = True
        else:
            data['enabled'] = False
        return data

    def create(self, validated_data):
        instance = super(ActivitySerializer, self).create(validated_data)
        instance.save()
        BizLog.objects.addnew(self.user, BizLog.INSERT, u"添加活动[%s],id=%s" % (instance.title, instance.id),
                              validated_data)
        return instance

    def update(self, instance, validated_data):
        BizLog.objects.addnew(self.user, BizLog.UPDATE, u"修改活动[%s],id=%s" % (instance.title, instance.id),
                              validated_data)
        instance = super(ActivitySerializer, self).update(instance, validated_data)
        return instance


class CouponComboboxSerializer(serializers.ModelSerializer):
    value = serializers.CharField(source='id', read_only=True)

    class Meta:
        model = Coupon
        fields = ('value', 'name',)