# coding=utf-8
from __future__ import absolute_import
import datetime
import hashlib
import requests
import json
from urlparse import urljoin

from gm_upload import set_video_watermark
from gm_upload.utils.qiniu_tool import QiniuTool
from django.db.models import Q
from django.conf import settings
from gm_types.gaia import VIDEO_CODE_STATUS
from api.models import Service, ServiceMonitor, ServiceRegisterVideo, ServiceVideo
from api.models import SKUPriceRule, ServiceItemPrice, ServiceItem
from api.models.types import REFUND_STATUS, ORDER_STATUS, SERVICE_MONITOR_STATUS, PAYMENT_TYPE
from celery import shared_task
from rpc.tool.log_tool import logging_exception

settled_status = [ORDER_STATUS.USED, ORDER_STATUS.SETTLED, ORDER_STATUS.AUDITING, ORDER_STATUS.SETTLING, ]


@shared_task
def judge_services():
    init_q = Q(payment_type__in=[PAYMENT_TYPE.FULL_PAYMENT, PAYMENT_TYPE.PREPAYMENT])
    for service in Service.objects.filter(init_q):
        try:
            service.monitor
        except ServiceMonitor.DoesNotExist:
            ServiceMonitor.objects.create(service=service)
        q = Q(last_modified__gt=service.monitor.handle_at)
        q &= Q(last_modified__gt=datetime.datetime.now() - datetime.timedelta(days=180))
        orders = service.order_set.filter(q)
        refund_num = orders.filter(refund__status=REFUND_STATUS.REFUNDED).count()
        settled_num = orders.filter(status__in=settled_status).count()
        service.monitor.refund_num = refund_num
        service.monitor.settled_num = settled_num
        service.monitor.save()
        if service.monitor.status == SERVICE_MONITOR_STATUS.BLACK:
            continue
        else:

            if refund_num < 4:
                continue
            if refund_num > settled_num:
                if refund_num > 2 * settled_num:
                    service.monitor.set_black()
                    continue
                service.monitor.set_alert()
                continue
            service.monitor.cancel_alert()
    return {
        'success': True,
    }


@shared_task
def set_water_mark_to_video_service(id):
    video = ServiceRegisterVideo.objects.get(id=id)
    video.persistent_status = VIDEO_CODE_STATUS.WAITING
    pid = set_video_watermark(
        video.video_url,
        hashlib.md5(video.video_url).hexdigest() + '.mp4',
        water_mark_url=settings.WATER_MARK_URL_FOR_VIDEO
    )
    video.persistentId = pid
    video.save(update_fields=['persistentId', 'persistent_status'])


@shared_task
def check_water_mark_video_is_finish_service():
    videos = ServiceRegisterVideo.objects.filter(~Q(persistent_status=VIDEO_CODE_STATUS.SUCCESS))
    for video in videos:
        try:
            if video.persistentId:
                result = json.loads(requests.get('http://api.qiniu.com/status/get/prefop?id=' +
                                                 video.persistentId).text)
                if result.get('code', 4) != 0:
                    continue

                if result['items'][0]['code'] == 0:
                    water_url = result['items'][0]['key']
                    # 刷新cdn缓存
                    QiniuTool.refresh_qiniu_resource_cache([urljoin(settings.VIDEO_HOST, water_url)])

                    video.water_url = water_url
                    video.persistent_status = VIDEO_CODE_STATUS.SUCCESS
                    video.save(update_fields=['persistent_status', 'water_url'])
                    if ServiceVideo.objects.filter(service_id=video.serviceregister.service_id).exists():
                        svideo = ServiceVideo.objects.get(service_id=video.serviceregister.service_id)
                        svideo.persistent_status = VIDEO_CODE_STATUS.SUCCESS
                        svideo.water_url = water_url
                        svideo.persistentId = video.persistentId
                        svideo.save(update_fields=['persistent_status', 'water_url', 'persistentId'])
                else:
                    video.persistent_status = result['items'][0]['code']
                    video.save(update_fields=['persistent_status'])
        except:
            logging_exception()
            continue

