#!/usr/bin/env python
# coding=utf-8
from django.db.models import Q
from django.utils import timezone
import datetime
import time

from gm_types.doctor import DOCTOR_MESSAGE_TYPE
from doctor.models import Content, HomePopup, HomeSlide, Bulletin, DoctorActivity, BulletinRead, BulletinExtra

from api.tool.user_tool import get_doctor_from_context
from api.tool.log_tool import logging_exception
from hippo.models import MerchantRelevance, UserExtra, Doctor
from rpc.decorators import bind, bind_context, list_interface


@bind('doctor/content/home_popup')
def home_popup():
    """
        since 2.0.0
        首页弹窗图
    """
    popup = HomePopup.objects.filter(
        is_online=True,
        begin_time__lte=timezone.now,
        end_time__gte=timezone.now,
    ).first()
    return popup and popup.to_data()


@bind_context('doctor/content/home_slide')
def home_slide(ctx):
    """
        since 2.0.0
        首页轮播图
    """
    banners = HomeSlide.objects.filter(
        is_online=True,
        begin_time__lte=timezone.now,
        end_time__gte=timezone.now,
    ).order_by('ordering')
    result = [banner.to_data() for banner in banners]
    return result


@bind_context('doctor/content/home_bulletin')
@list_interface(offset_name='start_num', limit_name='count')
def home_bulletin(ctx, count=10, start_num=0):
    """
        since 2.0.0
        消息公告
    """
    # TODO Deprecated 重构的时候没返回total_count, see 'doctor/content/bulletins'
    bulletins = Bulletin.objects.filter(is_online=True).order_by('-online_time')
    result = [b.to_data() for b in bulletins[start_num:start_num + count]]
    return result


@bind_context('doctor/content/bulletins')
@list_interface(offset_name='start_num', limit_name='count')
def home_bulletins(ctx, doctor_id, count=10, start_num=0):
    """
        since 2.0.0
        消息公告
    """
    """
    获取医生的商户id和city
    """
    merchant_id = MerchantRelevance.objects.get(doctor_id=doctor_id).merchant_id
    doctor = Doctor.objects.get(id=doctor_id)
    city_id = doctor.hospital.city_id

    def add_is_read(obj, doctor_id):
        if BulletinRead.objects.filter(doctor_id=doctor_id, bulletin_id=obj['id']).exists():
            obj.update({
                'is_read': True
            })
        else:
            if obj['date'] < time.mktime(datetime.datetime(2017, 9, 18).timetuple()):
                obj.update({
                    'is_read': True
                })
            else:
                obj.update({
                    'is_read': False
                })
        return obj

    bulletinextra_objs = BulletinExtra.objects.filter(Q(area='1') | Q(area='2', city_id=city_id) | Q(merchant_id=merchant_id))
    bulletin_ids = []
    for item in bulletinextra_objs:
        bulletin_ids.append(item.bulletin_id)
    bulletins = Bulletin.objects.filter(is_online=True, id__in=bulletin_ids).order_by('-online_time')
    result = {
        'total': bulletins.count(),
    }
    result['bulletins'] = [
        add_is_read(b.to_data(), doctor_id) for b in bulletins[start_num: start_num + count]
        ]
    return result


@bind_context('doctor/index/bulletins')
def index_bulletins(ctx, doctor_id):
    """
    首页更美公告部分
    :param ctx:
    :param doctor_id:
    :return:
    """
    """
    获取医生的商户id和city
    """
    merchant_id = MerchantRelevance.objects.get(doctor_id=doctor_id).merchant_id
    doctor = Doctor.objects.get(id=doctor_id)
    city_id = doctor.hospital.city_id
    bulletinextra_objs = BulletinExtra.objects.filter(Q(area='1') | Q(area='2', city_id=city_id) | Q(merchant_id=merchant_id))
    bulletin_ids = []
    for item in bulletinextra_objs:
        bulletin_ids.append(item.bulletin_id)
    bulletins = Bulletin.objects.filter(is_online=True, id__in=bulletin_ids).order_by('-online_time')
    b_list = [b.to_data() for b in bulletins]
    result = []
    for bi in b_list:
        if BulletinRead.objects.filter(doctor_id=doctor_id, bulletin_id=bi['id']).exists():
            bi['status'] = 1
        else:
            if bi['date'] < time.mktime(datetime.datetime(2017, 9, 18).timetuple()):
                bi['status'] = 1
            else:
                bi['status'] = 0
        result.append(bi)
    return result


@bind_context('doctor/content/get')
def get_content(ctx, bulletin_id=None, content_id=None):
    """
        since 2.0.0
        获取内容
        updated@2020.02.26: 允许不需要登陆访问， 用于视频面诊且参数只有content_id
    """

    try:
        if bulletin_id:
            content = Bulletin.objects.get(id=bulletin_id).content
        if content_id:
            content = Content.objects.get(id=content_id)
    except Content.DoesNotExist:
        logging_exception()
        raise
    except Bulletin.DoesNotExist:
        logging_exception()
        raise
    result = {
        'title': content.title,
        'content': content.content,
    }
    doctor = get_doctor_from_context(ctx)

    if doctor:
        # 将此公告加入已读列表
        if bulletin_id:
            br,_ = BulletinRead.objects.get_or_create(doctor_id=doctor.id, bulletin_id=bulletin_id)

    # 判断是否是医生可以报名参加的活动
    try:
        activity = DoctorActivity.objects.get(content=content)
        result['activity'] = {
            'id': activity.id,
            'status': activity.status(doctor),
        }
    except DoctorActivity.DoesNotExist:
        pass
    return result
