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

from api.models import Tag
from api.tool.image_utils import get_thumb_path
from api.tool.user_tool import filter_user_nick_name
from hippo.models import Doctor, UserExtra, Hospital
from rpc.decorators import bind

from api.models.slide import HomepageOperate
from gm_types.gaia import HOMEPAGE_OPERATE_LOCATION, DOCTOR_TYPE, TAG_TYPE
from gm_types.gaia import HOT_SEARCH_JUMP_TYPE
from rpc.decorators import cache_page


@bind('api/diary/jump_operate')
def diary_jump_operate(location=19):

    jump_operate = HomepageOperate.objects.filter(location=location, is_online=True).order_by('-last_time').first()
    if not jump_operate:
        return {}

    return {
        'jump': jump_operate.jump,
        'jump_type': jump_operate.jump_type,
        'title': jump_operate.title,
    }


@bind('api/diary/service_type')
@cache_page(60 * 5)
def get_diary_service_type(diary_id):
    _locations = [HOMEPAGE_OPERATE_LOCATION.ADV_DIARY_1,
                  HOMEPAGE_OPERATE_LOCATION.ADV_DIARY_2,
                  HOMEPAGE_OPERATE_LOCATION.ADV_DIARY_3,
                  HOMEPAGE_OPERATE_LOCATION.ADV_DIARY_4]
    _jum_type = HOT_SEARCH_JUMP_TYPE.DIARY[0]
    _data = HomepageOperate.objects.filter(location__in=_locations,
                                           jump_type=_jum_type,
                                           jump=diary_id,
                                           is_online=True).order_by('-last_time').first()
    if _data:
        return {
            'business_type': _data.service_type,
            'ordering': _data.location
        }
    return None

@bind('api/diary/service_type_list')
def get_diary_service_types(diary_ids):
    _locations = [HOMEPAGE_OPERATE_LOCATION.ADV_DIARY_1,
                  HOMEPAGE_OPERATE_LOCATION.ADV_DIARY_2,
                  HOMEPAGE_OPERATE_LOCATION.ADV_DIARY_3,
                  HOMEPAGE_OPERATE_LOCATION.ADV_DIARY_4]
    _jum_type = HOT_SEARCH_JUMP_TYPE.DIARY[0]
    _data = HomepageOperate.objects.filter(location__in=_locations,
                                           jump_type=_jum_type,
                                           jump__in=diary_ids,
                                           is_online=True)
    _list_types = list()
    for _item in _data:
        _list_types.append({
            'diary_id': _item.jump,
            'business_type': _item.service_type,
            'ordering': _item.location
        })

    return _list_types


@bind('api/diary/extra_info')
def get_diary_extra_info(data):
    url = 'https://www.igengmei.com/expert/{}/'
    officer_url = 'https://www.igengmei.com/hospital/{}/'
    mUrl = 'https://m.igengmei.com/expert/{}/'
    officer_mUrl = 'https://m.igengmei.com/organization/{}/'
    user_mUrl = 'https://m.igengmei.com/user/{}/profile/'
    doctor_ids = []
    user_ids = []
    response, doctors_info, authors_info, areas_info = {}, {}, {}, {}
    for key, val in data.items():
        doctor_ids.append(val['doctor_id'])
        user_ids.append(val['author'])
    doctors = Doctor.objects.using("slave").filter(id__in=doctor_ids)
    for obj in doctors:
        doctor_item = {}
        area_item = {}
        if obj.doctor_type == DOCTOR_TYPE.OFFICER:
            doctor_item.update(name=obj.name, url=officer_url.format(obj.id), mUrl=officer_mUrl.format(obj.id))
        elif obj.doctor_type == DOCTOR_TYPE.DOCTOR:
            doctor_item.update(name=obj.name, url=url.format(obj.id),
                               mUrl=mUrl.format(obj.id))
        doctor_item['hospital'] = obj.hospital.name if obj.hospital else ''
        try:
            city = obj.hospital.city.name
            province = obj.hospital.city.province.name
            country = obj.hospital.city.province.country.name
            area_item.update(city=city, country=country, province=province)
        except:
            pass
        doctors_info[str(obj.id)] = doctor_item
        areas_info[str(obj.id)] = area_item
    authors = UserExtra.objects.using("slave").filter(user_id__in=user_ids)
    default_portrait = 'https://heras.igengmei.com/service_home/2020/03/17/a99b291047'
    for obj in authors:
        portrait = get_thumb_path(obj.portrait) if obj.portrait else default_portrait
        name = filter_user_nick_name(obj.user)
        authors_info[str(obj.user_id)] = {'id': obj.user_id, 'name': name if name else '佚名', 'image': portrait, 'mUrl': user_mUrl.format(obj.user_id)}
    for key, val in data.items():
        tags_info = {}
        tag_ids = val['tag_ids']
        print(tag_ids)
        tags = Tag.objects.using("slave").filter(id__in=tag_ids)
        if tags:
            #三级标签
            third_tag = tags.using("slave").filter(tag_type=TAG_TYPE.ITEM_WIKI).first()
            second_tag = tags.filter(tag_type=TAG_TYPE.BODY_PART_SUB_ITEM).first()
            first_tag = tags.filter(tag_type=TAG_TYPE.BODY_PART).first()
            if third_tag:
                second_tag = third_tag.online_parent_tags()[0] if third_tag.online_parent_tags() else ''
                first_tag = second_tag.online_parent_tags()[0] if second_tag and second_tag.online_parent_tags() else ''
                projectName = third_tag.name
            elif second_tag:
                first_tag = second_tag.online_parent_tags()[0] if second_tag.online_parent_tags() else ''
                projectName = second_tag.name
            elif first_tag:
                projectName = first_tag.name
            else:
                projectName = '其他'
            categoryFirstName = first_tag.name if first_tag else '其他'
            categorySecondName = second_tag.name if second_tag else ''
            categoryThirdName = third_tag.name if third_tag else ''
            tag_names = list(tags.values_list('name', flat=True))[:10]
            tags_info.update(projectName=projectName, categoryFirstName=categoryFirstName, categorySecondName=categorySecondName,
                             categoryThirdName=categoryThirdName, tag_names=tag_names)
        area_info = areas_info.get(val['doctor_id'], {})
        if not area_info and val.get('hospital_id'):
            hospital_obj = Hospital.objects.filter(id=val.get('hospital_id')).last()

            try:
                city = hospital_obj.city.name
                area_info.update(city=city)
                province = hospital_obj.city.province.name
                area_info.update(province=province)
                country = hospital_obj.city.province.country.name
                area_info.update(country=country)
            except:
                pass

        response[key] = {'doctor_info': doctors_info.get(val['doctor_id'], {}), 'area_info': area_info,
                         'tags_info': tags_info, "author_info": authors_info.get(str(val['author']), {})}
    return response