#coding=utf-8
from libs import utils

from django.db.models import Q, Sum
from django.conf import settings
from rest_framework import serializers
from apps.base import Formater
from apps.exceptions import CustomError
from apps.foundation.models import BizLog
from apps.serializer_errors import dump_serializer_errors
from models import PurchasePlan, PurchaseUser, PurchasePlanDetail, PurchasePrice, PurchaseOrder, PurchaseOrderDetail, \
    PurchaseInvoiceImage, \
    PurchasePayment, PurchasePaymentDetail, GodownEntry, GodownEntryDetail, GodownEntryReturn, GodownEntryReturnDetail, \
    PurchasePay
from libs.booleancharfield import BooleanCharField, PriceShowCharField, AmountShowCharField, CountShowCharField, \
    TimeCharField, AmountShowCharFieldWithTwoDecimalPlaces

from apps.warehouse.models import WarehouseStock
from apps import base

class PurchasePlanSerializer(serializers.ModelSerializer):
    status = serializers.CharField(read_only=True)
    total_count = CountShowCharField(read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    demend_user_text = serializers.CharField(source='demend_user.name', read_only=True)
    demend_department_text = serializers.CharField(source='demend_department.name', read_only=True)
    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    check_user_text = serializers.CharField(source='check_user.name', read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    purchase_users = serializers.SerializerMethodField()
    check_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    is_compact_text = serializers.SerializerMethodField()
    report_text = serializers.SerializerMethodField()

    # check_user_text2 = serializers.CharField(source='check_user2.name', read_only=True)
    # check_time2 = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    # check_user_text3 = serializers.CharField(source='check_user3.name', read_only=True)
    # check_time3 = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    class Meta:
        model = PurchasePlan
        fields = '__all__'

    def get_purchase_users(self, obj):
        data = []
        rows = PurchaseUser.objects.filter(purchase=obj)
        data.extend([s[0] for s in rows.values_list('purchase_user__name')])
        return ','.join(data)

    def get_is_compact_text(self, obj):
        data = obj.isCompart()
        return data

    def get_report_text(self, obj):
        data = obj.isReport()
        return data

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

    def validate(self, data):
        data['demend_department'] = None
        if 'demend_user' in data and data['demend_user']:
            data['demend_department'] = data['demend_user'].department
        return data

    def create(self, validated_data):
        validated_data['create_user'] = self.user
        validated_data['department'] = self.user.department
        production = PurchasePlan.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加采购计划[%s]，id=%d" % (production.name, production.id),
            validated_data
        )
        return production

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

    def update(self, instance, validated_data):
        instance = super(PurchasePlanSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改采购计划[%s]，id=%d" % (instance.name, instance.id),
            validated_data
        )
        return instance


class PurchasePlanDetailSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='product.name', read_only=True)
    model = serializers.CharField(source='product.model', read_only=True)
    stock_count = CountShowCharField(source='product.stock_count', read_only=True)
    purchase_count = CountShowCharField()

    class Meta:
        model = PurchasePlanDetail
        fields = '__all__'

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instances = PurchasePlanDetail.getById(id)
        else:
            instances = None
        serializer = PurchasePlanDetailSerializer(instances, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        production = PurchasePlanDetail.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加采购计划明细[%s]，id=%d" % (production.product.name, production.id),
            validated_data
        )
        return production

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


    def validate(self, data):
        data['purchase_count'] = Formater.formatCount(data['purchase_count'])
        return data

    def update(self, instance, validated_data):
        instance = super(PurchasePlanDetailSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改采购计划明细[%s]，id=%d" % (instance.name, instance.id),
            validated_data
        )
        return instance


