# -*- coding: UTF-8 -*-
import datetime
from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_types.gaia import DOCTOR_SECKILL_APPLY_STATUS, SECKILL_TYPE
from api.models import Special, SpecialSeckillButton, DoctorSeckillApply, ServiceItem, SpecialRelatedTag, SpecialRule, \
    SpecialRelatedTagV3, SpecialNewTag
from hera.utils import get_tag_chain
from .talos.diary import Diary
from api.tool.datetime_tool import itv2time
from api.manager.service_info_manager import get_sku_id_to_sku_name_info

class SpecialDB(DataBuilder):

    def getval_campaign__name(self, obj):
        if getattr(obj, 'campaign', None):
            return obj.campaign.name
        return ''

    def getval_seckill_status(self, obj):
        now_t = datetime.datetime.now()
        if obj.is_online and (obj.start_time and now_t < obj.start_time):
            return u'上线中,即将开始'
        elif obj.is_online and (obj.start_time and obj.end_time and obj.start_time <= now_t <= obj.end_time):
            return u'上线中,正在秒杀'
        elif obj.is_online and (obj.end_time and now_t > obj.end_time):
            return u'上线中,已结束'
        else:
            return u'已下线'

    def getval_tags(self, obj):
        return [x.id for x in obj.tags.all()]

    def getval_groupbuy_type(self, obj):
        return obj.groupbuy.groupbuy_type

    def getval_active_type(self, obj):
        return obj.groupbuy.active_type

    def getval_countdown(self, obj):
        return itv2time(obj.groupbuy.countdown)

    def getval_suppor_copy(self, obj):
        return obj.end_time > datetime.datetime(2019, 9, 1, 0, 0, 0)


@DB
class SpecialDQ(DataSQLQuery):
        model = Special
        data_model = SpecialDB

        def filter_seckill_status(self, srch_key, srch_val, regex=False):
            now_t = datetime.datetime.now()
            q = None
            if srch_val == '1':
                q = Q(is_online=True) & Q(start_time__gt=now_t)
            elif srch_val == '2':
                q = Q(is_online=True) & Q(start_time__lte=now_t) & Q(end_time__gte=now_t)
            elif srch_val == '3':
                q = Q(is_online=False) | Q(end_time__lt=now_t)
            return q

        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_is_groupbuy(self, srch_key, srch_val, regex=False):
            return ~Q(groupbuy__isnull=bool(int(srch_val)))

        def filter_groupbuy_type(self, srch_key, srch_val, regex=False):
            return Q(groupbuy__groupbuy_type=srch_val)

        def filter_active_type(self, srch_key, srch_val, regex=False):
            return Q(groupbuy__active_type=srch_val)

        def update(self, updates, **kwargs):
            floor_id = updates.pop('floor_id', '')
            special_id = kwargs.get('id')
            if floor_id:
                ## 老标签存储
                new_tags = updates.get('tags', '')
                if new_tags !='':
                    old_tags = list(SpecialRelatedTag.objects.filter(
                        special_id=special_id, floor_id=floor_id
                    ).values_list('tag_id', flat=True))
                    SpecialRelatedTag.objects.filter(
                        tag_id__in=set(old_tags) - set(new_tags), special_id=special_id, floor_id=floor_id
                    ).delete()
                    SpecialRelatedTag.objects.bulk_create(
                        [
                            SpecialRelatedTag(special_id=special_id, tag_id=tag_id, floor_id=floor_id)
                            for tag_id in set(new_tags) - set(old_tags)
                        ]
                    )
                ## 新标签存储
                new_tags_v3 = updates.get('new_tags', '')
                if new_tags_v3 != '':
                    old_tags_v3 = list(SpecialRelatedTagV3.objects.filter(
                        special_id=special_id, floor_id=floor_id
                    ).values_list('tagv3_id', flat=True))
                    SpecialRelatedTagV3.objects.filter(
                        tagv3_id__in=set(old_tags_v3) - set(new_tags_v3), special_id=special_id, floor_id=floor_id
                    ).delete()
                    SpecialRelatedTagV3.objects.bulk_create(
                        [
                            SpecialRelatedTagV3(special_id=special_id, tagv3_id=tag_id, floor_id=floor_id)
                            for tag_id in set(new_tags_v3) - set(old_tags_v3)
                        ]
                    )
            else:
                ## 老标签
                new_tags = updates.get('tags', '')
                if new_tags != '':
                    old_tags = list(SpecialRule.objects.filter(special_id=special_id).values_list('tag_id', flat=True))
                    SpecialRule.objects.filter(tag_id__in=set(old_tags) - set(new_tags), special_id=special_id).delete()
                    for tag_id in set(new_tags) - set(old_tags):
                        SpecialRule.objects.update_or_create(
                            tag_id=tag_id,
                            special_id=special_id
                        )
                ## 新标签
                new_tags_v3 = updates.get('new_tags', '')
                if new_tags_v3 != '':
                    old_tags_v3 = list(SpecialNewTag.objects.filter(special_id=special_id).values_list('tagv3_id', flat=True))
                    SpecialNewTag.objects.filter(tagv3_id__in=set(old_tags_v3) - set(new_tags_v3), special_id=special_id).delete()
                    for tag_id in set(new_tags_v3) - set(old_tags_v3):
                        SpecialNewTag.objects.update_or_create(
                            tagv3_id=tag_id,
                            special_id=special_id
                        )


