# -*- coding: utf-8 -*-
# @Time    : 2020/4/8 11:21 AM
# @Author  : hexy

from __future__ import unicode_literals, absolute_import, print_function

from django.conf import settings
from gm_types.gaia import HOSPITAL_TYPE,TAG_V3_TYPE
from django.db.models import Q, Count

from api.models import Region,Province, Doctor, Service, ServiceTag, TagRelation, ServiceComment
from api.models.service import ServiceItem
from hippo.models import Merchant
from talos.models.diary import Diary
from agile.models.tag import TagV3
from api.models.tag import Tag
from api.models.types import TAG_TYPE
from rpc.decorators import bind
from api.tool.image_utils import get_full_path
from api.manager.service_info_manager import get_sku_id_to_sku_name_info


@bind('api/region/all')
def region_all():
    objs = Region.objects.filter()
    return [{'id':obj.id,'name':obj.name,'english_name':obj.english_name} for obj in objs]


@bind('api/pc/all')
def region_all():
    objs = Province.objects.filter()
    return [obj.pc_data() for obj in objs]


@bind('api/tag/v3/all')
def tag_choices():

    # objs = TagV3.objects.using(settings.SLAVE_DB_NAME).filter(tag_type=TAG_V3_TYPE.FIRST_CLASSIFY)
    #
    # l = []
    # for obj in objs:
    #     x = {'id': obj.id, 'name': obj.name,'child':[]}
    #     for obj2 in obj.children_tags:
    #         x2 = {'id': obj2.child.id, 'name': obj2.child.name, 'child': []}
    #         for obj3 in obj2.child.children_tags:
    #             x3 = {'id': obj3.child.id, 'name': obj3.child.name}
    #             x2['child'].append(x3)
    #         x['child'].append(x2)
    #     l.append(x)
    # return l
    objs = Tag.objects.using(settings.SLAVE_DB_NAME).filter(tag_type=TAG_TYPE.BODY_PART,is_online=True)

    l = []
    for obj in objs:
        x = {'id': obj.id, 'name': obj.name,'child':[]}
        for obj2 in obj.online_child_tags():
            x2 = {'id': obj2.id, 'name': obj2.name, 'child': []}
            for obj3 in obj2.online_child_tags():
                x3 = {'id': obj3.id, 'name': obj3.name}
                x2['child'].append(x3)
            x['child'].append(x2)
        l.append(x)
    return l

@bind('api/merchant/choices')
def city_choices(q='', page=1, num=10):
    page = int(page)
    num = int(num)

    if len(str(q)) > 0:
        qry = Q(id__contains=q) | Q(name__contains=q)
        query = Merchant.objects.using(settings.SLAVE_DB_NAME).filter(qry)
    else:
        query = Merchant.objects.using(settings.SLAVE_DB_NAME).filter()
    total_count = query.count()
    start_pos = (page - 1) * num
    start_pos = start_pos if start_pos >= 0 else 0
    results = [
        {
            'id': str(obj.id),
            'name': obj.name,
            'is_online':obj.is_online,
            'doctor_id':obj.doctor_id
        } for obj in query[start_pos: start_pos + num]
        ]

    all_doctor_ids = [item['doctor_id'] for item in results]

    doctor_objs = Doctor.objects.filter(id__in=all_doctor_ids)

    for obj in doctor_objs:
        for item in results:
            if obj.id == item['doctor_id']:
                item['is_online'] = (item['is_online'] and obj.is_online)
                item['manage_type'] = HOSPITAL_TYPE.getDesc(obj.hospital.hospital_type)
                break

    for item in results:
        del item['doctor_id']

    return {'total_count': total_count, 'results': results, 'page': page, 'num': num}


@bind('api/promotion/merchant/info')
def merchant_info(merchant_ids):
    objs = Merchant.objects.using(settings.SLAVE_DB_NAME).filter(id__in=merchant_ids)


    results = [
        {
            'id': str(obj.id),
            'name': obj.name,
            'is_online':obj.is_online,
            'doctor_id':obj.doctor_id
        } for obj in objs
        ]

    all_doctor_ids = [item['doctor_id'] for item in results]

    doctor_objs = Doctor.objects.filter(id__in=all_doctor_ids)

    for obj in doctor_objs:
        for item in results:
            if obj.id == item['doctor_id']:
                item['is_online'] = (item['is_online'] and obj.is_online)
                item['manage_type'] = HOSPITAL_TYPE.getDesc(obj.hospital.hospital_type)
                break

    for item in results:
        del item['doctor_id']

    return results

