# coding=utf8
import traceback
from datetime import datetime
from decimal import Decimal
from django.db import IntegrityError
from django.http.response import HttpResponse
from apps.task.models import Task, TaskNotify
from core.utils.email import send
from django_q.tasks import async_task
from core.utils import log as logger


def cta(timestamp, last_price, task):
    print(task)
    _type = task.get('type')
    max_val = Decimal(task.get('max_val'))
    min_val = Decimal(task.get('min_val'))
    style = None
    point = ''
    point_val = None
    over = False
    if _type == 'A':
        if max_val == min_val:
            if last_price > min_val:
                style = '突破'
                point = '预值'
                point_val = min_val
                over = True
        else:
            if last_price < min_val:
                style = '回调'
                point = '突破原点'
                point_val = min_val
                over = True
            m = max_val - min_val
            p1 = min_val + m * Decimal('0.333')
            p2 = min_val + m * Decimal('0.382')
            if last_price >= p1:
                style = '突破'
                point = '0.333'
                point_val = p1
            if last_price >= p2:
                style = '突破'
                point = '0.382'
                point_val = p2
                over = True
    if _type == 'D':
        if max_val == min_val:
            if last_price < min_val:
                style = '突破'
                point = '预值'
                point_val = min_val
                over = True
        else:
            if last_price > max_val:
                style = '回调'
                point = '突破原点'
                point_val = max_val
                over = True
            m = max_val - min_val
            p1 = max_val - m * Decimal('0.333')
            p2 = max_val - m * Decimal('0.382')
            if last_price <= p1:
                style = '突破'
                point = '0.333'
                point_val = p1
            if last_price <= p2:
                style = '突破'
                point = '0.382'
                point_val = p2
                over = True
    _title = '【{}{}】的提醒'
    _content = '【{}】，镜像空间【{}-{}】，预期趋势【{}】；在【{}】【{}】点位为【{}】'
    times = datetime.fromtimestamp(timestamp)
    title = _title.format(style, point)
    content = _content.format(task.get('name'), task.get('max_val'), task.get('min_val'), task.get('type'), times,
                              style, last_price)
    if style:
        try:
            TaskNotify.objects.create(task_id=task.get('id'), point=point_val)
            if over:
                Task.remove_task(task)
            logger.error(content)
            send(title, content, task.get('emails'))
        except IntegrityError:
            pass
        except Exception as e:
            trace = traceback.format_exc()
            logger.error(trace)


def push(request):
    data = request.GET.get('data')
    data = data.split(',')
    print(data)
    timestamp = int(data[0].split('.')[0])
    instrument = data[1]
    last_price = Decimal(data[2])
    tasks = Task.get_active_list(instrument)
    for task in tasks:
        async_task(cta, timestamp, last_price, task)
        # cta(timestamp, last_price, task)
    return HttpResponse('ok')
