# -*- coding: utf-8 -*-

from django.db.models import Q

from rpc.decorators import bind, cache_page
from api.models.face.heidong_scan import HeiDongDimensionImage, HeiDongDimensionDetail, HeiDongDimension
from api.services.tag_service import list_tags_by_polymer_ids


@bind('api/heidong_scan/result')
@cache_page(60 * 10)
def nanshen_activite_get_question(filters):
    query = Q()
    for k, v in filters.items():
        query |= Q(facial_type=k) & Q(classification=v) & Q(is_online=True) & Q(client=True)

    dimensiondetails = HeiDongDimensionDetail.objects.filter(query)
    dimensions = HeiDongDimension.objects.filter(is_online=True)
    dimensions_image = HeiDongDimensionImage.objects.filter(is_online=True)

    polymer_ids = list(set([int(i.polymer_id) for i in dimensiondetails]))
    tags_info = list_tags_by_polymer_ids(polymer_ids)

    dimensions_image_dict = {}
    for item in dimensions_image:
        dimensions_image_dict.update({item.dimension: item.img_url})

    dimensions_dict = {}
    for item in dimensions:
        dimensions_dict[(item.dimension, item.facial_type)] = item

    dimensions_detail_dict = {}

    for item in dimensiondetails:
        if item.dimension not in dimensions_detail_dict:
            dimensions_detail_dict[item.dimension] = []

        dimensions_detail_dict[item.dimension].append({
            "img_url": dimensions_dict.get((item.dimension, item.facial_type)).img_url if dimensions_dict.get(
                (item.dimension, item.facial_type)) else '',
            "out_content": dimensions_dict.get((item.dimension, item.facial_type)).out_content if dimensions_dict.get(
                (item.dimension, item.facial_type)) else '',
            "rank": dimensions_dict.get((item.dimension, item.facial_type)).score if dimensions_dict.get(
                (item.dimension, item.facial_type)) else 0,
            "score": item.score,
            "polymer_id": item.polymer_id,
            "analysis": item.analysis,
            "service_button_words": item.service_button_words,
            "tags_info": tags_info.get(int(item.polymer_id), [])
        })

    # 排序， 分数小的在前
    for _, item in dimensions_detail_dict.items():
        item.sort(key=lambda x: x["score"])

    return {"dimensions": dimensions_detail_dict, "dimensions_image": dimensions_image_dict}


@bind('api/heidong_scan/polymer/tags')
def get_polymer_tags(polymer_ids):
    """
        通过聚合id获取标签
    """
    if not polymer_ids:
        return {}
    return list_tags_by_polymer_ids(polymer_ids)
