# 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
from fish.constant import TREND, get_trend_name


class ManageTaskSerializer(serializers.ModelSerializer):
    state_display = serializers.CharField(source='get_state_display', read_only=True)
    class Meta:
        model = Task
        fields = ('id', 'name', 'emails', 'state', 'state_display', 'created_at', 'remark')

    def validate(self, attrs):
        return attrs

    def to_representation(self, instance):
        result = serializers.ModelSerializer.to_representation(self, instance)
        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='低点')
    trend = serializers.ChoiceField(choices=TREND, label='趋势')
    emails = NamePrimaryKeyRelatedField(label='''通知邮箱''', queryset=Contacts.objects.all(),
                                        select_value='email', flag=True)

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

    def validate(self, attrs):
        if attrs.get('max_val') < attrs.get('min_val'):
            raise ManageAPIException(errmsg='高点不能低于低点')
        instrument = attrs.get('instrument') + attrs.get('code').replace(' ', '')
        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')), 'trend': attrs.get('trend')}
        attrs['config'] = config

        emails = attrs.get('emails').split('#')
        attrs['emails'] = emails
        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, get_trend_name(attrs.get('trend')))
        attrs['name'] = name
        attrs.pop('code', None)
        attrs.pop('max_val', None)
        attrs.pop('min_val', None)
        attrs.pop('trend', 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