@bind('api/sign/service/items')
def get_service(service_item_ids=[]):
    objs = ServiceItem.objects.filter(id__in=service_item_ids)
    l = []
    all_service_item_id = [item.id for item in objs]
    service_item_id_to_sku_name_info = get_sku_id_to_sku_name_info(all_service_item_id, False)
    for obj in objs:
        hospital_name = None
        try:
            hospital_name = obj.service.doctor.hospital.name
        except Exception as _:
            pass
        doctor_name = None
        try:
            doctor_name = obj.service.doctor.name
        except Exception as _:
            pass
        business_name = None
        try:
            doctor_name = obj.service.doctor.business_partener.username
        except Exception as _:
            pass
        daily_count = 0
        try:
            daily_count = Diary.objects.filter(topics__is_online=True, service_id=obj.service.id).count()
        except Exception as _:
            pass
        price_info = obj.get_default_price_info()
        if obj.service.upgrade:
            sku_name = service_item_id_to_sku_name_info.get(str(obj.id), {}).get('name', '')
        else:
            sku_name = obj.sku_name
        if not sku_name:
            sku_name = obj.service.name
        x = {
            "sku_name": sku_name,
            "sku_id": obj.id,
            "service_id": obj.service.id,
            "service_name": obj.service.name,
            "gengmei_price": price_info.get("gengmei_price", 0),
            "pre_payment_price": price_info.get("pre_payment_price", 0),
            "hospital_name": hospital_name,
            "doctor_name": doctor_name,
            "business_name": business_name,
            "daily_count": daily_count,
            "subscribe_count": obj.service.sell_amount_display,
            "service_image": get_full_path(obj.service.image_header),
            "sku_stock": obj.sku_stock,  # 库存数量
        }
        l.append(x)
    return l


@bind('api/sign/service/info')
def get_service_info(service_ids=[]):

    services = Service.objects.filter(id__in=service_ids)
    service_tags = ServiceTag.objects.filter(service_id__in=service_ids)
    comment_count = ServiceComment.objects.filter(is_online=True, service_id__in=service_ids).values(
        'service_id').annotate(Count('id'))
    comment_count_dict = {d['service_id']: d['id__count'] for d in comment_count}

    from collections import defaultdict

    #tag信息
    service_tags_dict = defaultdict(dict)
    for item in service_tags:
        try:#脏数据获取不到tag信息
            if item.tag.tag_type == TAG_TYPE.BODY_PART:
                service_tags_dict[item.service_id].setdefault(TAG_TYPE.BODY_PART, []).append(item.tag)
            elif item.tag.tag_type == TAG_TYPE.BODY_PART_SUB_ITEM:
                service_tags_dict[item.service_id].setdefault(TAG_TYPE.BODY_PART_SUB_ITEM, []).append(item.tag)
            elif item.tag.tag_type == TAG_TYPE.ITEM_WIKI:
                service_tags_dict[item.service_id].setdefault(TAG_TYPE.ITEM_WIKI, []).append(item.tag)
        except Exception as e:
            continue

    #获取父级标签
    for service_id in service_tags_dict.keys():
        tree_tags = service_tags_dict[service_id].get(TAG_TYPE.ITEM_WIKI, [])
        scend_tags = TagRelation.objects.filter(child__id__in=[item.id for item in tree_tags],
                                                is_deleted=False).select_related("parent")
        scend_tags = [item.parent for item in scend_tags if item.parent.tag_type == TAG_TYPE.BODY_PART_SUB_ITEM]
        service_tags_dict[service_id].setdefault(TAG_TYPE.BODY_PART_SUB_ITEM, []).extend(scend_tags)

        second_tags = service_tags_dict[service_id].get(TAG_TYPE.BODY_PART_SUB_ITEM, [])
        first_tags = TagRelation.objects.filter(child__id__in=[item.id for item in second_tags],
                                                is_deleted=False).select_related("parent")
        first_tags = [item.parent for item in first_tags if item.parent.tag_type == TAG_TYPE.BODY_PART]
        service_tags_dict[service_id].setdefault(TAG_TYPE.BODY_PART, []).extend(first_tags)

    res = {}
    for service in services:
        tag_info = service_tags_dict.get(service.id, {})

        res[str(service.id)] = {
            "first_tags": {item.id: item.name for item in tag_info.get(TAG_TYPE.BODY_PART, [])},
            "scend_tags": {item.id: item.name for item in tag_info.get(TAG_TYPE.BODY_PART_SUB_ITEM, [])},
            "tree_tags": {item.id: item.name for item in tag_info.get(TAG_TYPE.ITEM_WIKI, [])},
            "doctor": service.doctor.name,
            "hospital": service.doctor.hospital.name,
            "business_partener": service.doctor.business_partener.username,
            "city": service.doctor.hospital.city.name,
            "province": service.doctor.hospital.city.province.name,
            "region": service.doctor.hospital.city.province.region.name,
            "comment_count": comment_count_dict.get(service.id, 0)
        }

    return res
