# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

import datetime
import random

import pili
import time
import logging
import traceback
from django.conf import settings
from django.db import models
from django.db import transaction
from django.utils import timezone
from gm_types.gaia import TOPIC_TYPE, LIVE_MSG_TYPE, LIVE_STATUS
from gm_types.mimas import LIVE_CLARITY
from gm_upload import ImgUrlField, IMG_TYPE

from talos.cache.live import (
    live_view_max_cache, live_view_num_cache, live_user_enter_time_cache,
    live_view_sum_cache, live_fake_vote_cache, live_cache,
)
from talos.libs.datetime_utils import ts_now_as_score
from talos.libs.image_utils import get_full_path
from talos.models.topic import ProblemTag, Problem
from talos.rpc import CODES
from talos.rpc import gen
from talos.rpc import logging_exception
from talos.services.doctor import DoctorService
from talos.services.goods import GoodsService
from talos.services.hospital import HospitalService
from talos.services.tag import TagService
from talos.services.user import UserService
from utils.tasks import common_push


class ShortvideoBlackList(models.Model):
    class Meta:
        verbose_name = u'小视频黑名单'
        app_label = 'api'
        db_table = 'api_shortvideo_black_list'

    user_id = models.IntegerField(verbose_name=u'小视频用户名')
    is_online = models.BooleanField(verbose_name=u'是否生效')


class LiveChannel(models.Model):
    class Meta:
        verbose_name = u'直播频道'
        app_label = 'talos'
        db_table = 'api_live_channel'

    user_id = models.IntegerField(verbose_name=u'用户外键id')
    person_id = models.CharField(verbose_name=u'用户外键id', max_length=64)
    created_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    updated_time = models.DateTimeField(verbose_name=u'更新时间', default=timezone.now)
    title = models.CharField(verbose_name=u'标题', max_length=128, default='')
    cover_url = models.CharField(verbose_name=u'封面地址', max_length=128, default='')
    status = models.BooleanField(verbose_name='是否直播', default=False)

    def data(self, user):
        stream = self.now_stream
        return stream.data(user)

    def empty_data(self, user):
        social_info = None
        if user:
            from social.models import SocialInfo
            social_info = SocialInfo(uid=user.id)
        self_user = UserService.get_user_by_person_id(self.person_id)
        is_following = social_info and social_info.is_following_user_for_live(uid=self_user.id) or False

        return {
            "id": self.id,
            "user_portrait": self_user.portrait,
            "uname": self_user.nickname,
            'title': self_user.nickname + u'的直播间',
            'audience_num': 0,
            'is_following': is_following,
            'url': '',
            'cover_url': get_full_path(self.cover_url, '-w'),
            'user_id': self_user.id,
            'status': self.status,
            'm_url': '',
            'stream_id': self.id,
            'tags': [],
            'channel_id': self.id,
            'membership_level': self_user.membership_level,
            'notice': '',
            'live_duration': 0,
        }

    @property
    def now_stream(self):
        return self.streams.order_by('-id').first()

    @property
    def live_view_num(self):
        return self.now_stream.live_view_num

    def add_view_num(self):
        return self.now_stream.add_view_num()

    def sub_view_num(self):
        return self.now_stream.sub_view_num()


