# coding:utf-8
from __future__ import absolute_import, unicode_literals

import datetime
import operator
from functools import reduce

from django.conf import settings
from django.db.models import Q
from celery import shared_task

from utils.rpc import rpc_client, logging_exception

from talos.services import UserService
from talos.models.topic import Problem
from talos.models.topic import TopicReply
from talos.models.diary import Diary




@shared_task
def crash_check():
    """查询包含crash相关关键字的帖子／日记／回复
    邮件发送至
    邮件格式：用户ID－帖子时间－帖子类型（含帖子ID）－内容
    """

    text = []
    yesterday = datetime.datetime.now() + datetime.timedelta(days=settings.DAYS_BEFORE_TODAY)
    q_diary = []
    q_problem = []
    q_reply = []
    # 拼关键字查询条件Q
    for keyword in settings.CRASH_KEYWORDS:
        for field in settings.MODEL_FIELDS['diary']:
            item_q = Q(**{field + '__icontains': keyword})
            q_diary.append(item_q)

    for keyword in settings.CRASH_KEYWORDS:
        for field in settings.MODEL_FIELDS['problem']:
            q_problem.append(Q(**{field + '__icontains': keyword}))

    for keyword in settings.CRASH_KEYWORDS:
        for field in settings.MODEL_FIELDS['topicreply']:
            q_reply.append(Q(**{field + '__icontains': keyword}))

    try:
        # check
        crash_diary_set = Diary.objects.filter(reduce(operator.or_, q_diary)).exclude(
            created_time__lte=yesterday).select_related()
        for crash_item in crash_diary_set:
            text.append(email_body_format(crash_item.user_id, crash_item.last_modified,
                                          Diary._meta.verbose_name, crash_item.id,
                                          crash_item.title, crash_item.created_time))

        crash_set_problem = Problem.objects.filter(reduce(operator.or_, q_problem)).exclude(
            created_time__lte=yesterday).select_related()
        for cp in crash_set_problem:
            text.append(email_body_format(cp.user_id, cp.last_modified, Problem._meta.verbose_name,
                                          cp.pk, cp.ask + cp.answer, cp.created_time))

        crash_set_reply = TopicReply.objects.filter(reduce(operator.or_, q_reply)).exclude(
            reply_date__lte=yesterday).select_related()
        for cr in crash_set_reply:
            text.append(email_body_format(cr.user_id, cr.reply_date,
                                          TopicReply._meta.verbose_name,
                                          cr.pk, cr.content, cr.reply_date))

        # 发邮件
        if not text:
            text.append(u'未发现crash相关帖子信息！')

        rpc_client['internal_email/send'](
            to=settings.SENDTO,
            subject=settings.SUBJECT,
            text=''.join(text)
        ).unwrap()

    except:
        logging_exception()


def email_body_format(userid=None, time=None, type_content=None, content_id=None, content_text=None,
                      create_time=None):
    """格式化邮件内容
    """
    try:
        user = UserService.get_user_by_user_id(user_id=userid)
        device = user.devices.last()
        device_info = u'设备: {}\n 系统版本：{}\n 平台：{}'.format(device.model, device.os_version, device.platform)
    except:
        device_info = '未知设备'

    return u'用户ID：{userid}\n 创建时间：{create_time}\n 时间：{time}\n  ' \
           u'帖子类型：{type_content}({content_id}):\n  帖子内容：{content_text}\n'.format( \
        userid=userid, time=time, type_content=type_content,
        content_id=content_id, content_text=content_text, create_time=create_time) + device_info
