# -*- coding: utf-8 -*-
""" 733上线更新线上数据 """
import logging

from django.core.management import BaseCommand

from live.models import LiveChannel, LiveStream
from utils.rpc import get_rpc_invoker


class Command(BaseCommand):
    """ Import famous doctor award list from txt to database """

    def handle(self, *args, **options):
        # 更新channel表user_id字段
        self.update_channel_user_id()

        # 更新steam结束
        self.update_stream_is_finish()

        # stream表更新finish_time
        self.update_stream_finish_time()

    def update_stream_is_finish(self):
        streams = LiveStream.objects.filter(is_finish=False).all()
        print("update_stream_is_finish, num:", len(streams))
        for stream in streams:
            if stream.save_replay_url and stream.status == False:
                stream.is_finish = True
                stream.save()

    def update_channel_user_id(self):
        channels = LiveChannel.objects.filter(user_id=None)
        print("update_channel_user_id, num:", len(channels))
        rpc = get_rpc_invoker()
        for channel in channels:
            if channel.user_id:
                continue
            person_id = channel.person_id
            try:
                result = rpc['api/person/user_info'](person_id=person_id).unwrap()
                channel.user_id = result.get("user_id")
                channel.save()
            except:
                logging.info("{person_id}找不到对应的user_id".format(person_id=channel.person_id))

    def update_stream_finish_time(self):
        print("update_stream_finish_time start")
        streams = LiveStream.objects.filter(is_finish=True).all()
        for stream in streams:
            if not stream.finish_time or (
                    stream.finish_time.hour == 0 and stream.finish_time.minute == 0 and stream.finish_time.second == 0):
                print(stream.finish_time, "更新为", stream.updated_time)
                stream.finish_time = stream.updated_time
                stream.save(update_fields=['finish_time'])