class LiveStream(models.Model):
    class Meta:
        verbose_name = u'直播流'
        app_label = 'talos'
        db_table = 'api_live_stream'

    channel = models.ForeignKey(LiveChannel, null=True, related_name=u'streams')
    status = models.BooleanField(verbose_name='是否直播', default=False)
    created_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now)
    updated_time = models.DateTimeField(verbose_name=u'更新时间', default=timezone.now)
    finish_time = models.DateTimeField(verbose_name=u'结束时间')
    stream_key = models.CharField(verbose_name=u'直播流的key', max_length=128, default='', db_index=True)
    save_replay_url = models.CharField(verbose_name=u'直播流的回放地址', max_length=128, default='', db_index=True)

    title = models.CharField(verbose_name=u'标题', max_length=128, default='')
    cover_url = models.CharField(verbose_name=u'封面地址', max_length=128, default='')
    topic = models.OneToOneField(Problem, related_name=u'stream', null=True)
    is_finish = models.BooleanField(verbose_name='是否关闭', default=False)
    is_show = models.BooleanField(verbose_name='是否展示', default=False)
    notice = models.CharField(verbose_name='公告', max_length=128, default='')
    clarity = models.IntegerField(verbose_name='清晰度', choices=LIVE_CLARITY, default=LIVE_CLARITY.DEFAULT)

    # 这个字段是给统计使用
    max_view_num = models.IntegerField(verbose_name=u'最大在线人数', default=0)
    sum_view_num = models.IntegerField(verbose_name=u'直播观看总人数', default=0)
    sum_view_num_fake = models.IntegerField(verbose_name=u'直播观看总人数(灌水)', default=0)

    # 弹幕回放
    replay_danmu = models.TextField(verbose_name=u'弹幕回放')

    # 美购相关
    hospital_id = models.CharField(verbose_name=u'医院外建', null=True, max_length=100)
    service_id = models.CharField(verbose_name=u'美购外建', null=True, max_length=100)

    is_test = models.BooleanField(verbose_name='是否是测试数据', default=False)
    stick_status = models.IntegerField(verbose_name=u'置顶状态', default=0)
    stick_timestamp = models.IntegerField(verbose_name=u'置顶操作的时间戳', default=0)

    def get_live_stream_user_id(self):
        try:
            person_id = list(LiveChannel.objects.filter(id=self.channel.id).values_list("person_id", flat=True))
            logging.info("get ----person:%s" % person_id)
            return person_id[0]
        except:
            logging_exception()
            return None

    @classmethod
    def get_current_streams(cls, is_test=False):
        """获取当前正在进行的直播流"""

        if is_test:
            res = cls.objects.filter(status=True, is_finish=False).order_by('-id')\
                .select_related('channel__person_id')
        else:
            res = cls.objects.filter(status=True, is_finish=False, is_test=False).order_by('-id')\
                .select_related('channel__person_id')
        return res

    @classmethod
    def create_stream(cls, user, channel, title, cover_url, tag_id, hospital_id=None, service_id=None,
                      notice='', clarity=LIVE_CLARITY.DEFAULT, is_test=False):
        with transaction.atomic():
            stream_key = 'live' + str(int(time.time())) + u'_' + str(user.id)
            stream = LiveStream()
            stream.channel = channel
            stream.status = False
            stream.stream_key = stream_key
            stream.title = title
            stream.cover_url = cover_url
            stream.hospital_id = hospital_id
            stream.service_id = service_id
            stream.notice = notice
            stream.clarity = clarity
            stream.is_test = is_test
            stream.save()
            LiveStreamTag(live_stream=stream, tag_id=tag_id).save()
            live_fake_vote_cache.setex(str(stream.id), 60 * 10, 0)
            from live.tasks import calc_sleep_user_for_prepare
            calc_sleep_user_for_prepare.delay(stream.id)
            return stream

    @classmethod
    def create_or_update_stream(cls, stream, user, channel, title, cover_url, tag_id, hospital_id=None,
                                service_id=None, notice='', clarity=LIVE_CLARITY.DEFAULT, is_test=False):
        if stream.check_stream_status_from_qiniu():
            gen(CODES.LIVE_IS_CONTINUE)

        stream = LiveStream.objects.filter(channel=channel).order_by('-updated_time').first()
        timedetla = datetime.datetime.now() - stream.updated_time
        if (timedetla.seconds > settings.LIVE_TIME_OUT and not stream.status) or stream.is_finish:
            stream = LiveStream.create_stream(user, channel, title, cover_url, tag_id, hospital_id, service_id,
                                              notice, clarity, is_test=is_test)
            create_live = True
        else:
            stream.update_stream(title, cover_url, tag_id, hospital_id, service_id, notice, clarity, is_test=is_test)
            create_live = False
        return stream, create_live

    def update_stream(self, title, cover_url, tag_id, hospital_id=None, service_id=None,
                      notice='', clarity=LIVE_CLARITY.DEFAULT, is_test=False):
        with transaction.atomic():
            self.updated_time = datetime.datetime.now()
            self.title = title
            self.cover_url = cover_url
            self.notice = notice
            self.clarity = clarity
            self.is_test = is_test
            if hospital_id:
                self.hospital_id = hospital_id
            if service_id:
                self.service_id = service_id
            streamtag = LiveStreamTag.objects.filter(live_stream=self).first()
            if streamtag:
                streamtag.tag_id = tag_id
                streamtag.save()
            self.save()

    def check_stream_status_from_qiniu(self):
        if not self.status:
            return False
        mac = pili.Mac(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)
        client = pili.Client(mac)
        hub = client.hub(settings.QINIU_HUB_NAME)
        s = hub.get(self.stream_key)
        try:
            # qiniu nolive 会抛异常
            s.status()
            return True
        except:
            return False

    @property
    def live_status_stream(self):
        if self.is_finish:
            return False

        timedetla = datetime.datetime.now() - self.updated_time
        if timedetla.seconds > settings.LIVE_TIME_OUT and self.status is False:
            return False

        if timedetla.seconds < settings.LIVE_TIME_OUT and self.status is False:
            return True

        return self.status

    @property
    def live_status(self):
        if self.live_status_stream:
            return LIVE_STATUS.LIVE
        else:
            return LIVE_STATUS.NOLIVE

    @property
    def live_duration(self):
        if self.is_finish:
            return ((self.finish_time or self.updated_time) - self.created_time).seconds
        return (datetime.datetime.now() - self.created_time).seconds

    def data(self, user):
        social_info = None
        if user:
            from social.models import SocialInfo
            social_info = SocialInfo(uid=user.id)
        self_user = UserService.get_user_by_person_id(self.channel.person_id)
        is_following = social_info and social_info.is_following_user_for_live(uid=self_user.id) or False

        channel = self.channel

        return {
            "id": self.id,
            "user_portrait": self_user.portrait,
            "uname": self_user.nickname,
            'title': self.title,
            'audience_num': channel.live_view_num,
            'is_following': is_following,
            'url': self.url,
            'cover_url': get_full_path(self.cover_url, '-webp'),
            'user_id': self_user.id,
            'status': self.live_status,
            'm_url': self.m_url,
            'stream_id': self.id,
            'tags': self.get_tags(),
            'channel_id': channel.id,
            'membership_level': self_user.membership_level,
            'notice': self.notice,
            'live_duration': self.live_duration,
            'user_level': {
                'membership_icon': self_user.membership_icon,
                'level_icon': self_user.level_icon,
                'constellation_icon': self_user.constellation_icon,
            },
        }

    def data_v1(self, user):
        '''
        新版灰度首页返回的数据格式
        :return:
        '''
        result = self.data(user)
        new_info = {
            'content': '',
            'comment_num': self.livemsg_set.count(),
            'vote_num': live_fake_vote_cache.get(str(self.id)).decode() if live_fake_vote_cache.get(str(self.id)) else 0
        }
        result.update(new_info)
        return result

    def data_for_redis(self):
        return {
            'id': self.id,
            'title': self.title
        }

    def replay_data(self, user):
        data = self.data_live(user)
        data['status'] = self.live_status
        data['url'] = settings.QINIU_REPLAY_LIVE_DOMAIN + self.save_replay_url
        data['topic_id'] = self.topic.id

        view_num = int(self.topic.view_num)
        data['audience_num'] = str(view_num + self.live_view_num)

        return data

    def replay_data_for_list(self, user):
        data = self.data(user)
        data['status'] = self.live_status
        data['url'] = settings.QINIU_REPLAY_LIVE_DOMAIN + self.save_replay_url
        data['topic_id'] = self.topic.id

        view_num = int(self.topic.view_num)
        data['audience_num'] = str(view_num + self.live_view_num)

        return data

    def get_topic_reply_info(self):
        """deprecated func name typo"""
        return {
            'source': settings.QINIU_REPLAY_LIVE_DOMAIN + self.save_replay_url,
            'cover': get_full_path(self.cover_url, '-w'),
            'content': self.title
        }

    def get_topic_replay_info(self):
        return {
            'source': settings.QINIU_REPLAY_LIVE_DOMAIN + self.save_replay_url,
            'cover': get_full_path(self.cover_url, '-w'),
            'content': self.title
        }

    @property
    def url(self):
        return pili.rtmp_play_url(settings.QINIU_LIVE_RMTP_PLAY_DOMAIN,
                                  settings.QINIU_HUB_NAME, self.stream_key)

    @property
    def m_url(self):
        return pili.hls_play_url(settings.QINIU_LIVE_RMTP_PLAY_DOMAIN,
                                 settings.QINIU_HUB_NAME, self.stream_key)

    @property
    def live_view_num(self):
        try:
            num = live_view_num_cache.get(str(self.id))
            if num:
                num = int(num)
                return self.display_num(num)
            else:
                return 0
        except ValueError:
            return 0

    def display_num(self, num):
        if num == 1:
            # 主播不算用户
            result = 0
        else:
            result = 100 + (num - 1) * 70
        return int(result + self.get_addition_view_num())

    def create_topic(self):
        self_user = UserService.get_user_by_person_id(self.channel.person_id)
        with transaction.atomic():
            topic = Problem()
            topic.user_id = self_user.id
            topic.topic_type = TOPIC_TYPE.TOPIC
            topic.ask = self.title
            topic.save()
            try:
                tag = self.tags[0]
                ProblemTag.objects.get_or_create(problem_id=topic.id, tag_id=tag.id)
            except IndexError:
                pass
            self.topic = topic
            self.save()
            # push to the liver fans
            common_push.delay(uname=self_user.nickname, uid=self_user.id, topic_id=self.channel.id, push_type="live")
        Problem.set_view_amount_of_id(topic.id, self.live_view_num)

    @property
    def tags(self):
        tag_ids = LiveStreamTag.objects.filter(live_stream_id=self.id).values_list('tag_id', flat=True)
        tag_ids = list(tag_ids)
        tags = TagService.get_tags_by_tag_ids(tag_ids)
        return tags

    def get_tags(self):
        """problems's tags."""
        ts = []
        for tag in self.tags:
            data = {'name': tag.name, 'tag_id': tag.id, "tag_type": tag.tag_type}
            ts.append(data)
        return ts

    def set_first_user_enter_time_cache(self):
        start_time = ts_now_as_score()
        if not live_user_enter_time_cache.get(str(self.id)):
            live_user_enter_time_cache.set(str(self.id), start_time)

    def clear_redis_info(self):
        from live.managers import LiveMsgManager
        live_msg_manager = LiveMsgManager()
        live_msg_manager.clear_redis(self.id)
        # 删除统计相关星系
        self.max_view_num = live_view_max_cache.get(str(self.id))
        self.sum_view_num = live_view_sum_cache.get(str(self.id))
        self.sum_view_num_fake = self.live_view_num
        self.save()
        live_view_max_cache.delete(str(self.id))
        live_view_sum_cache.delete(str(self.id))

    def add_view_num(self):
        try:
            live_view_num_cache.incr(str(self.id), 1)
            live_view_sum_cache.incr(str(self.id))
            self.set_live_view_max_num()
        except:
            logging_exception()

    def get_addition_view_num(self):
        result = 0
        start_time = live_user_enter_time_cache.get(str(self.id))
        if not start_time:
            return 0
        now_time = ts_now_as_score()

        random.seed(now_time)
        random_num = random.randrange(-3, 3)
        if start_time:
            num = int(now_time) - int(start_time)

            if num <= 0:
                result = 0
            elif 1 <= num <= 600:
                result = abs(int(num * 59 / 60) + random_num)
            elif 600 <= num <= 1800:
                result = int(590 + (num - 600) * 69 / 60) + random_num
            elif 1800 <= num <= 7200:
                result = int(2070 + (num-1800) * 79 / 60) + random_num
            elif 7200 < num:
                result = 10021
        return result

    def set_live_view_max_num(self):
        try:
            num = live_view_max_cache.get(str(self.id))
            now_num = live_view_num_cache.get(str(self.id))
            if num and now_num and int(num) < int(now_num):
                live_view_max_cache.set(str(self.id), now_num)
            elif int(now_num):
                live_view_max_cache.set(str(self.id), now_num)
        except ValueError:
            logging_exception()

    def sub_view_num(self):
        try:
            num = live_view_num_cache.decr(str(self.id))
            if num <= 0:
                live_view_num_cache.incr(str(self.id))
        except:
            logging_exception()

    def set_status(self, flag):
        now = datetime.datetime.now()
        channel = self.channel
        with transaction.atomic():
            self.status = flag
            channel.status = flag
            self.updated_time = now
            channel.updated_time = now
            self.save(update_fields=['status', 'updated_time'])
            channel.save(update_fields=['status', 'updated_time'])

    def data_live(self, user):
        result = self.data(user)
        hospital_data = {}
        if self.hospital_id:
            hospital = HospitalService.get_hospital_info_by_hospital_id(self.hospital_id)
            if hospital:
                hospital_data = hospital
                hospital_data['portrait'] = get_full_path(hospital['portrait'], '-half')
        result['hospital'] = hospital_data
        result['show_hospital'] = True if hospital_data else False
        service_data = {}
        if self.service_id:
            service_data = GoodsService.get_live_service_info_by_id_with_cache(self.service_id)
        else:
            service_id = LiveStreamService.get_first_live_service_id(self.id)
            if service_id:
                service_data = GoodsService.get_live_service_info_by_id_with_cache(service_id)

        result['service'] = service_data
        result['show_service'] = True if service_data else False
        result['is_doctor'] = DoctorService.if_person_is_doctor(self.channel.person_id)
        return result

    @classmethod
    def batch_data(cls, streams, user):
        data = []
        social_info = None
        if user:
            from social.models import SocialInfo
            social_info = SocialInfo(uid=user.id)
        person_ids = [stream.channel.person_id for stream in streams]
        persons = UserService.get_users_by_person_ids(person_ids)

        for stream in streams:
            pid = stream.channel.person_id
            data.append({
                "id": stream.id,
                "user_portrait": persons[pid].portrait,
                "uname": persons[pid].nickname,
                'title': stream.title,
                'audience_num': stream.channel.live_view_num,
                'is_following': social_info and social_info.is_following_user_for_live(uid=persons[pid].id) or False,
                'url': stream.url,
                'cover_url': get_full_path(stream.cover_url, '-w'),
                'user_id': persons[pid].id,
                'status': stream.live_status,
                'm_url': stream.m_url,
                'stream_id': stream.id,
                'tags': stream.get_tags(),
                'channel_id': stream.channel.id,
                'hospital_id': stream.hospital_id,
                'service_id': stream.service_id,
                'person_id': pid,
                'membership_level': persons[pid].membership_level,
                'user_level': {
                    'membership_icon': persons[pid].membership_icon,
                    'level_icon': persons[pid].level_icon,
                    'constellation_icon': persons[pid].constellation_icon,
                },
                'topic_id': stream.topic.id if stream.topic else None,
                'topic_view_num': int(stream.topic.view_num) if stream.topic else 0,
                'save_replay_url': stream.save_replay_url,
            })
        return data

    @classmethod
    def batch_replay_data(cls, streams, user):
        data = cls.batch_data_live(streams, user)
        for stream in data:
            stream['url'] = settings.QINIU_REPLAY_LIVE_DOMAIN + stream['save_replay_url']
            stream['audience_num'] = str(stream['topic_view_num'] + stream['audience_num'])
        return data

    @classmethod
    def batch_data_live(cls, streams, user):
        data = cls.batch_data(streams, user)
        hospital_ids = [stream.hospital_id for stream in streams if stream.hospital_id]
        hospitals = HospitalService.get_hospital_info_by_ids(hospital_ids)

        service_ids = [stream.service_id for stream in streams if stream.service_id]
        services = GoodsService.get_live_service_info_by_ids(service_ids)

        person_ids = [stream.channel.person_id for stream in streams]
        doctors = DoctorService.list_doctors_by_person_ids(person_ids)
        for stream in data:
            hospital = stream["hospital_id"] and hospitals.get(str(stream["hospital_id"])) or {}
            if hospital:
                hospital['portrait'] = get_full_path(hospital['portrait'], '-half')
            stream['hospital'] = hospital
            stream['show_hospital'] = bool(hospital)

            # 批量接口 没有用到service / show_service 字段，不做版本兼容
            service = services[str(stream["service_id"])] if stream["service_id"] else {}
            stream['service'] = service
            stream['show_service'] = bool(service)

            doctor = doctors.get(str(stream["person_id"]), None)
            stream['is_doctor'] = True if doctor else False
            stream['doctor'] = doctor

        return data

    def get_topic_is_online(self):

        try:
            topic_id = list(set(LiveStream.objects.filter(id=self.id).values_list("topic", flat=True)))
            if topic_id:
                is_online = list(set(Problem.objects.filter(id=topic_id[0]).values_list("is_online", flat=True)))
                if is_online:
                    return is_online[0]
                else:
                    return None
            return None
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
            return None


