# coding: utf-8
import json
import datetime
from rpc.cache import push_cache
from api.models import Special, Person
from sms.utils.smsfactory import send_sms
from api.tool.log_tool import logging_exception


class GroupbuyMsgList(object):
    
    def __init__(self, activity_id, end_time=0):
        self.activity_id = activity_id
        self.end_time = end_time
        self.groupbuy_msg_key = "groupbuy_msg_list_activity:{}".format(activity_id)

    def msg_list(self, offset=0, count=100):
        return push_cache.lrange(self.groupbuy_msg_key, offset, count)
    
    def gets_user_id_from_msg(self, msg, is_puppet=False, only_puppet=False):
        msg = msg.replace("'", '"')
        msg = json.loads(msg)
        has_robot = msg.get('has_robot')
        if not is_puppet:
            return [msg.get('creator_user_id')]
        if only_puppet:
            if has_robot:
                return [msg.get('user_id')]
            else:
                return []
        return [msg.get('creator_user_id'), msg.get('user_id')]

    def _gets_user_ids_by_msg_list(self, msg_list, is_puppet=False, only_puppet=False):
        user_ids = []
        [user_ids.extend(self.gets_user_id_from_msg(item, is_puppet, only_puppet)) for item in msg_list]
        return user_ids

    def gets_user_ids(self, is_puppet=False, only_puppet=False):
        """ 
            only_puppet 是否只返回马甲
            is_puppet 是否包含马甲
        """
        start, per = 0, 100
        user_ids = []
        msg_list = self.msg_list(start, per)
        user_ids.extend(self._gets_user_ids_by_msg_list(msg_list, is_puppet, only_puppet))
        while msg_list:
            start = per
            per += 100
            msg_list = self.msg_list(start, per)
            user_ids.extend(self._gets_user_ids_by_msg_list(msg_list, is_puppet, only_puppet))
        return user_ids

    def push_msg(self, msg):
        msg = json.dumps(msg, encoding='UTF-8')
        msgs = self.msg_list(0, 1)
        if msgs:
            push_cache.lpush(self.groupbuy_msg_key, msg)
        else:
            special = Special.objects.filter(id=self.activity_id).first()
            if special:
                activity_period_time = int((self.end_time - datetime.datetime.now()).total_seconds())
                if activity_period_time < 0:
                    return
                push_cache.lpush(self.groupbuy_msg_key, msg)
                push_cache.expire(self.groupbuy_msg_key, activity_period_time)


def groupbuy_push_message(user_id, template_id):
    """ 拼团成功短信推送 """
    try:
        obj = Person.objects.get(user_id=user_id)
        send_sms(obj.phone, template_id, [])
    except:
        logging_exception()


def push_msg_groupbuy_msg(activity_id, creator_user_id, user_id, message, has_robot=True, end_time=0):
    """ 拼团轮播消息添加 """
    msg = construct_groupbuy_msg(creator_user_id=creator_user_id, user_id=user_id, message=message, activity_id=activity_id, has_robot=has_robot)
    obj = GroupbuyMsgList(activity_id, end_time)
    obj.push_msg(msg)


def groupbuy_msg_list(activity_id, offset=0, count=100):
    """ 拼团成功 奖品领取等消息列表 """
    obj = GroupbuyMsgList(activity_id)
    msg_list = obj.msg_list(offset, count)
    all_user_ids = obj.gets_user_ids(is_puppet=True)
    return [json.loads(item) for item in msg_list], all_user_ids


def construct_groupbuy_msg(creator_user_id, user_id, message, activity_id, has_robot=True):
    return {
        "creator_user_id": creator_user_id,
        "user_id": user_id,
        "message": message,
        "has_robot": has_robot,
        "activity_id": activity_id,
    }
