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

from gm_types.error import ERROR
from gm_types.wiki import PRODUCT_TYPE
from gm_types.gaia import VIDEO_LIBRARY_VIDEO_TYPE

from rpc.exceptions import GaiaRPCFaultException

from wiki.models.item import Item, ItemAfterKnow, ItemRelationKeyWords, ItemTagV3
from wiki.models.video import VideoLibrary, VideoRelationWord
from wiki.logices.item import get_item_related_product_id_by_type
from wiki.logices.common_query import (
    NewWikiRelationWords,
    wiki_data_create,
    wiki_data_update,
    wiki_video_update,
    wiki_video_create,
)

VIDEOURL = 'http://video-static.igengmei.com/'


class ItemDB(DataBuilder, NewWikiRelationWords):
    def getval_related_drug(self, obj):
        return get_item_related_product_id_by_type(obj.id, PRODUCT_TYPE.DRUG)

    def getval_related_instrument(self, obj):
        return get_item_related_product_id_by_type(obj.id, PRODUCT_TYPE.INSTRUMENT)

    def getval_related_materials(self, obj):
        return get_item_related_product_id_by_type(obj.id, PRODUCT_TYPE.MATERIALS)

    def getval_tags(self, obj):
        return list(obj.tags.values_list('tag_id', flat=True))

    def getval_video_data(self, obj):
        video_libs = VideoLibrary.objects.filter(source_id=obj.id, is_online=True,
                                                 video_type=VIDEO_LIBRARY_VIDEO_TYPE.ITEM)
        index, result = 0, {}
        item_list = list(ItemRelationKeyWords.objects.filter(item_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

    def getval_tag_v3_ids(self, obj):
        return list(ItemTagV3.objects.filter(
            item_id=obj.id
        ).values_list("tag_v3_id", flat=True))


@DB
class ItemDQ(DataSQLQuery):
    model = Item
    data_model = ItemDB

    def update(self, updates, **kwargs):
        objs = self.model.objects.filter(**kwargs)

        #处理视频
        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.ITEM)

        for obj in objs:
            related_drug = updates.get('related_drug')
            related_instrument = updates.get('related_instrument')
            related_materials = updates.get('related_materials')

            if updates.get('similar_item') and str(obj.id) in updates.get('similar_item'):
                raise GaiaRPCFaultException(ERROR.UNIVERSAL, u'相似项目不能与自己关联', data=None)

            if related_drug or related_materials or related_instrument:
                related_drug = related_drug or get_item_related_product_id_by_type(obj.id, PRODUCT_TYPE.DRUG)
                related_instrument = related_instrument or get_item_related_product_id_by_type(obj.id, PRODUCT_TYPE.INSTRUMENT)
                related_materials = related_materials or get_item_related_product_id_by_type(obj.id, PRODUCT_TYPE.MATERIALS)
                obj.related_product = related_drug + related_instrument + related_materials

            wiki_data_update(
                _update_id=obj.id,
                updates=updates,
                relation_models={
                    "relwords": ItemRelationKeyWords,
                    "tag_v3": ItemTagV3,
                },
                model_param="item_id"
            )

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

    def create(self, **kwargs):
        kwargs.pop('after_know')
        similar_item = kwargs.pop('similar_item')
        related_drug = kwargs.pop('related_drug')
        related_instrument = kwargs.pop('related_instrument')
        related_materials = kwargs.pop('related_materials')
        video_data = kwargs.pop('video_data', None)

        obj = wiki_data_create(
            own_model=self.model,
            relation_models={
                "relwords": ItemRelationKeyWords,
                "tag_v3": ItemTagV3,
            },
            model_param="item_id",
            **kwargs
        )
        # obj = self.model.objects.create(**kwargs)

        # 处理视频
        if video_data:
            video_data = json.loads(str(video_data))
            wiki_video_create(wiki_id=obj.id, video_data=video_data, video_type=VIDEO_LIBRARY_VIDEO_TYPE.ITEM)

        obj.similar_item = similar_item
        obj.related_product = related_drug + related_instrument + related_materials
        obj.video_data = [] or video_data
        return to_dict(obj)

@DB
class ItemAfterKnowDQ(DataSQLQuery):
    model = ItemAfterKnow