class LiveStreamTag(models.Model):
    class Meta:
        app_label = 'talos'
        db_table = 'api_streamtag'

    live_stream = models.ForeignKey(LiveStream)
    tag_id = models.IntegerField()

    def __unicode__(self):
        return "%s:%d" % (self.tag_id, self.live_stream_id)


class LiveWhiteList(models.Model):
    class Meta:
        verbose_name = u'直播白名单'
        app_label = 'talos'
        db_table = 'api_live_white_list'

    user_id = models.IntegerField(verbose_name=u'用户外键id')
    is_online = models.BooleanField(verbose_name=u'是否生效')


class LiveMsg(models.Model):
    class Meta:
        verbose_name = u'弹幕数据'
        app_label = 'talos'
        db_table = 'api_live_msg'

    person_id = models.CharField(verbose_name=u'用户外键id', max_length=64)
    stream = models.ForeignKey(LiveStream)
    msg = models.CharField(verbose_name=u'标题', max_length=128, default='')
    created_time = models.DateTimeField(verbose_name=u'创建时间', default=timezone.now, db_index=True)
    type = models.IntegerField(verbose_name=u'消息类型', default=LIVE_MSG_TYPE.TEXT_MSG)
    is_vest_send = models.BooleanField(verbose_name=u'是否为马甲用户发送', default=False)

    def data(self):
        if self.type == int(LIVE_MSG_TYPE.NOTIFI_MSG):
            uname = ''
        else:
            self_user = UserService.get_user_by_person_id(self.person_id)
            uname = self_user.nickname

        return {
            'id': self.id,
            'text': self.msg,
            'name': uname,
            'type': self.type
        }


