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

import json
from django.db.models import Q

from gm_types.gaia import FACIAL_FEATUREA, SCAN_TYPE

from api.models.user_face_image import FaceOneImage, FaceOneImageV2
from api.models.face import Facial, FacialCombi, FacialFeatureFamily, SkinResult, ScanRecord


class FaceService(object):

    @classmethod
    def create_one_image(cls, face_id, user_id, face_url):
        if not user_id:
            return None

        if not face_id:
            return None

        if not face_url:
            return None

        obj = FaceOneImage(face_id=face_id, user_id=user_id, face_url=face_url)
        obj.save()

        return {'id': obj.id, 'face_id': obj.face_id}

    @classmethod
    def get_one_image(cls, user_id, face_id=None):
        if not user_id:
            return None

        if not face_id:
            obj = FaceOneImage.objects.filter(user_id=user_id).order_by('-id').first()
        else:
            obj_tmp = FaceOneImage.objects.filter(user_id=user_id, face_id=face_id).first()
            obj = obj_tmp if obj_tmp else FaceOneImage.objects.filter(user_id=user_id).order_by('-id').first()
        if not obj:
            return None

        return {
            'id': obj.id,
            'user_id': obj.user_id,
            'face_id': obj.face_id,
            'face_url': obj.face_url,
        }

    @classmethod
    def create_one_image_v2(cls, face_id, face_url, device_id="", user_id=0):
        """
        新的数据记录入口
        :param face_id:
        :param face_url:
        :param device_id:
        :param user_id:
        :return:
        """
        obj, status = FaceOneImageV2.objects.get_or_create(
            face_id=face_id,
            face_url=face_url,
            device_id=device_id,
            user_id=user_id
        )

        return {
            "id": obj.id,
        }

    @classmethod
    def get_one_image_v2(cls, face_id):
        """
        通过face_id 获取记录的图片
        :param face_id:
        :return:
        """

        default = {
            "face_id": face_id,
            "face_url": "",
        }
        _obj = FaceOneImageV2.objects.filter(face_id=face_id).first()
        if _obj:
            default.update({
                "face_url": _obj.face_url
            })
        return default

    @classmethod
    def had_test_record(cls, user_id=None, device_id=None):
        """用户是否参与测试"""

        if not (user_id or device_id):
            return {}

        from django.db.models import Q
        query = Q(device_id=device_id)

        if user_id:
            query = Q(user_id=user_id)

        return {
            "skin": SkinResult.objects.filter(query).exists(),
            "scan": ScanRecord.objects.filter(query, client_cache=True,
                                              scan_type__in=[SCAN_TYPE.SCAN_FACE, SCAN_TYPE.SCAN_FACE_OLD]).exists(),
        }


class FacialService(object):
    facial_combi_unmatched = {
        "1": {
            "face_name": "小众脸",
            # "desc": "宝藏男孩就是你！世界上只有3%的人和你相似，不一样的帅气只有你！",
            "celebrity": '',
        },
        "2": {
            "face_name": "小众脸",
            # "desc": "宝藏少女就是你！世界上只有3%的人和你相似，不一样的美只有你！",
            "celebrity": '',
        }
    }

    @classmethod
    def get_desc_by_classification(cls, contour, chin, eyebrow, eye, nose, lip):
        """
        获取部位描述
        :param contour: 脸型
        :param chin: 下巴
        :param eyebrow: 眉毛
        :param eye: 眼睛
        :param nose: 鼻
        :param lip: 唇
        :return:
        """
        _filter_q = Q()
        if contour:
            _filter_q |= Q(facial_type=FACIAL_FEATUREA.CONTOUR, classification=contour)

        if chin:
            _filter_q |= Q(facial_type=FACIAL_FEATUREA.CHIN, classification=chin)

        if eyebrow:
            _filter_q |= Q(facial_type=FACIAL_FEATUREA.EYEBROW, classification=eyebrow)

        if eye:
            _filter_q |= Q(facial_type=FACIAL_FEATUREA.EYE, classification=eye)

        if nose:
            _filter_q |= Q(facial_type=FACIAL_FEATUREA.NOSE, classification=nose)

        if lip:
            _filter_q |= Q(facial_type=FACIAL_FEATUREA.LIP, classification=lip)

        _filter_q &= Q(is_online=True)

        # 展示控制的部位
        display_facial_type_set = {
            FACIAL_FEATUREA.CONTOUR,
            FACIAL_FEATUREA.CHIN,
            FACIAL_FEATUREA.EYEBROW,
            FACIAL_FEATUREA.EYE,
            FACIAL_FEATUREA.NOSE,
            FACIAL_FEATUREA.LIP
        }

        _facial_list = Facial.objects.filter(_filter_q).values("classification", "desc", "facial_type")
        _control_display_facial_set = set()  # 用于去重
        _facial_display_dic = dict()
        for item in _facial_list:
            facial_type = item.get("facial_type", 0)
            classification = item.get("classification", "unknown")

            if facial_type in display_facial_type_set and facial_type not in _control_display_facial_set:
                _facial_display_dic[json.dumps((facial_type, classification))] = item.get("desc", "")
                _control_display_facial_set.add(facial_type)

            if not (display_facial_type_set - _control_display_facial_set):
                break

        return _facial_display_dic

    @classmethod
    def get_face_name_and_desc(cls, filters):
        """
        通过不同部位类型组合，获取
        :param filters: {"contour":"yuanlian", "chin":"jianxiaba"}  筛选条件
        :return:
        """

        result = {
            "face_name": "",
            "desc": "",
            "celebrity": "",
        }

        filters.update({
            "is_online": True,
        })

        facial_combi_obj = FacialCombi.objects.filter(**filters).only("title", "desc", "celebrity", "image_url").first()
        if facial_combi_obj:
            result.update({
                "face_name": facial_combi_obj.title,
                "desc": facial_combi_obj.desc,
                "celebrity": facial_combi_obj.celebrity,
                "image_url": facial_combi_obj.image_url,
            })
        else:
            result.update(cls.facial_combi_unmatched.get(str(filters.get("gender", 1))))

        return result


class FacialFeatureService(object):
    @classmethod
    def get_online_info(cls, feature=None):

        if not feature:
            obj_list = list(FacialFeatureFamily.objects.filter(is_online=True).values(
                "id",
                "classification",
                "facial_type",
                "desc1",
                "desc2",
                "img_url",
                "polymer_id",
                "choice_button_words",
                "service_button_words",
                "topic_id"
            ))
        else:
            obj_list = list(FacialFeatureFamily.objects.filter(classification=feature, is_online=True).values(
                "id",
                "classification",
                "facial_type",
                "desc1",
                "desc2",
                "img_url",
                "polymer_id",
                "choice_button_words",
                "service_button_words",
                "topic_id"
            ))

        return obj_list

