# coding=utf8
from rest_framework import serializers
from core.framework.exceptions import ManageAPIException
from apps.task.models import Task
from apps.base.models import Contacts
from fish.instruments import INSTRUMENT_CHOICES, get_instrument_name
from apps.manage.serializers import NamePrimaryKeyRelatedField, DateTimeCharField


class ManageTaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ('id', 'name', 'emails', 'active')

    def validate(self, attrs):
        return attrs

    def to_representation(self, instance):
        result = serializers.ModelSerializer.to_representation(self, instance)
        result['active_display'] = '正常' if instance.active else '失效'
        return result


class ManageTaskAddSerializer(serializers.ModelSerializer):
    instrument = serializers.ChoiceField(choices=INSTRUMENT_CHOICES, label='''产品合约''')
    code = serializers.CharField(label='编号')
    max_val = serializers.DecimalField(max_digits=10, decimal_places=2, label='高点')
    min_val = serializers.DecimalField(max_digits=10, decimal_places=2, label='低点')
    type = serializers.ChoiceField(choices=(('A', '多'), ('D', '空')), label='趋势')
    emails = NamePrimaryKeyRelatedField(label='''通知邮箱''', queryset=Contacts.objects.all(),
                                        select_value='email', flag=True)

    class Meta:
        model = Task
        fields = ('instrument', 'code', 'max_val', 'min_val', 'type', 'emails')

    def validate(self, attrs):
        if attrs.get('max_val') < attrs.get('min_val'):
            raise ManageAPIException(errmsg='高点不能低于低点')
        instrument = attrs.get('instrument') + attrs.get('code')
        instrument_name = get_instrument_name(attrs.get('instrument')) + attrs.get('code')
        attrs['instrument_name'] = instrument_name
        attrs['instrument'] = instrument
        config = {'max_val': str(attrs.get('max_val')), 'min_val': str(attrs.get('min_val')), 'type': attrs.get('type')}
        attrs['config'] = config

        emails = attrs.get('emails').split('#')
        attrs['emails'] = emails
        _r = ''
        if attrs.get('max_val') == attrs.get('min_val'):
            _r = '预值【{}】'.format(attrs.get('max_val'))
        else:
            _r = '镜像空间【{}-{}】'.format(attrs.get('max_val'), attrs.get('min_val'))
        name = '【{}】，{}，预期趋势【{}】'.format(instrument_name, _r, '多' if attrs.get('type') == 'A' else '空')
        attrs['name'] = name
        attrs.pop('code', None)
        attrs.pop('max_val', None)
        attrs.pop('min_val', None)
        attrs.pop('type', None)
        return attrs

    def to_representation(self, instance):
        result = serializers.ModelSerializer.to_representation(self, instance)
        return result

    def create(self, validated_data):
        task = serializers.ModelSerializer.create(self, validated_data)
        task.set_active_list(task.instrument)
        return task
