# -*- coding: UTF-8 -*-
import datetime

from django.db.models import Q, F
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from django.db import transaction
from gm_types.gaia import SEARCH_KEYWORDS_POSITION, SEARCH_KEYWORDS_TYPE, HOT_SEARCH_JUMP_TYPE, SERVICE_ORDER_TYPE
from gm_types.error import ERROR

from launch.models.screen_label import ShortcutScreenLabel
from rpc.tool.dict_mixin import to_dict
from api.models import SearchKeyword, User, SearchActivity, SearchKeywordOperationRecord
from rpc.exceptions import GaiaRPCFaultException


class ShortcutScreenLabelDB(DataBuilder):

    def getval_status(self, obj):
        now_datetime = datetime.datetime.now()
        if now_datetime < obj.start_time:
            status =  u'未开始'
        elif now_datetime > obj.end_time:
            status = u'已结束'
        else:
            status = u'进行中'
        return status

    def getval_operator_name(self, obj):
        return obj.operator.last_name or obj.operator.username

    def getval_rank(self, obj):
        now = datetime.datetime.now()
        if now < obj.start_time or now > obj.end_time:
            return ''
        query = Q(is_delete=False)
        query &= Q(start_time__lt=now)
        query &= Q(end_time__gt=now)
        shortcut_screen_label= ShortcutScreenLabel.objects.filter(query).order_by('position', '-create_time')
        for index, ssl in enumerate(shortcut_screen_label):
            if ssl.title == obj.title:

                return index+1


@DB
class ShortcutScreenLabelDQ(DataSQLQuery):
    model = ShortcutScreenLabel
    data_model = ShortcutScreenLabelDB

    def filter_title(self, srch_key, srch_val, regex=True):
        title = 99
        for enum, count in SERVICE_ORDER_TYPE.choices:
            if srch_val==count:
                title = enum
                break
        return Q(title=title)

    def filter_start_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_end_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_status(self, srch_key, srch_val, regex=False):
        now = datetime.datetime.now()
        srch_val = str(srch_val)
        if srch_val == '0':
            q = Q(start_time__gt=now)
        elif srch_val == '1':
            q = Q(start_time__lte=now) & Q(end_time__gte=now)
        elif srch_val == '2':
            q = Q(end_time__lt=now)
        else:
            q = Q()
        return q

    def create(self, **kwargs):
        start_time = kwargs.get('start_time', '')
        end_time = kwargs.get('end_time', '')
        now = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        if start_time < now or end_time < now:
            raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'开始时间, 结束时间不能小于当前编辑时间', data=None)
        if end_time <= start_time:
            raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'结束时间不能小于等于开始时间', data=None)
        q = Q(title=kwargs['title']) & Q(is_delete=False)
        q &= Q(start_time__lte=start_time, end_time__gte=start_time) | Q(start_time__lte=end_time, end_time__gte=end_time)
        if self.model.objects.filter(q).exists():
            raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'该标签已配置, 生效时间区间重合, 不能重复配置', data=None)
        obj = self.model.objects.create(**kwargs)
        return to_dict(obj)

    def update(self, updates, **kwargs):
        _pk = kwargs.get("id", 0)
        shortcut_screen_label = self.model.objects.get(pk=_pk)
        title = updates.get('title', '')
        start_time = updates.get('start_time', '')
        end_time = updates.get('end_time', '')

        now = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        if start_time:
            if start_time != str(shortcut_screen_label.start_time.strftime("%Y-%m-%d %H:%M:%S")) and start_time < now:
                raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'开始时间不能小于当前编辑时间', data=None)
        if end_time:
            if end_time != str(shortcut_screen_label.end_time.strftime("%Y-%m-%d %H:%M:%S")) and end_time < now:
                raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'结束时间不能小于当前编辑时间', data=None)
        if title:
            title = title
        else:
            title = shortcut_screen_label.title
        if start_time:
            success_time = start_time
        else:
            success_time = shortcut_screen_label.start_time
        if end_time:
            failure_time = end_time
        else:
            failure_time = shortcut_screen_label.end_time

        q = Q(title=title) & ~Q(id=_pk) & Q(is_delete=False)
        other_ssl = self.model.objects.filter(q)
        if other_ssl:
            for s in other_ssl:
                if success_time <= str(s.end_time.strftime("%Y-%m-%d %H:%M:%S")) and failure_time >= str(s.start_time.strftime("%Y-%m-%d %H:%M:%S")):
                    raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'该标签已配置, 生效时间区间重合, 不能重复配置', data=None)

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

