from rest_framework import serializers

from apps.system.models import City, File, Organization, Province
from .models import QAction, QActionItem, QOrg, QTask, Quali, QualiLib
from django.db import transaction
from apps.system.serializers import CitySerializer, FileSimpleSerializer, OrganizationSimpleSerializer, DictSerializer, UserSimpleSerializer
from rest_framework.exceptions import ParseError


class QualiLibListSerializer(serializers.ModelSerializer):
    class Meta:
        model = QualiLib
        fields = '__all__'

class QualiListSerializer(serializers.ModelSerializer):
    province_name = serializers.CharField(source='province.name', read_only=True)
    city_name = serializers.CharField(source='city.name', read_only=True)
    org_ = OrganizationSimpleSerializer(source='org', read_only=True)
    citys_ = CitySerializer(source='citys', many=True, read_only=True)
    file_ = FileSimpleSerializer(source='file', read_only=True)
    class Meta:
        model = Quali
        fields = '__all__'


class QTaskCreateUpdateSerializer(serializers.ModelSerializer):
    orgs = serializers.PrimaryKeyRelatedField(label='上报公司ID列表',
                                              queryset = Organization.objects.all(), many=True, write_only=True)
    class Meta:
        model = QTask
        fields = ['name', 'end_date', 'orgs']
    
    def create(self, validated_data):
        with transaction.atomic():
            orgs = validated_data.pop('orgs')
            validated_data['state'] = '待发布'
            instance = super().create(validated_data)
            for i in orgs:
                QOrg.objects.get_or_create(qtask=instance, org=i, 
                                        defaults={'qtask': instance, 'org': i})
            return instance

    def update(self, instance, validated_data):
        with transaction.atomic():
            if instance.state == '已关闭':
                raise ParseError('任务已关闭,不可更改')
            orgs = validated_data.pop('orgs')
            instance = super().update(instance, validated_data)
            for i in orgs:
                QOrg.objects.get_or_create(qtask=instance, org=i,
                                        defaults={'qtask': instance, 'org': i})
            return instance
        

class QTaskListSerializer(serializers.ModelSerializer):
    orgs_count = serializers.SerializerMethodField()

    class Meta:
        model = QTask
        fields = '__all__'

    def get_orgs_count(self, obj):
        count = QOrg.objects.filter(qtask=obj).count()
        return count

class QTaskSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = QTask
        fields = '__all__'

class QOrgListSerializer(serializers.ModelSerializer):
    org_ = OrganizationSimpleSerializer(source='org', read_only=True)
    qtask_ = QTaskSimpleSerializer(source='qtask', read_only=True)
    class Meta:
        model = QOrg
        fields =  '__all__'


class QActionListSerializer(serializers.ModelSerializer):
    quali_name = serializers.CharField(source='quali.name', read_only=True)
    atype_name = serializers.CharField(source='atype.name', read_only=True)
    afield_name = serializers.CharField(source='afield.name', read_only=True)
    file_ = FileSimpleSerializer(source='file', read_only=True)
    create_by_ = UserSimpleSerializer(source='create_by', read_only=True) 
    class Meta:
        model = QAction
        fields = '__all__'


class QActionServiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = QAction
        fields = ['qtask', 'value2']
    
    def create(self, validated_data):
        validated_data['action'] = 'service:update'
        return super().create(validated_data)

class QualiCreateSerializer(serializers.ModelSerializer):
    citys = serializers.ListField(child=serializers.IntegerField(), label='城市ID列表')
    class Meta:
        model = Quali
        fields = ['name', 'type', 'grade', 'scope', 'level', 'province', 'city', 'description', 'citys', 'file', 'end_date']


class QualiUpdateSerializer(serializers.ModelSerializer):
    citys = serializers.ListField(child=serializers.IntegerField(), label='城市ID列表')
    id = serializers.IntegerField(label='修改资质的ID')
    class Meta:
        model = Quali
        fields = ['scope', 'level', 'description', 'id', 'citys', 'file', 'end_date']

class QualiSerializer(serializers.ModelSerializer):
    class Meta:
        model = Quali
        fields = '__all__'

class QActionQualiCreateSerializer(serializers.ModelSerializer):
    value2 = QualiCreateSerializer()
    class Meta:
        model = QAction
        fields = ['qtask', 'value2']

    def create(self, validated_data):
        validated_data['action'] = 'quali:create'
        value2 = self.data['value2']
        if value2['type'] in ['CMA', 'CNAS']:
            value2['name'] = value2['type']
        validated_data['value2'] = value2
        # if value2.get('province', None):
        #     value2['province'] = value2['province'].id
        # if value2.get('city', None):
        #     value2['city'] = value2['city'].id
        # if value2.get('file', None):
        #     value2['file'] = value2['file'].id
        return super().create(validated_data)

class QActionQualiUpdateSerializer(serializers.ModelSerializer):
    value2 = QualiUpdateSerializer()
    class Meta:
        model = QAction
        fields = ['qtask', 'value2']
    
    def create(self, validated_data):
        validated_data['action'] = 'quali:update'
        validated_data['value2'] = self.data['value2']
        return super().create(validated_data)

class QActionNoChangeSerializer(serializers.ModelSerializer):
    class Meta:
        model = QAction
        fields = ['qtask']

class QActionACreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = QAction
        fields = ['atype', 'afield', 'file', 'num', 'qtask', 'num2', 'num3', 'num4']
        extra_kwargs = {'atype': {'required': True}, 'afield': {'required': True}, 'file': {'required': True}}
    
    def create(self, validated_data):
        validated_data['action'] = 'ablity:create'
        return super().create(validated_data)


class QActionItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = QActionItem
        fields = ['action', 'field', 'value1', 'value2', 'city']


class QActionDetailSerializer(serializers.ModelSerializer):
    update_detail = QActionItemSerializer(source='items_qaction', many=True, read_only=True)
    value2 = serializers.SerializerMethodField()
    quali_name = serializers.CharField(source='quali.name', read_only=True)
    atype_name = serializers.CharField(source='atype.name', read_only=True)
    afield_name = serializers.CharField(source='afield.name', read_only=True)
    file_ = FileSimpleSerializer(source='file', read_only=True)
    create_by_ = UserSimpleSerializer(source='create_by', read_only=True) 
    class Meta:
        model = QAction
        fields ='__all__'

    def get_value2(self, obj):
        value2 = obj.value2
        if isinstance(value2, dict):
            if value2.get('province', None):
                value2['province_name'] = Province.objects.get(id=value2['province']).name
            if value2.get('city', None):
                value2['city_name'] = City.objects.get(id=value2['city']).name
            if value2.get('citys', None):
                value2['citys_'] = CitySerializer(instance=City.objects.filter(id__in=value2['citys']), many=True).data
            if value2.get('file', None):
                value2['file_'] = FileSimpleSerializer(instance=File.objects.get(id=value2['file'])).data
        return value2