# -*- coding: UTF-8 -*-
from __future__ import absolute_import

from django.contrib.auth.models import User
from django.db.models import Q

from api.models.others import UserBlackList, PreBlackList
from api.models.types import REPORT_TYPE, REPORT_ACTIONS
from hera.queries.talos.report import ReportDQ
from message.utils.message import send_one_message
from mimas.event_manager import EventDispatcher
from rpc.decorators import bind_context
from rpc.tool.error_code import gen
from rpc.tool.error_code import CODES
from services.talos_service import topic_reply_update_reply_num_by_ids, topic_update_reply_num_by_ids
from statistic.models import Device
from talos.models import Report
from talos.models.topic import Problem, TopicReply
from ..datatables import PreBlackListDT
from ..queries.preblacklist import PreBlackListDQ


uri_pre = 'hera/report'
head_id = 22
reply_type = [REPORT_TYPE.REPLY, REPORT_TYPE.DIARY_REPLY]


def put_user_in_blacklist(user):
    if not user:
        return

    reports = Report.objects.filter(user_id=user.id)
    for report in reports:
        device_id = None
        if report.type == REPORT_TYPE.TOPIC and report.problem:
            device_id = report.problem.device_id
        elif report.type in reply_type and report.topic_reply:
            pass

        if report.is_handled and report.action != REPORT_ACTIONS.USER_MISTAKE and device_id:
            d = Device.objects.filter(device_id=device_id).last()
            UserBlackList.objects.get_or_create(bind_user=user, device=d)

    UserBlackList.objects.get_or_create(bind_user=user)


def remove_from_blacklist(user):
    if not user:
        return
    for device in Device.objects.filter(user=user):
        UserBlackList.objects.filter(device=device).delete()
    UserBlackList.objects.filter(bind_user=user).delete()


# @bind_context(uri_pre + '/list')
# def report_datatable(ctx, req_data):
#     dtobj = ReportDT(Report)
#     return dtobj.process(req_data, [])


@bind_context(uri_pre + '/query')
def report_query(ctx, options):
    dqobj = ReportDQ()
    return dqobj.process(**options)


@bind_context(uri_pre + '/preblackquery')
def preblack_query(ctx, options):
    dqobj = PreBlackListDQ()
    return dqobj.process(**options)


@bind_context(uri_pre + '/preblacklist')
def preblacklist_datatable(ctx, req_data):
    dtobj = PreBlackListDT(PreBlackList)
    return dtobj.process(req_data, [])


@bind_context(uri_pre + '/preblacklist/listupdate')
def preblacklist_listupdate(ctx, items):
    info = []
    for obj in items:
        preblacklist = PreBlackList.objects.get(pk=obj['key'])
        user = preblacklist.reported_user
        user_in_blacklist = UserBlackList.objects.filter(bind_user=user)
        is_blocked = obj['is_blocked']
        if user_in_blacklist and not is_blocked:
            remove_from_blacklist(user)
        if not user_in_blacklist and is_blocked:
            put_user_in_blacklist(user)

        info.append(obj['key'])
    return info


@bind_context(uri_pre + '/get_related')
def get_related_user(ctx, user_id):
    user_list = []
    devices = [device.device_id for device in Device.objects.filter(user=user_id)]
    devices = Device.objects.filter(device_id__in=devices)
    for device in devices:
        for user in device.user.all():
            user_list.append(user)
    users = list(set(user_list))
    user_list = []
    for user in users:
        data = {
            'id': str(user.id),
            'name': user.last_name,
        }
        user_list.append(data)
    return user_list


