#!/usr/bin/env python
#-*- coding: utf-8 -*-

import copy
import datetime
import multiprocessing
from django.core.management import BaseCommand

from gm_types.mimas import GRABBING_PLATFORM

from qa.models import Answer, Question
from utils.rpc import rpc_client

create_time = datetime.datetime(2018, 1, 14)
edit_time = datetime.datetime(2018, 1, 1)  # 明哲要求数据源从1月1号开始统计


def _async_func(answer):

    content = answer.content
    if content.startswith("<p>") and content.endswith("</p>"):
        answer.content = content.replace("<p>", "").replace("</p>","")
        answer.save()


class Command(BaseCommand):

    def handle(self, *args, **kwargs):

        print("start")
        user_ids = rpc_client["api/user/get_vest_user_id"]().unwrap()
        user_ids = copy.deepcopy(user_ids)
        Answer.objects.filter(user__in=user_ids, create_time__gte=create_time,
                              is_online=True, platform=None).update(platform=GRABBING_PLATFORM.HERA)
        Question.objects.filter(user__in=user_ids, create_time__gte=create_time,
                              is_online=True, platform=None).update(platform=GRABBING_PLATFORM.HERA)
        user_ids += [22, ]
        answers = Answer.objects.filter(is_online=True, platform=None, content__isnull=False,
                                        create_time__gte=edit_time).exclude(user__in=user_ids)

        pool = multiprocessing.Pool(processes=4)
        for answer in answers:
            pool.apply_async(_async_func, args=(answer,))
        pool.close()
        pool.join()

        print("end")