# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function

from django.db.models import Q
from django.conf import settings
from gm_types.gaia import SERVICE_ORDER_TYPE, VIDEO_CODE_STATUS
from gm_upload import set_video_watermark
from gm_upload.utils.qiniu_tool import QiniuTool
import json
import hashlib
import requests
from urlparse import urljoin

from api.models import Service
from api.models import Hospital, Doctor
from hippo.models import HospitalVideo
from celery import shared_task
from rpc.cache import hospital_cache, doctor_search_tags_cache, hospital_search_tags_cache
from rpc.tool.es_helpers import get_objects_from_queryset_and_pk_list
from rpc.tool.log_tool import logging_exception
import jieba

from search.utils.service import filter_service

HOSPITAL_NAME_PREFIX = 'name_pre:'


@shared_task
def hospital2redis(hospital_id=None,user=None):
    """将医院名字分词存入redis

    :return:
    """

    def add_hospital_key(hospital):
        if not hospital:
            return
        keys = jieba.cut_for_search(hospital['name'])
        for key in keys:
            key = HOSPITAL_NAME_PREFIX + key
            hospital_cache.sadd(key, hospital['id'])

    if hospital_id:
        try:
            hospital = Hospital.objects.get(id=hospital_id)
            hospital = hospital.hospital_detail()
            add_hospital_key(hospital)
        except:
            logging_exception()
    else:
        # 清空已有数据
        #hospital_cache.flushdb()

        start_num = 0
        count = 100
        try:
            while True:
                hospitals = Hospital.objects.exclude(id='wanmeizhensuo')
                hospitals = [h.hospital_detail(user) for h in hospitals[start_num:start_num+count]]
                for hospital in hospitals:
                    add_hospital_key(hospital)

                if len(hospitals) < count:
                    break

                start_num = start_num + count
        except:
            logging_exception()

    return hospital_cache.dbsize()


@shared_task
def calc_doctor_tags_for_search(doctor_id=None):
    '''
    计算医生搜索的tag相关
    :return:
    '''
    if doctor_id:
        doctor = Doctor.objects.get(id=doctor_id)
        ids = filter_service(size=100, filters={"doctor_id": doctor.id},
                             sort_type=SERVICE_ORDER_TYPE.ORDER_HIGHEST_SALES)['service_ids']
        services = Service.objects.filter(id__in=ids)
        result = []
        for service in services:
            result += service.get_tags_for_search()
        result = sorted(set(result), key=result.index)
        doctor_search_tags_cache.set(str(doctor.id), json.dumps(result))
        return result

    doctors = Doctor.objects.filter(is_online=True)
    for doctor in doctors:
        try:
            ids = filter_service(size=100, filters={"doctor_id": doctor.id},
                                 sort_type=SERVICE_ORDER_TYPE.ORDER_HIGHEST_SALES)['service_ids']
            services = get_objects_from_queryset_and_pk_list(
                Service.objects.filter(is_online=True), pk_list=ids
            )
            result = []
            for service in services:
                result += service.get_tags_for_search()
            result = sorted(set(result), key=result.index)
            doctor_search_tags_cache.set(doctor.id, json.dumps(result))
        except:
            print(doctor.id)
            logging_exception()


@shared_task
def calc_hospital_tags_for_search():
    hospitals = Hospital.objects.all()
    for hospital in hospitals:
        try:
            ids = list(Doctor.objects.filter(hospital_id=hospital.id, is_online=True).values_list('id', flat=True))
            ids = filter_service(size=100, filters={"doctor_ids": ids},
                                 sort_type=SERVICE_ORDER_TYPE.ORDER_HIGHEST_SALES)['service_ids']

            services = get_objects_from_queryset_and_pk_list(
                Service.objects.filter(is_online=True), pk_list=ids
            )
            result = []
            for service in services:
                result += service.get_tags_for_search()
            result = sorted(set(result), key=result.index)
            hospital_search_tags_cache.set(hospital.id, json.dumps(result))
        except:
            print(hospital.id)
            logging_exception()


@shared_task
def set_water_mark_to_video_hospital(id):
    video = HospitalVideo.objects.get(id=id)
    video.persistent_status = VIDEO_CODE_STATUS.WAITING
    pid = set_video_watermark(
        video.video_url,
        hashlib.md5(video.video_url).hexdigest() + '.mp4',
        water_mark_url=settings.WATER_MARK_URL_FOR_VIDEO
    )
    video.persistentId = pid
    video.water_url = ''
    video.save(update_fields=['persistentId', 'persistent_status', 'water_url'])


@shared_task
def check_water_mark_video_is_finish_hospital():
    videos = HospitalVideo.objects.filter(~Q(persistent_status=VIDEO_CODE_STATUS.SUCCESS))
    for video in videos:
        try:
            if video.persistentId:
                result = json.loads(requests.get('http://api.qiniu.com/status/get/prefop?id=' +
                                                 video.persistentId).text)
                if result.get('code') != 0:
                    continue

                if result['items'][0]['code'] == 0:
                    water_url = result['items'][0]['key']

                    # 刷新cdn缓存
                    QiniuTool.refresh_qiniu_resource_cache([urljoin(settings.VIDEO_HOST, water_url)])

                    video.water_url = water_url
                    video.persistent_status = VIDEO_CODE_STATUS.SUCCESS
                    video.save(update_fields=['persistent_status', 'water_url'])
                else:
                    video.persistent_status = result['items'][0]['code']
                    video.save(update_fields=['persistent_status'])
        except:
            logging_exception()