class PurchaseUserSerializer(serializers.ModelSerializer):
    purchase_user_text = serializers.CharField(source='purchase_user.name', read_only=True)

    class Meta:
        model = PurchaseUser
        fields = '__all__'

    @staticmethod
    def factory(user, data):
        instances = None
        serializer = PurchaseUserSerializer(instances, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        purchaseuser = PurchaseUser.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加采购计划[%s]采购员[%s]，id=%d" % (purchaseuser.purchase.no, purchaseuser.purchase_user.name, purchaseuser.id),
            validated_data
        )
        return purchaseuser

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

    def update(self, instance, validated_data):
        instance = super(PurchaseUserSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改采购计划[%s]采购员[%s]，id=%d" % (instance.purchase.no, instance.purchase_user.name, instance.id),
            validated_data
        )
        return instance


class PurchasePriceSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='purchase_detail.product.name', read_only=True)
    model = serializers.CharField(source='purchase_detail.product.model', read_only=True)
    type_id = serializers.CharField(source='purchase_detail.product.type', read_only=True)
    type_text = serializers.CharField(source='purchase_detail.product.get_type_display', read_only=True)
    quality_request_text = serializers.CharField(source='purchase_detail.quality_request_text', read_only=True)
    purchase_count = CountShowCharField(source='purchase_detail.purchase_count', read_only=True)
    unit = serializers.CharField(source='purchase_detail.product.unit', read_only=True)
    demend_user_text = serializers.CharField(source='purchase_user.purchase.demend_user.name', read_only=True)
    purchase_user_text = serializers.CharField(source='purchase_user.name', read_only=True)
    product_time = serializers.DateTimeField(format=base.DATE_FORMAT, source='purchase_detail.product_time', read_only=True)
    supplier_text = serializers.CharField(source='supplier.name', read_only=True)
    price = PriceShowCharField()
    report_text = BooleanCharField(source='report', read_only=True)

    class Meta:
        model = PurchasePrice
        fields = '__all__'

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instances = PurchasePrice.getById(id)
        else:
            instances = None
        serializer = PurchasePriceSerializer(instances, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        purchaseprice = PurchasePrice.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加采购计划[%s]报价[%s]，id=%d" % (purchaseprice.purchase_detail.purchase.no, purchaseprice.price, purchaseprice.id),
            validated_data
        )
        return purchaseprice

    def validate(self, data):
        if 'price' in data:
            data['price'] = Formater.formatPrice(data['price'])
        return data

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

    def update(self, instance, validated_data):
        instance = super(PurchasePriceSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改采购计划[%s]报价[%s]，id=%d" % (instance.purchase_detail.purchase.no, instance.price, instance.id),
            validated_data
        )
        return instance


class PurchaseOrderSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    check_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    arrval_text = serializers.CharField(source='get_arrval_display', read_only=True)
    check_user_text = serializers.CharField(source='check_user.name', read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    supplier_name = serializers.CharField(source='supplier.name', read_only=True)
    supplier_type = serializers.CharField(source='supplier.type', read_only=True)
    supplier_contacts = serializers.CharField(source='supplier.contacts', read_only=True)
    supplier_phone_number = serializers.CharField(source='supplier.phone_number', read_only=True)
    supplier_opening_bank = serializers.CharField(source='supplier.opening_bank', read_only=True)
    supplier_account = serializers.CharField(source='supplier.account', read_only=True)
    products = serializers.SerializerMethodField()
    entries = serializers.SerializerMethodField()
    arrvals = serializers.SerializerMethodField()
    is_pay = serializers.SerializerMethodField()
    payment_amount = serializers.SerializerMethodField()
    count = CountShowCharField()
    amount = AmountShowCharFieldWithTwoDecimalPlaces()
    apply_amount = AmountShowCharFieldWithTwoDecimalPlaces(read_only=True)
    # check_user_text2 = serializers.CharField(source='check_user2.name', read_only=True)
    # check_time2 = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    # check_user_text3 = serializers.CharField(source='check_user3.name', read_only=True)
    # check_time3 = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)

    class Meta:
        model = PurchaseOrder
        fields = '__all__'

    def get_products(self, obj):
        data = []
        rows = PurchaseOrderDetail.objects.filter(main=obj)
        data.extend([s[0] for s in rows.values_list('product__name')])
        return ','.join(data)

    def get_entries(self, obj):
        data = []
        rows = GodownEntry.objects.filter(purchase_order=obj)
        data.extend([s[0] for s in rows.values_list('no')])
        return ','.join(data)
    def get_is_pay(self, obj):
        data = 0
        rows = PurchasePayment.objects.filter(order=obj)
        if rows:
            data = 1
        return data

    def get_arrvals(self, obj):
        sum_rows = PurchaseOrderDetail.objects.filter(main=obj).aggregate(sum_count=Sum('arrval_count'))
        return Formater.formatCountShow(sum_rows['sum_count'] or 0)

    def get_payment_amount(self, obj):
        sum_rows = PurchasePayment.objects.filter(order=obj).aggregate(sum_amount=Sum('actual_amount'))
        return Formater.formatAmountShowWithTwoDecimalPlaces(sum_rows['sum_amount'] or 0)

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instance = PurchaseOrder.getById(id)
        else:
            instance = None
        serializer = PurchaseOrderSerializer(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
        order = PurchaseOrder.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加采购合同[%s]，id=%d" % (order.no, order.id),
            validated_data
        )
        return order

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

    def update(self, instance, validated_data):
        instance = super(PurchaseOrderSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改采购合同[%s]，id=%d" % (instance.no, instance.id),
            validated_data
        )
        return instance

class PurchaseOrderDetailSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='product.name', read_only=True)
    model = serializers.CharField(source='product.model', read_only=True)
    supplier_name = serializers.CharField(source='main.supplier.name', read_only=True)
    order_no = serializers.CharField(source='main.no', read_only=True)
    count = CountShowCharField()
    arrval_count = CountShowCharField(read_only=True)
    price = PriceShowCharField()
    amount = AmountShowCharField(read_only=True)
    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    check_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    invoice_date = serializers.DateField(format=base.DATE_FORMAT, read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    check_user_text = serializers.CharField(source='check_user.name', read_only=True)
    invoice_amount = AmountShowCharField(read_only=True)
    check_status_text = serializers.CharField(source='get_check_status_display', read_only=True)
    images = serializers.SerializerMethodField()

    class Meta:
        model = PurchaseOrderDetail
        fields = '__all__'

    def get_images(self, obj):
        data = []
        rows = PurchaseInvoiceImage.objects.filter(order_detail=obj)
        data.extend([s[0] for s in rows.values_list('invoice_image')])
        return ','.join(data)

    @staticmethod
    def factory(user, data):
        instances = None
        serializer = PurchaseOrderDetailSerializer(instances, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        order = PurchaseOrderDetail.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加采购合同明细[%s]，id=%d" % (order.main.no, order.id),
            validated_data
        )
        return order

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

    def validate(self, data):
        data['price'] = Formater.formatPrice(data['price'])
        data['count'] = Formater.formatCount(data['count'])
        data['amount'] = data['count'] * data['price']
        return data

    def update(self, instance, validated_data):
        instance = super(PurchaseOrderDetailSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改采购合同明细[%s]，id=%d" % (instance.main.no, instance.id),
            validated_data
        )
        return instance


class GodownEntrySerializer(serializers.ModelSerializer):
    status = serializers.CharField(read_only=True)
    no = serializers.CharField(read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    department_text = serializers.CharField(source='department.name', read_only=True)
    supplier_text = serializers.CharField(source='supplier.name', read_only=True)
    total_count = CountShowCharField(read_only=True)
    total_amount = AmountShowCharField(read_only=True)
    total_invoice_amount = AmountShowCharField(read_only=True)
    check_user_text = serializers.CharField(source='check_user.name', read_only=True)
    check_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    warehouse_text = serializers.CharField(source='warehouse.name', read_only=True)
    purchase_order_no = serializers.CharField(source='purchase_order.no', read_only=True)
    is_clear_text = serializers.SerializerMethodField()

    def get_is_clear_text(self, obj):
        payment = PurchasePayment.objects.filter(order=obj.purchase_order).first()
        if payment and payment.is_clear:
            return '是'
        else:
            return '否'

    class Meta:
        model = GodownEntry
        fields = '__all__'

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instance = GodownEntry.getById(id)
        else:
            instance = None
        serializer = GodownEntrySerializer(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 = GodownEntry.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加入库单[%s]，id=%d" % (instance.no, instance.id),
            validated_data
        )
        return instance

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

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

class GodownEntryDetailSerializer(serializers.ModelSerializer):
    product_base_text = serializers.CharField(source='product_base.name', read_only=True)
    product_base_model = serializers.CharField(source='product_base.model', read_only=True)
    unit_text = serializers.CharField(source='product_base.unit', read_only=True)
    count = CountShowCharField()
    price = PriceShowCharField()
    amount = AmountShowCharField(read_only=True)
    invoice_amount = AmountShowCharField()

    class Meta:
        model = GodownEntryDetail
        fields = '__all__'

    @staticmethod
    def factory(user, data):
        serializer = GodownEntryDetailSerializer(None, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        instance = GodownEntryDetail.objects.create(**validated_data)

        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加入库明细[%s]，id=%d" % (instance.product_base.name, instance.id),
            validated_data
        )
        return instance

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

    def validate(self, data):
        data['price'] = Formater.formatPrice(data['price'])
        data['count'] = Formater.formatCount(data['count'])
        data['amount'] = data['count'] * data['price']
        data['invoice_amount'] = Formater.formatAmount(data['invoice_amount'])
        warehouse_stock = WarehouseStock.getByWarehouseAndProduct(data['main'].warehouse, data['product_base'])
        data['warehouse_stock'] = warehouse_stock
        return data


class GodownEntryReturnSerializer(serializers.ModelSerializer):
    status = serializers.CharField(read_only=True)
    no = serializers.CharField(read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    department_text = serializers.CharField(source='department.name', read_only=True)
    supplier_text = serializers.CharField(source='supplier.name', read_only=True)
    total_count = CountShowCharField(read_only=True)
    total_amount = AmountShowCharField(read_only=True)
    warehouse_text = serializers.CharField(source='warehouse.name', read_only=True)
    check_user_text = serializers.CharField(source='check_user.name', read_only=True)
    check_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)

    class Meta:
        model = GodownEntryReturn
        fields = '__all__'

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instance = GodownEntryReturn.getById(id)
        else:
            instance = None
        serializer = GodownEntryReturnSerializer(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 = GodownEntryReturn.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加退货单[%s]，id=%d" % (instance.no, instance.id),
            validated_data
        )
        return instance

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

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


class GodownEntryReturnDetailSerializer(serializers.ModelSerializer):
    main_no = serializers.CharField(source='main.no', read_only=True)
    main_supplier = serializers.CharField(source='main.supplier.name', read_only=True)
    godownentry_no = serializers.CharField(source='godownentry_detail.main.no', read_only=True)
    main_warehouse = serializers.CharField(source='main.warehouse.name', read_only=True)
    main_create_user = serializers.CharField(source='main.create_user.name', read_only=True)
    main_create_time = TimeCharField(source='main.create_time', read_only=True)
    main_check_user = serializers.CharField(source='main.create_user.name', read_only=True)
    main_check_time = TimeCharField(source='main.check_time.name', read_only=True)
    product_base_text = serializers.CharField(source='product_base.name', read_only=True)
    product_base_model = serializers.CharField(source='product_base.model', read_only=True)
    main_notes = serializers.CharField(source='main.notes', read_only=True)

    count = CountShowCharField()
    price = PriceShowCharField(read_only=True)
    amount = AmountShowCharField()

    class Meta:
        model = GodownEntryReturnDetail
        fields = '__all__'

    @staticmethod
    def factory(user, data):
        serializer = GodownEntryReturnDetailSerializer(None, data=data)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        instance = GodownEntryReturnDetail.objects.create(**validated_data)

        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加退货明细[%s]，id=%d" % (instance.product_base.name, instance.id),
            validated_data
        )
        return instance

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

    def validate(self, data):
        data['count'] = Formater.formatCount(data['count'])
        data['amount'] = Formater.formatAmount(data['amount'])
        data['price'] = data['amount'] / data['count']
        warehouse_stock = WarehouseStock.getByWarehouseAndProduct(data['main'].warehouse, data['product_base'])
        data['warehouse_stock'] = warehouse_stock
        return data


class PurchasePaymentSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    check_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    check_user_text = serializers.CharField(source='check_user.name', read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    supplier_name = serializers.CharField(source='order.supplier.name', read_only=True)
    supplier_account = serializers.CharField(source='order.supplier.account', read_only=True)
    supplier_bank = serializers.CharField(source='order.supplier.opening_bank', read_only=True)
    order_no = serializers.CharField(source='order.no', read_only=True)
    payment = BooleanCharField(source='is_pay', read_only=True)
    is_clear_text = BooleanCharField(source='is_clear', read_only=True)
    amount = AmountShowCharFieldWithTwoDecimalPlaces()
    actual_amount = AmountShowCharFieldWithTwoDecimalPlaces()
    apply_amount = AmountShowCharFieldWithTwoDecimalPlaces()
    amount_CNY = serializers.SerializerMethodField()
    actual_amount_CNY = serializers.SerializerMethodField()
    apply_amount_CNY = serializers.SerializerMethodField()

    # review_user_text = serializers.CharField(source='review_user.name', read_only=True)
    # review_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    # ratify_user_text = serializers.CharField(source='ratify_user.name', read_only=True)
    # ratify_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)

    class Meta:
        model = PurchasePayment
        fields = '__all__'

    def get_amount_CNY(self, obj):
        retval = Formater.formatAmountShow(obj.amount)
        return utils.number2CNY(float(retval))

    def get_actual_amount_CNY(self, obj):
        retval = Formater.formatAmountShow(obj.actual_amount)
        return utils.number2CNY(float(retval))

    def get_apply_amount_CNY(self, obj):
        retval = Formater.formatAmountShow(obj.apply_amount)
        return utils.number2CNY(float(retval))

    @staticmethod
    def factory(user, data, id=None):
        if id:
            instance = PurchasePayment.getById(id)
        else:
            instance = None
        serializer = PurchasePaymentSerializer(instance, data=data, partial=True)
        serializer.user = user
        return serializer

    def create(self, validated_data):
        validated_data['create_user'] = self.user
        validated_data['department'] = self.user.department
        order = PurchasePayment.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加采购付款单[%s]，id=%d" % (order.no, order.id),
            validated_data
        )
        return order

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

    def update(self, instance, validated_data):
        instance = super(PurchasePaymentSerializer, self).update(instance, validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.UPDATE,
            u"修改采购付款单[%s]，id=%d" % (instance.no, instance.id),
            validated_data
        )
        return instance


class PurchasePaySerializer(serializers.ModelSerializer):
    payment_type_text = serializers.CharField(source='get_status_display', read_only=True)
    payment_time = serializers.DateTimeField(format=base.DATETIME_FORMAT, read_only=True)
    payment_user_text = serializers.CharField(source='payment_user.name', read_only=True)

    class Meta:
        model = PurchasePay
        fields = '__all__'

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

    def create(self, validated_data):
        validated_data['payment_user'] = self.user
        validated_data['payment_department'] = self.user.department
        order = PurchasePay.objects.create(**validated_data)
        BizLog.objects.addnew(
            self.user,
            BizLog.INSERT,
            u"添加采购付款单明细id=%d" % (order.id),
            validated_data
        )
        return order

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