# 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
from fish.constant import *

EMAIL_TITLE = '''【%(action)s%(position)s】的提醒'''
EMAIL_CONTENT = '''品种合约【%(name)s】
%(notify_type)s【%(ranges)s】
预期趋势【%(trend)s】
在【%(times)s】【%(action)s】
点位【%(last_price)s】
【%(remark)s】'''


def cta(timestamp, last_price, task):
    last_price = Decimal(last_price)
    max_val = Decimal(task.get('max_val'))
    min_val = Decimal(task.get('min_val'))
    notify_point = None  # 符合通知点
    state = ING
    action = '突破'
    position = None
    notify_type = '镜像空间'
    remark = task.get('remark')
    trend = task.get('trend')
    ranges = '{}-{}'.format(task.get('max_val'), task.get('min_val'))
    if last_price >= max_val or last_price <= min_val:
        if max_val == min_val:  # 预值
            if trend == RAISE:
                f = last_price >= max_val
            else:
                f = last_price <= max_val
            if f:
                notify_point = task.get('max_val')
                position = '预值'
                notify_type = '预值'
                ranges = task.get('max_val')
                state = DONE
        else:
            if (trend == RAISE and last_price < min_val) or (trend == FALL and last_price > max_val):
                action = '回调'
                position = '突破原点'
                notify_point = task.get('max_val')
                state = FAIL
            else:
                position = '0.382'
                notify_point = task.get('p382')
                state = DONE
    else:
        if task.get('p333'):
            p333 = Decimal(task.get('p333'))
            if (trend == RAISE and last_price >= p333) or (trend == FALL and last_price <= p333):
                position = '0.333'
                notify_point = task.get('p333')
        if task.get('p382'):
            p382 = Decimal(task.get('p382'))
            if (trend == RAISE and last_price >= p382) or (trend == FALL and last_price <= p382):
                position = '0.382'
                notify_point = task.get('p382')
                state = DONE

    if notify_point:
        try:
            TaskNotify.objects.create(task_id=task.get('id'), point=notify_point, curr_point=str(last_price))
            if state != ING:
                Task.remove_task(task, state)
            times = datetime.fromtimestamp(timestamp)
            title = EMAIL_TITLE % {'action': action, 'position': position}
            content = EMAIL_CONTENT % {'name': task.get('instrument_name'), 'notify_type': notify_type,
                                       'ranges': ranges,
                                       'trend': get_trend_name(trend), 'times': times, 'action': action,
                                       'last_price': last_price,
                                       'remark': remark}
            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(',')
    timestamp = int(data[0].split('.')[0])
    instrument = data[1]
    last_price = 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')