@bind_context(uri_pre + '/action')
def report_action(ctx, items):
    info = []
    head = User.objects.get(id=head_id)
    topic_reply_update_ids = []
    topic_update_ids = []
    for obj in items:
        user_obj = None
        report, _ = Report.objects.get_or_create(id=obj['key'])
        report_user_id = report.user_id  # 举报人

        if obj['action'] == u'0':
            return gen(CODES.UPDATE_FAIL)

        if obj['action'] != u'0'and not report.action:
            report.action = obj['action']
            report.is_handled = True
            report.save()

        # 解决数据report.action == '0'的情况
        if obj['action'] and report.action == u'0':
            report.action = obj['action']
            report.is_handled = True
            report.save()
        if obj['action'] == REPORT_ACTIONS.DOCTOR_AD:
            # 医生拉客
            if report.type == REPORT_TYPE.TOPIC:
                # 帖子回复的上下线
                if report.problem.is_online:
                    # report.problem.update_reply_num(False)
                    topic_update_ids.append(report.problem.id)
                report.problem.is_online = False
                report.problem.save()
                content = {
                    'text': u'你好，在社区发布话题时，请勿添加qq、微信、电话、外网链接等联系方式，再次违规将被禁言'
                }
                user_id = report.problem.user_id

            elif report.type in reply_type:
                # 帖子回复的上下线
                if report.topic_reply.is_online:
                    # report.topic_reply.update_reply_num(False)
                    topic_reply_update_ids.append(report.topic_reply.id)
                report.topic_reply.is_online = False
                report.topic_reply.save()
                content = {
                    'text': u'你好，在社区回复话题时，请勿添加qq、微信、电话、外网链接等联系方式，再次违规将被禁言'
                }
                user_id = report.topic_reply.user_id
            user_obj = User.objects.get(id=user_id)
            send_one_message(head, user_obj, content=content, push_stat_labels={'event_type':'push', 'event':'operator_daily'})

        elif obj['action'] == REPORT_ACTIONS.IMPROPER_SPEECH:
            # 疑似广告
            if report.type == REPORT_TYPE.TOPIC:
                # 帖子回复的上下线
                if report.problem.is_online:
                    # report.problem.update_reply_num(False)
                    topic_update_ids.append(report.problem.id)
                report.problem.is_online = False
                report.problem.save()
                content = {
                    'text': u'你好，请勿在社区发布广告，再次违规将被禁言'
                }
                user_id = report.problem.user_id
            elif report.type in reply_type:
                # 帖子回复的上下线
                if report.topic_reply.is_online:
                    # report.topic_reply.update_reply_num(False)
                    topic_reply_update_ids.append(report.topic_reply.id)
                report.topic_reply.is_online = False
                report.topic_reply.save()
                content = {
                    'text': u'你好，请勿在社区发布广告，再次违规将被禁言'
                }
                user_id = report.topic_reply.user_id
            user_obj = User.objects.get(id=user_id)
            send_one_message(head, user_obj, content=content, push_stat_labels={'event_type':'push', 'event':'operator_daily'})
        elif obj['action'] == REPORT_ACTIONS.SERIOUS_AD:
            # 严重垃圾广告
            if report.type == REPORT_TYPE.TOPIC:
                user_id = report.problem.user_id
            elif report.type in reply_type:
                user_id = report.topic_reply.user_id
            Problem.objects.filter(user_id=user_id).update(is_online=False)
            TopicReply.objects.filter(user_id=user_id).update(is_online=False)

            for device in Device.objects.filter(user__id=user_id):
                UserBlackList.objects.get_or_create(bind_user_id=user_id, device=device)
            UserBlackList.objects.get_or_create(bind_user_id=user_id, device=None)
        elif obj['action'] == REPORT_ACTIONS.PERSONAL_ATTACK:
            # 人身攻击
            if report.type == REPORT_TYPE.TOPIC:
                # 帖子回复的上下线
                if report.problem.is_online:
                    # report.problem.update_reply_num(False)
                    topic_update_ids.append(report.problem.id)
                report.problem.is_online = False
                report.problem.save()
                user_id = report.problem.user_id
            elif report.type in reply_type:
                # 帖子回复的上下线
                if report.topic_reply.is_online:
                    # report.topic_reply.update_reply_num(False)
                    topic_reply_update_ids.append(report.topic_reply.id)
                report.topic_reply.is_online = False
                report.topic_reply.save()
                user_id = report.topic_reply.user_id

            content = {
                'text': u'你好，请勿在社区内对他人进行人身攻击、谩骂侮辱，再次违规将被禁言'
            }
            user_obj = User.objects.get(id=user_id)
            send_one_message(head, user_obj, content=content, push_stat_labels={'event_type':'push', 'event':'operator_daily'})
        elif obj['action'] == REPORT_ACTIONS.LEAVE_CONTACT:
            # 留联系方式
            if report.type == REPORT_TYPE.TOPIC:
                # 帖子回复的上下线
                if report.problem.is_online:
                    # report.problem.update_reply_num(False)
                    topic_update_ids.append(report.problem.id)
                report.problem.is_online = False
                report.problem.save()
                user_id = report.problem.user_id
                content = {
                    'text': u'你好，请勿在社区留联系方式，再次违规将被禁言'
                }
            elif report.type in reply_type:
                # 帖子回复的上下线
                if report.topic_reply.is_online:
                    # report.topic_reply.update_reply_num(False)
                    topic_reply_update_ids.append(report.topic_reply.id)
                report.topic_reply.is_online = False
                report.topic_reply.save()
                user_id = report.topic_reply.user_id
                content = {
                    'text': u'你好，请勿在社区留联系方式，初次违规禁言1天，再次违规禁言7天，三次违规禁言一个月，三次以上永久禁言'
                }
            user_obj = User.objects.get(id=user_id)
            send_one_message(head, user_obj, content=content, push_stat_labels={'event_type':'push', 'event':'operator_daily'})
        elif obj['action'] == REPORT_ACTIONS.USER_MISTAKE:
            # 用户误点举报，不做处理
            pass

        elif obj['action'] == REPORT_ACTIONS.DOCTOR_SOLICIT \
                or obj['action'] == REPORT_ACTIONS.DOCTOR_LEAVE_CONTACT \
                or obj['action'] == REPORT_ACTIONS.OTHER_DOCTOR_LEAVE\
                or obj['action'] == REPORT_ACTIONS.ASK_FOR_CONTACT:
            if report.type == REPORT_TYPE.TOPIC:
                # 帖子回复的上下线
                if report.problem.is_online:
                    # report.problem.update_reply_num(False)
                    topic_update_ids.append(report.problem.id)
                report.problem.is_online = False
                report.problem.save()
                user_id = report.problem.user_id
                content_type = u'发表帖子'
                if obj['action'] == REPORT_ACTIONS.DOCTOR_SOLICIT:
                    content = {
                        'text': u'你好，请不要引导用户私信你，再次违规将被禁言'
                    }
                if obj['action'] == REPORT_ACTIONS.DOCTOR_LEAVE_CONTACT:
                    content = {
                        'text': u'你好，在社区{}时，请勿添加qq、微信、电话、外网链接等联系方式，再次违规将被禁言'.format(content_type)
                    }
                if obj['action'] == REPORT_ACTIONS.OTHER_DOCTOR_LEAVE:
                    content = {
                        'text': u'你好，请不要对非本医生名下的在线面诊和免费招募进行回复，再次违规将对你进行禁言处理'
                    }
                if obj['action'] == REPORT_ACTIONS.ASK_FOR_CONTACT:
                    content = {
                        'text': u'你好，请勿向他人索取联系方式，再次违规将被禁言'
                    }
            elif report.type in reply_type:
                # 帖子回复的上下线
                if report.topic_reply.is_online:
                    # report.topic_reply.update_reply_num(False)
                    topic_reply_update_ids.append(report.topic_reply.id)
                report.topic_reply.is_online = False
                report.topic_reply.save()
                user_id = report.topic_reply.user_id
                content_type = u'回复话题'
                if obj['action'] == REPORT_ACTIONS.DOCTOR_SOLICIT:
                    content = {
                        'text': u'您好，请不要引导用户私信您，初次违规禁言1天，再次违规禁言7天，三次违规禁言一个月，三次以上永久禁言'
                    }
                if obj['action'] == REPORT_ACTIONS.DOCTOR_LEAVE_CONTACT:
                    content = {
                        'text': u'您好，在社区{}时，请勿添加qq、微信、电话、外网链接等联系方式，初次违规禁言1天，再次违规禁言7天，三次违规禁言一个月，三次以上永久禁言'.format(content_type)
                    }
                if obj['action'] == REPORT_ACTIONS.OTHER_DOCTOR_LEAVE:
                    content = {
                        'text': u'您好，请不要对非本医生名下的在线面诊和免费招募进行回复，初次违规禁言1天，再次违规禁言7天，三次违规禁言一个月，三次以上永久禁言'
                    }
                if obj['action'] == REPORT_ACTIONS.ASK_FOR_CONTACT:
                    content = {
                        'text': u'您好，请勿向他人索取联系方式，再次违规将做禁言处理，您可以与想联系的用户互相关注通过私信取得联系'
                    }
            user_obj = User.objects.get(id=user_id)
            send_one_message(head, user_obj, content=content, push_stat_labels={'event_type':'push', 'event':'operator_daily'})
        elif obj['action'] == REPORT_ACTIONS.STEAL:
            # 盗取案例
            if report.type == REPORT_TYPE.TOPIC:
                # 帖子回复的上下线
                if report.problem.is_online:
                    topic_update_ids.append(report.problem.id)
                report.problem.is_online = False
                report.problem.save()
                user_id = report.problem.user_id
                content = {
                    'text': u'您好，您因被举报盗用他人案例已做禁言处理'
                }
            elif report.type in reply_type:
                # 帖子回复的上下线
                if report.topic_reply.is_online:
                    topic_reply_update_ids.append(report.topic_reply.id)
                report.topic_reply.is_online = False
                report.topic_reply.save()
                user_id = report.topic_reply.user_id
            user_obj = User.objects.get(id=user_id)
            send_one_message(head, user_obj, content=content,
                             push_stat_labels={'event_type': 'push', 'event': 'operator_daily'})
        report.save()
        info.append(obj)

        # push signal到mimas
        current_user = ctx.session.user
        if user_obj:
            EventDispatcher.sent_item_is_spam_signal(current_user.id, report.id, user_obj.id, report.type)

        # 用户被举报3次,自动进入黑名单审核列表
        if user_obj:
            q = ~Q(action=REPORT_ACTIONS.USER_MISTAKE)
            topics_count = Report.objects\
                .filter(problem__user_id=user_obj.id, type=REPORT_TYPE.TOPIC)\
                .filter(q).distinct().count()
            replies_count = Report.objects\
                .filter(topic_reply__user_id=user_obj.id, type=REPORT_TYPE.REPLY)\
                .filter(q).distinct().count()
            if topics_count + replies_count >= 3:
                user_exists = PreBlackList.objects.filter(reported_user=user_obj)
                if not user_exists:
                    PreBlackList.objects.create(
                        report_user_id=report_user_id,
                        reported_user=user_obj,
                        report_time=report.report_time,
                    )
    topic_reply_update_reply_num_by_ids(ids=topic_reply_update_ids, is_online=False)
    topic_update_reply_num_by_ids(ids=topic_update_ids, is_online=False)
    return info
