# coding=utf-8

import json

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

from apps.order.models import *
from apps.base import Formater

from utils.exceptions import CustomError


class OrderSerializer(serializers.ModelSerializer):
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    customer_name = serializers.CharField(source='customer.name', read_only=True)
    customer_tel = serializers.CharField(source='customer.tel', read_only=True)
    total_amount = serializers.SerializerMethodField()
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    express_info = serializers.SerializerMethodField()
    dispatch_user_text = serializers.CharField(source='dispatch_user.employee.name', read_only=True)
    dispatch_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    cancel_user_text = serializers.CharField(source='cancel_user.employee.name', read_only=True)
    cancel_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)

    class Meta:
        model = Order
        fields = '__all__'

    def get_total_amount(self, obj):
        return Formater.formatPriceShow(obj.total_amount)

    def get_express_info(self, obj):
        if obj.express_no and obj.express_company:
            return '{}，{}'.format(obj.express_no, obj.express_company.name)
        return ''


class OrderDetailsSerializer(serializers.ModelSerializer):
    commodity_name = serializers.CharField(source='commodity.name', read_only=True)
    price = serializers.SerializerMethodField()
    amount = serializers.SerializerMethodField()
    images = serializers.SerializerMethodField()

    class Meta:
        model = OrderDetails
        fields = '__all__'

    def get_price(self, obj):
        return Formater.formatPriceShow(obj.price)

    def get_amount(self, obj):
        return Formater.formatPriceShow(obj.amount)

    def get_images(self, obj):
        if obj.commodity.show_image:
            return obj.commodity.show_image.get_path()
        return ''
