# coding=utf-8
import json
from rest_framework import serializers
from apps.option.models import Option
from utils.exceptions import CustomError
from apps.option.serializers import OptionSerializer
from .models import ReportCustomer

class ReportCustomerSerializer(serializers.ModelSerializer):
    gender_text = serializers.CharField(source='get_gender_display', read_only=True)
    report_status_text = serializers.CharField(source='get_report_status_display', read_only=True)
    check_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    source_text = serializers.CharField(source='source.name', read_only=True)
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    project_text = serializers.SerializerMethodField()

    def get_project_text(self, obj):
        project = obj.project.all()
        return ','.join(project.values_list('name', flat=True))

    class Meta:
        model = ReportCustomer
        fields = '__all__'

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        instance = super(ReportCustomerSerializer, self).create(validated_data)
        projects = self.initial_data['project']
        if projects:
            projects = json.loads(projects)
        else:
            raise CustomError(u'请选择项目')

        for project in projects:
            instance.project.add(project)
        return instance

    def update(self, instance, validated_data):
        instance = super(ReportCustomerSerializer, self).update(instance, validated_data)
        projects = self.initial_data['project']
        if projects:
            projects = json.loads(projects)
        else:
            raise CustomError(u'请选择项目')

        for project in projects:
            instance.project.add(project)
        return instance