class SpecialSeckillButtonDB(DataBuilder):
    def getval_status(self, obj):
        q = Q(status=DOCTOR_SECKILL_APPLY_STATUS.DEFAULT) | Q(status=DOCTOR_SECKILL_APPLY_STATUS.RE_APPLY)
        has_not_pass = obj.doctorseckillapply_set.filter(q).exists()
        return u'未处理完成' if has_not_pass else u'处理完成'

    def getval_content(self, obj, need_escape=False):
        return obj.content or ''
@DB
class SpecialSeckillButtonDQ(DataSQLQuery):
    model = SpecialSeckillButton
    data_model = SpecialSeckillButtonDB

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

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

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

    def filter_end_sell_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):
        self.distinct = True
        q = Q(doctorseckillapply__status=DOCTOR_SECKILL_APPLY_STATUS.DEFAULT)
        q |= Q(doctorseckillapply__status=DOCTOR_SECKILL_APPLY_STATUS.RE_APPLY)
        if srch_val == '0':
            return q
        else:
            return ~q

    def create(self, **kwargs):
        if kwargs:
            tags = kwargs.pop('tags')
            new_tags = kwargs.pop('new_tags')
            cities = kwargs.pop('cities')
            doctors = kwargs.pop('doctors')
            button = SpecialSeckillButton.objects.create(**kwargs)
            button.tags = tags
            button.new_tags = new_tags
            button.cities = cities
            button.doctors = doctors
        return {'id':button.id}


class DoctorSeckillApplyDB(DataBuilder):
    def getval_service_item_name(self, obj):
        # item = ServiceItem.objects.get(id=obj.service_item_id)
        items_name = get_sku_id_to_sku_name_info([obj.service_item_id], False)[str(obj.service_item_id)].get('name', '')
        return items_name

    def getval_has_specials(self, obj):
        specialitems = obj.specialitem_set.all()
        special_list = []
        for specialitem in specialitems:
            special_date = u'{}:{}'.format(specialitem.special_id, specialitem.special.title)
            special_list.append(special_date)
        return ','.join(special_list)

    def getval_status_name(self, obj):
        return DOCTOR_SECKILL_APPLY_STATUS.getDesc(obj.status)

    def getval_service_item__gengmei_price(self, obj):
        price_info = obj.service_item.get_default_price_info()
        return price_info.get('gengmei_price', 0)

    def getval_has_prices(self, obj):
        week = datetime.datetime.now() - datetime.timedelta(days=7)
        week_applys = DoctorSeckillApply.objects.filter(service_item=obj.service_item, pass_time__gt=week,
                                                        status=DOCTOR_SECKILL_APPLY_STATUS.PASS).all()
        return [u'申请ID:{},活动价{}'.format(week_apply.id, week_apply.seckill_price) for week_apply in week_applys]

    def getval_group(self, obj):
        if obj.service_item.service.doctor.business_partener:
            group = ':'.join([x.title for x in obj.service_item.service.doctor.business_partener.belong_groups.all()])
        else:
            group = ''
        return group

    def getval_diary_count(self, obj):
        diary = Diary.objects.filter(topics__is_online=True, service_id=obj.service_item.service_id)
        return diary.count()

    def getval_tag_chains(self, obj):
        tag_chains = {}
        tag = obj.service_item.service.tags.filter(tag_type__in=['1', '2', '3']).first()
        try:
            if tag not in tag_chains:
                tag_chains[tag] = get_tag_chain(tag)
            first, second, third = tag_chains[tag]
        except:
            first = second = third = ''
        return {'first': first, 'second': second, 'third': third}

@DB
class DoctorSeckillApplyDQ(DataSQLQuery):
    model = DoctorSeckillApply
    data_model = DoctorSeckillApplyDB

    def filter_id(self, srch_key, srch_val, regex=False):
        if not isinstance(srch_val, list):
            srch_val = [srch_val]
        srch_val = [i for i in srch_val if i != '']
        return Q(id__in=srch_val)

    def filter_service_item_id(self, srch_key, srch_val, regex=False):
        if not isinstance(srch_val, list):
            srch_val = [srch_val]
        srch_val = [i for i in srch_val if i != '']
        return Q(service_item_id__in=srch_val)
