#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2019/6/4


from gm_dataquery.db import DB
from gm_types.error import ERROR
from rpc.tool.dict_mixin import to_dict
from rpc.exceptions import GaiaRPCFaultException
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from api.models.beauty_topic import MotherWord, MotherwordPhotoRelated, BeautyPhoto


class MotherWordDB(DataBuilder):

    def getval_related_stars(self, obj):
        beautyphoto_ids = MotherwordPhotoRelated.objects.filter(motherword_id=obj.id).values_list('beautyphoto_id')
        return list(BeautyPhoto.objects.filter(id__in=beautyphoto_ids).values_list('role_name'))


@DB
class MotherWordDQ(DataSQLQuery):
    model = MotherWord
    data_model = MotherWordDB

    def update(self, updates, **kwargs):
        is_online = updates.pop('is_online', True)
        if (not is_online) and (MotherwordPhotoRelated.objects.filter(motherword_id=kwargs['id']).exists()):
            raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message='请先处理该母词关联的美图', data=None)

        return super(MotherWordDQ.sqlquery, self).update(updates, **kwargs)


class BeautyPhotoDB(DataBuilder):
    def getval_mother_word(self, obj):
        the_first = obj.motherwords.first()
        return the_first.motherword_id if the_first else ''

    def getval_motherword_name(self, obj):
        the_first = obj.motherwords.first()
        return the_first.motherword.name if the_first else ''

@DB
class BeautyPhotoDQ(DataSQLQuery):
    model = BeautyPhoto
    data_model = BeautyPhotoDB

    def create(self, **kwargs):
        mother_word = kwargs.pop('mother_word')
        obj = self.model.objects.create(**kwargs)
        MotherwordPhotoRelated.objects.update_or_create(
            beautyphoto_id=obj.id,
            defaults={'motherword_id': mother_word}
        )
        return to_dict(obj)

    def update(self, updates, **kwargs):
        mother_word = updates.pop('mother_word', '')
        if mother_word:
            MotherwordPhotoRelated.objects.update_or_create(
                beautyphoto_id=kwargs['id'],
                defaults={'motherword_id': mother_word}
            )
        return super(BeautyPhotoDQ.sqlquery, self).update(updates, **kwargs)