# coding: utf-8

from __future__ import unicode_literals, absolute_import, print_function

from api.models.types import SERVICE_ADVERTISE_TYPE, DOCTOR_TYPE

from rpc.decorators import bind_context
from api.models import AdvertiseDoctor
from api.models import AdvertiseHospital
from api.models import AdvertiseService


@bind_context('api/advertise/doctors')
def get_advertise_doctors(ctx, count=12):
    doctors = AdvertiseDoctor.objects.all().order_by('rank')[:count]
    result = []
    for doctor in doctors:
        _doctor = doctor.doctor
        info = _doctor.data()
        service_tags = _doctor.service_tag()
        tags_name = [tag['name'] for tag in service_tags]
        info['good_at'] = ' '.join(tags_name)
        result.append(info)
    return result


@bind_context('api/advertise/hospitals')
def get_advertise_hospital(ctx, count=12):
    hospitals = AdvertiseHospital.objects.all().order_by('rank')[:count]
    result = []
    for hospital in hospitals:
        try:
            officers = hospital.hospital.doctor_hospital.filter(doctor_type=DOCTOR_TYPE.OFFICER)
            if not officers:
                continue
            result.append({
                'id': officers.first().id,
                'image': hospital.portrait,
                'title': hospital.hospital.name,
            })
        except:
            pass
    return result


def build_services(data):
    services = []

    for item in data:
        service_info = item.service.get_service_info()

        is_multiattribute = service_info['is_multiattribute']

        gengmei_price = service_info["gengmei_price"]
        gengmei_price_display = gengmei_price if not is_multiattribute else gengmei_price.split('-')[0] + u'起'
        original_price = service_info['original_price_display']
        original_price_display = original_price if not is_multiattribute else original_price.split('-')[0] + u'起'

        d = {
            'id': service_info['service_id'],
            'name': service_info["service_name"],
            'gengmei_price': gengmei_price_display,
            'original_price': original_price_display,
            'sell_amount': service_info['sell_amount'],
            'is_multiattribute': is_multiattribute,
            'image': service_info['service_image'],
        }
        services.append(d)

    return services


@bind_context('api/advertise/service/doctor_recommand')
def get_doctor_recommand(ctx, count=12):
    services = AdvertiseService.objects.filter(
        advertise_type=SERVICE_ADVERTISE_TYPE.DOCTORRECOMMEND
    ).prefetch_related('service').order_by('rank')[:count]
    return {'doctor_recommand': build_services(services)}


@bind_context('api/advertise/service/popular')
def get_popular_service(ctx, count=12):
    services = AdvertiseService.objects.filter(
        advertise_type=SERVICE_ADVERTISE_TYPE.POPULARSERVICE
    ).prefetch_related('service').order_by('rank')[:count]
    return {'popular_services': build_services(services)}

