from decimal import Decimal
from django.db import models
from django.contrib.postgres.fields import JSONField, ArrayField
from core.orm.model import BaseModel
from django.core.cache import cache
from fish.constant import *


class Task(BaseModel):
    name = models.CharField(max_length=200, null=True)
    instrument = models.CharField(max_length=200)
    instrument_name = models.CharField(max_length=200, null=True)
    emails = ArrayField(models.CharField(max_length=200, blank=True), verbose_name='通知邮箱')
    state = models.CharField(max_length=20, choices=TASK_STATE_CHOICES, default=ING)
    remark = models.TextField(default='', verbose_name='备注')
    config = JSONField()

    @property
    def code(self):
        pass

    @property
    def max_val(self):
        pass

    @property
    def min_val(self):
        pass

    @property
    def trend(self):
        pass

    @staticmethod
    def set_active_list(instrument):
        active_list = Task.objects.filter(instrument=instrument, state=ING)
        dd = []
        for al in active_list:
            d = {'id': al.pk, 'instrument': al.instrument, 'instrument_name': al.instrument_name, 'emails': list(al.emails),
                 'trend': al.config.get('trend'), 'max_val': al.config.get('max_val'),
                 'min_val': al.config.get('min_val'), 'remark': al.remark}
            if al.config.get('min_val') != al.config.get('max_val'):  # 鱼头镜像
                max_val = Decimal(al.config.get('max_val'))
                min_val = Decimal(al.config.get('min_val'))
                m = max_val - min_val
                if al.config.get('trend') == RAISE:  # 估多
                    p333 = min_val + m * Decimal('0.333')
                    p382 = min_val + m * Decimal('0.382')
                else:  # 估空
                    p333 = max_val - m * Decimal('0.333')
                    p382 = max_val - m * Decimal('0.382')
                d.update({'p333': str(p333)})
                d.update({'p382': str(p382)})
            dd.append(d)
        if not dd:
            cache.set(instrument, [], 0)
        else:
            cache.set(instrument, dd, 24 * 60 * 60)

    @staticmethod
    def get_active_list(instrument):
        active_list = cache.get(instrument)
        return active_list if active_list else []

    @staticmethod
    def remove_task(task, state):
        Task.objects.filter(pk=int(task.get('id'))).update(state=state)
        Task.set_active_list(task.get('instrument'))


class TaskNotify(BaseModel):
    task_id = models.IntegerField()
    point = models.CharField(max_length=200)
    curr_point = models.CharField(max_length=200, default='0')

    class Meta:
        ordering = ['-id']
        unique_together = ('task_id', 'point')
