from urllib.parse import urljoin

from django.conf import settings
from django.db.models import Q

from gm_types.mimas.qa import VIDEO_SOURCE_TYPE


def get_video_cover_url(source_id=None, source_type=None, video_urls=[]):
    """
    根据视频地址，处理出视频封面    http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=11604981
    :param video_url: 以列表形式传入视频地址，NTM4MTMwKzE0Nzk4OTY4NDA0ODk=.mp4 或者 http://video-static.igengmei.com/lk82Vwe46leuk-qhwTk7uXsp10tv
    :return: [{"video_url":video_url,"video_pic":video_pic}]
    """

    from talos.models.topic.video import VideoCover
    from qa.tasks.get_video_blurcover import get_video_blurcover
    if isinstance(video_urls, str):
        video_urls = [video_urls]

    urls = [video_url.replace(settings.VIDEO_HOST, '') for video_url in video_urls]
    video_cover_info = VideoCover.objects.filter(
        video_url__in=urls,
        source_type=source_type,
        source_id=source_id
    ).values("video_url", "video_pic", "webp_url", "width", "height")

    _need_filter_video_urls, video_cover_list = [], []
    for item in video_cover_info:
        webp_url = item.get("webp_url") or ""

        _video_url = urljoin(settings.VIDEO_HOST, item["video_url"])
        _data = {
            "video_url": _video_url,
            "video_pic": item["video_pic"],
            "short_video_url": webp_url,
            "width": item.get("width", 0),
            "height": item.get("height", 0),
        }
        video_cover_list.append(_data)
        _need_filter_video_urls.append(_video_url)

    _url_list = list(set(video_urls) - set(_need_filter_video_urls))
    if _url_list:
        for raw_video_url in _url_list:
            _data = {
                "video_url": raw_video_url,
                "video_pic": urljoin(raw_video_url, settings.VIDEO_PIC_URL),
                "short_video_url": "",
                "width": 0,
                "height": 0,
            }
            video_cover_list.append(_data)
        get_video_blurcover.delay(source_id=source_id, source_type=source_type, video_list=_url_list)

    video_cover_list = sorted(video_cover_list, key=lambda _item: video_urls.index(_item["video_url"]))
    return video_cover_list
