# -*- coding: UTF-8 -*-
import datetime
import json
from django.db import transaction
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_types.push import HERA_TASK_TYPE
from gm_types.gaia import BENEFIT_TYPE, PUSHCOUPON_USER_TYPE
from api.models import PushTask, PushCoupon, PushCouponUser, PushtaskQAAlert
from api.models import User, ChannelGift, GiftToCoupon
from rpc.exceptions import GaiaRPCFaultException
from rpc.context import get_rpc_remote_invoker
from gm_types.error import ERROR


class PushTaskDB(DataBuilder):
    def getval_to_device(self, obj):
        text = u'无'
        if obj.to_android:
            text = u'Android'
        if obj.to_ios:
            text = u' IOS'
        if obj.to_android and obj.to_ios:
            text = u'Android IOS'
        return text

    def getval_creator_name(self, obj):
        if obj.creator:
            if obj.creator.last_name:
                return obj.creator.last_name
            else:
                return obj.creator.username
        else:
            return ''

    def getval_approver_name(self, obj):
        if obj.approver:
            if obj.approver.last_name:
                return obj.approver.last_name
            else:
                return obj.approver.username
        else:
            return ''

    

    def getval_jump_type(self, obj):
        text = u''
        if obj.topic_id:
            text += u'讨论帖'
        if obj.service:
            text += u'单一美购'
        if obj.special:
            text += u'美购专场'
        if obj.diary_id:
            text += u'日记本'
        if obj.tag:
            text += u'标签'
        if obj.url:
            text += u'网页'
        if obj.activity_id:
            text += u'免费活动'
        if obj.zhibo_user:
            text += u'直播'
        if obj.article_id:
            text += u'专栏详情'
        if obj.question_id:
            text += u'问题详情'
        if obj.answer_id:
            text += u'回答详情'
        return text

    def getval_approve_status(self, obj):
        return u'通过审核' if obj.approver else u'未审核'

    def batch_message_id(self, data, items):
        raw = get_rpc_remote_invoker()['push2/push/user/get_push_info'](
            hera_push_task_ids=[x.id for x in items],
            task_type=HERA_TASK_TYPE.MESSAGE
        ).unwrap()
        message_map = {x['hera_push_task_id']: x['msg_id'] for x in raw}
        # 过滤一些推送内容是空的问答
        asy_now = datetime.datetime.now()
        qa_id = [x['pk'] for x in data]
        no_alert_ids = PushtaskQAAlert.objects\
            .filter(pushtask_qa_id__in=qa_id, have_alert=False)\
            .values_list('pushtask_qa_id', flat=True)
        [x.update(alert="" if x['pk'] in no_alert_ids else x.get('alert')) for x in data]
        [x.update(message_id=message_map.get(x['pk'])) for x in data]
        for x in data:
            if x.get('message_id',None) is None and datetime.datetime.strptime(x.get('eta','1991-01-01 00:00:00') ,'%Y-%m-%d %H:%M:%S') <asy_now and x.get('approve_status', u'') ==  u'通过审核':
                x['operate']=True
            else:
                x['operate']=False
        # [x.update(operate=True if (x.get('message_id',None) and datetime.datetime.strptime(x.get('eta','1991-01-01 00:00:00') ,'%Y-%m-%d %H:%M:%S') <asy_now and x.get('approve_status', u'') ==  u'通过审核') else False) for x in data]
        return data


@DB
class PushTaskDQ(DataSQLQuery):
        model = PushTask
        data_model = PushTaskDB


class PushCouponDB(DataBuilder):
    def getval_user_list(self, obj):
        return '\r\n'.join(map(str, obj.user.filter(user_type=PUSHCOUPON_USER_TYPE.DEFAULT).values_list('user_id', flat=True)))

    def getval_market_id(self, obj):
        return [int(item) for item in eval(obj.market_id)]

    #todo
    def batch_message_id(self, data, items):
        raw = get_rpc_remote_invoker()['push2/push/user/get_push_info'](
            hera_push_task_ids=[x.id for x in items],
            task_type=HERA_TASK_TYPE.COUPON
        ).unwrap()
        message_map = {x['hera_push_task_id']: x['msg_id'] for x in raw}
        [x.update(message_id=message_map.get(x['pk'])) for x in data]
        return data


@DB
class PushCouponDQ(DataSQLQuery):
    model = PushCoupon
    data_model = PushCouponDB

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

    def create(self, **kwargs):
        user_list = kwargs.pop('user_list')
        market_ids = kwargs.get('market_id', None)
        if market_ids:
            from hera.views.market import gets_user_ids
            user_list = gets_user_ids(market_ids)
        users = User.objects.filter(id__in=user_list)
        # 判断礼包里面是否含有折扣券
        # gift_id = kwargs.get('gift_id', 0)
        # channelgift = ChannelGift.objects.filter(id=gift_id).first()
        # if channelgift and GiftToCoupon.objects.filter(
        #         coupon_gift_id=channelgift.gift_id, coupon__benefit_type=BENEFIT_TYPE.DISCOUNT
        # ).exists():
        #     raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'当前礼包含有折扣券类型美券，暂不可以保存', data=None)

        with transaction.atomic():
            obj = self.model.objects.create(**kwargs)
            if market_ids:
                PushCouponUser.objects.bulk_create(
                [PushCouponUser(push_coupon_id=obj.id, user=user, user_type=PUSHCOUPON_USER_TYPE.MARKET)
                 for user in users])
            else:
                PushCouponUser.objects.bulk_create(
                    [PushCouponUser(push_coupon_id=obj.id, user=user)
                    for user in users])
        return {'id': obj.id}

    def update(self, updates, **kwargs):
        user_list = updates.pop('user_list', None)
        market_ids = updates.get('market_id', [])
        if market_ids:
            from hera.views.market import gets_user_ids
            user_list = gets_user_ids(market_ids)
        # gift_id = updates.get('gift_id', 0)
        # channelgift = ChannelGift.objects.filter(id=gift_id).first()
        # if channelgift and GiftToCoupon.objects.filter(
        #         coupon_gift_id=channelgift.gift_id, coupon__benefit_type=BENEFIT_TYPE.DISCOUNT
        # ).exists():
        #     raise GaiaRPCFaultException(error=ERROR.UNIVERSAL, message=u'当前礼包含有折扣券类型美券，暂不可以保存', data=None)

        with transaction.atomic(self.model.objects.db):
            for obj in self.model.objects.select_for_update().filter(**kwargs):
                for k, v in updates.items():
                    setattr(obj, k, v)
                obj.save()
                if user_list:
                    obj.user.all().delete()
                    users = User.objects.filter(id__in=user_list)
                    if market_ids:
                        PushCouponUser.objects.bulk_create(
                            [PushCouponUser(push_coupon_id=obj.id, user=user, user_type=PUSHCOUPON_USER_TYPE.MARKET)
                            for user in users])
                    else:
                        PushCouponUser.objects.bulk_create(
                            [PushCouponUser(push_coupon_id=obj.id, user=user)
                            for user in users])