class LiveComment(models.Model):
    class Meta:
        verbose_name = u'直播机器人评论'
        app_label = 'talos'
        db_table = 'api_live_comment'

    comment = models.CharField(verbose_name=u'评论文案', max_length=128, default='')
    weight = models.IntegerField(verbose_name=u'权重')
    is_deleted = models.BooleanField(verbose_name=u'是否删除', default=False)


class ZhiboConfig(models.Model):
    class Meta:
        verbose_name = u'直播配置信息'
        verbose_name_plural = u'直播配置信息'
        db_table = 'api_zhiboconfig'
        app_label = 'talos'

    description = models.CharField(max_length=10, verbose_name=u'描述')
    foreshowcover_img = ImgUrlField(img_type=IMG_TYPE.ZHIBO, max_length=128, verbose_name=u'预告封面图片')
    foreshowpage_img = ImgUrlField(img_type=IMG_TYPE.ZHIBO, max_length=128, verbose_name=u'预告页面图片')

    # 首页Feed流所需图片
    trailer_image = ImgUrlField(img_type=IMG_TYPE.ZHIBO, max_length=128, verbose_name=u'首页直播预告')
    cover_image = ImgUrlField(img_type=IMG_TYPE.ZHIBO, max_length=128, verbose_name=u'首页直播封面')

    anchor_user_id = models.IntegerField(verbose_name=u'用户外键id')
    start_time = models.DateTimeField(verbose_name=u'开始时间')
    end_time = models.DateTimeField(verbose_name=u'结束时间')
    zhibo_time = models.DateTimeField(verbose_name=u'直播时间')
    is_online = models.BooleanField(default=False, verbose_name=u'是否上线')
    is_shouyejingxuan = models.BooleanField(default=False, verbose_name=u'是否在首页－精选显示')
    is_shouyezhibo = models.BooleanField(default=False, verbose_name=u'是否在首页－直播显示')
    is_zhiboliebiao = models.BooleanField(default=False, verbose_name=u'是否在直播列表页显示')
    adorder_id = models.CharField(max_length=12, verbose_name=u'广告订单ID', null=True)
    # 完整描述 2017-05-15
    full_desc = models.CharField(max_length=500, verbose_name=u'完整描述', default='')

    def data_for_backend(self, user, trailer=True):
        social_info = None
        if user:
            from social.models import SocialInfo
            social_info = SocialInfo(uid=user.id)

        is_following = social_info and social_info.is_following_user_for_live(uid=self.anchor_user_id) or False
        self_user = UserService.get_user_by_user_id(self.anchor_user_id)

        from live.managers import get_or_create_channel_by_user_id
        return {
            'id': self.id,
            'conf_id': self.id,
            'user_id': self.anchor_user_id,
            'user_portrait': self_user.portrait,
            'title': self.full_desc,
            'desc': self.description,
            'is_following': is_following,
            "uname": self_user.nickname,
            'cover_url': get_full_path(self.foreshowcover_img, '-w'),
            'choice_cover_url': get_full_path(self.trailer_image) if trailer else get_full_path(self.cover_image),
            'status': int(LIVE_STATUS.NOTICE),
            'membership_level': self_user.membership_level,
            'channel_id': get_or_create_channel_by_user_id(self.anchor_user_id).id,
            'stream_id': 0,  # 无效字段 只是用来占位 方便客户端填充结构
            'tags': [],  # 无效字段 只是用来占位 方便客户端填充结构
            'audience_num': 0,  # 无效字段 只是用来占位 方便客户端填充结构
            'url': '',
            'content': self.full_desc,
            "zhibo_time": self.zhibo_time.timestamp(),
            "comment_num": 0,
            "vote_num": 0,
            "user_level": {
                'level_icon': self_user.level_icon,
                'membership_icon': self_user.membership_icon,
                'constellation_icon': self_user.constellation_icon,
            },
        }

    def data_for_ship(self):
        from live.managers import get_or_create_channel_by_user_id
        channel = get_or_create_channel_by_user_id(self.anchor_user_id)
        return {
            'desc': self.description,
            'background': self.foreshowpage_img,
            'channel_id': channel.id,

            # 7.0 add  share_data

            'cover_url': get_full_path(self.foreshowcover_img, '-w'),
            'uname': UserService.get_user_by_person_id(channel.person_id).nickname,
            'start_time': "{}月{}日 {}: {}".format(
                self.zhibo_time.month, self.zhibo_time.day,
                "%02d" % self.zhibo_time.hour, "%02d" % self.zhibo_time.minute
            ),
        }


class LiveStreamService(models.Model):
    """ 直播-商品（全部逻辑在`live`服务，这里保持低版本兼容) """

    class Meta:
        verbose_name = u'直播-商品'
        app_label = 'talos'
        db_table = 'api_live_stream_service'

    stream_id = models.IntegerField(db_index=True, verbose_name=u"关联的直播流ID")
    service_id = models.IntegerField(db_index=True, verbose_name=u"关联的美购id")
    is_deleted = models.BooleanField(verbose_name=u'是否删除')

    @classmethod
    def get_first_live_service_id(cls, stream_id):
        """ 获取 第一件直播-商品 """

        obj = cls.objects.filter(stream_id=stream_id, is_deleted=False).first()

        if obj:
            return obj.service_id

        return None


class LiveFloatingConfig(object):
    """直播悬浮窗后台配置"""
    def __init__(self):
        self.rc = live_cache

    @property
    def key(self):
        return 'floating_config'

    def get(self):
        ret = self.rc.get(self.key) or 0
        if ret:
            ret = int(ret)
        return ret

    def set(self, stream_id):
        if not stream_id:
            self.rc.delete(self.key)
            return
        self.rc.set(self.key, stream_id)
