# -*- coding=utf-8 -*-
from rest_framework import serializers as serializer
from console.contract.models import Contract
# EnterpriseSerializer
from common.accounts.serializers import UsersCommonSerializer
from common.accounts.models import Users


class ContractInfoSerializer(serializer.ModelSerializer):
    customer = serializer.SerializerMethodField()
    business_entity = serializer.SerializerMethodField()
    contract_party = serializer.SerializerMethodField()
    salesman = serializer.SerializerMethodField()
    customer_contact = serializer.SerializerMethodField()

    def get_customer(self, obj):
        id = None
        name = None
        if obj.customer:
            id = obj.customer.id
            name = obj.customer.name
        return {
            "id": id,
            "name": name,
        }

    def get_business_entity(self, obj):
        return obj.business_entity.name if obj.business_entity else ''

    def get_contract_party(self, obj):
        return obj.contract_party.name if obj.contract_party else ''

    def get_salesman(self, obj):
        try:
            return UsersCommonSerializer(obj.salesman).data
        except Users.DoesNotExist:
            return {}

    def get_customer_contact(self, obj):
        try:
            return UsersCommonSerializer(obj.customer_contact).data
        except Users.DoesNotExist:
            return {}

    class Meta:
        model = Contract
        fields = ("id", "customer", "code", "business_entity",
                  "contract_party", "salesman", "amount", "entry_date",
                  "effective_date", "end_date", "closed_date", "type",
                  "customer_contact", "remark")
