# -*- coding: UTF-8 -*-
import json
from gm_dataquery.dict_mixin import to_dict
from wiki.models.video import VideoLibrary, VideoRelationWord
from gm_dataquery.dataquery import DataSQLQuery, DataBuilder
from gm_dataquery.db import DB

from gm_types.wiki import NEW_WIKI_WORDREL_CATEGORY
from gm_types.gaia import VIDEO_LIBRARY_VIDEO_TYPE


from wiki.models.brand import Brand, BrandRelationKeyWords
from wiki.logices.common_query import (
    NewWikiRelationWords,
    wiki_data_create,
    wiki_data_update,
    wiki_video_update,
    wiki_video_create,
)


class BrandDB(DataBuilder, NewWikiRelationWords):

    def getval_video_data(self, obj):
        video_libs = VideoLibrary.objects.filter(source_id=obj.id, is_online=True, video_type=VIDEO_LIBRARY_VIDEO_TYPE.BRAND)
        index, result = 0, {}
        item_list = list(BrandRelationKeyWords.objects.filter(brand_id=obj.id, is_effect=True).values_list('wordrel_id', flat=True))
        for video_lib in video_libs:
            word_list = list(VideoRelationWord.objects.filter(video_id=video_lib.id).values_list('word_id', flat=True))
            word_list.extend(item_list)
            result[index] = {
                "img": video_lib.raw_image_url,
                "video": video_lib.raw_video_url,
                "tags": word_list,
                "order": video_lib.ordering,
                "key": video_lib.raw_video_url,
            }
            index += 1
        return result


@DB
class BrandDQ(DataSQLQuery):
    model = Brand
    data_model = BrandDB

    def create(self, **kwargs):
        video_data = kwargs.pop('video_data', None)
        brand_obj = wiki_data_create(self.model, BrandRelationKeyWords, "brand_id", **kwargs)

        # 处理视频
        if video_data:
            video_data = json.loads(str(video_data))
            wiki_video_create(wiki_id=brand_obj.id, video_data=video_data, video_type=VIDEO_LIBRARY_VIDEO_TYPE.BRAND)
            brand_obj.video_data = video_data
        return to_dict(brand_obj)

    def update(self, updates, **kwargs):
        _brand_id = kwargs.get("id", 0)
        updates = wiki_data_update(_brand_id, updates, BrandRelationKeyWords, "brand_id")
        if updates.get("video_data"):
            video_data = str(updates.get("video_data"))
            video_data = json.loads(video_data)
            wiki_video_update(video_data=video_data, wiki_id=int(kwargs.get('id')), video_type=VIDEO_LIBRARY_VIDEO_TYPE.BRAND)

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