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

import json

from django.utils import timezone
from django.conf import settings
from django.core.management import BaseCommand

from api.models import (
    Doctor,
    Hospital,
    Person,
)
from talos.models.topic import (
    Problem,
)
from talos.models.live import (
    LiveChannel,
    LiveStream,
)


class Command(BaseCommand):

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

        # 上海机构对应的user_id
        hospital_user_ids = list(Hospital.objects.using(settings.SLAVE_DB_NAME).filter(
            city_id="shanghai").values_list("user_id", flat=True))

        # 上海的医生对应的user_id
        doctor_user_ids = list(Doctor.objects.using(settings.SLAVE_DB_NAME).filter(
            hospital__city_id="shanghai").values_list("user_id", flat=True))

        # 取user_id 对应的person id
        _user_id = set()
        _user_id.update(set(filter(None, hospital_user_ids)))
        _user_id.update(set(filter(None, doctor_user_ids)))

        _person_ids = list(Person.objects.filter(
            user_id__in=list(_user_id)
        ).using(settings.SLAVE_DB_NAME).values_list("id", flat=True))
        person_ids = [id.hex for id in _person_ids]

        # person_id 对应的直播渠道
        live_channel_ids = list(LiveChannel.objects.filter(
            person_id__in=person_ids).values_list("id", flat=True))

        # 获取所有直播贴
        _topic_ids = list(LiveStream.objects.filter(
            channel_id__in=live_channel_ids
        ).values_list("topic_id", flat=True))

        # 查询所有在线的贴子
        topic_ids = list(Problem.objects.filter(
            pk__in=_topic_ids, is_online=True
        ).values_list("id", flat=True))

        # ------------直播贴下线------------------

        # 写日志
        with open("offline_live_topic_ids.txt", "a+") as f:
            f.write(json.dumps(topic_ids))

        # 一次下线 200 条 直播贴
        cnt = 200
        while topic_ids:
            _ids = topic_ids[:cnt]
            Problem.objects.filter(id__in=_ids).update(
                is_online=False,
                last_modified=timezone.now()
            )
            topic_ids = topic_ids[cnt:]
