# coding: utf-8
import datetime
import itertools
import operator
import time
import json
import random
from django.db import transaction, IntegrityError
from django.db.models import F
from gm_types.gaia import GROUPBUY_STATUS, GROUPBUY_TYPE, ORDER_STATUS,SETTLEMENT_STATUS,LOGIN_AUTH_TYPE
from gm_types.pay import CHANNEL
from api.models import (
    GroupBuyTeamOrder,
    User,
    UserExtra,
    GroupBuyTeam,
    Order,
    Service,
    ServiceItem,
    Person,
    PlatformUser,
    UserExtraWechatInfo
)
from gaia import settings
from api.tool.user_tool import filter_user_nick_name, get_user_by_id
from rpc.tool.error_code import CODES
from rpc.tool.log_tool import logging_exception,info_logger
from rpc.cache import groupbuy_cache
from utils.wechat_applet_tools import applet_template_push
from django.conf import settings
from api.util.wechat_util import get_wechat_access_token
from api.models.settlement import Settlement, SettlementItem
from celery import shared_task
from api.tool.log_tool import order_logger


def try_get_groupbuy_info_by_groupbuy_id(id, lock=False):
    pass


def try_get_groupbuy_info_by_order_id(order_id, lock=False):
    pass


def get_groupbuy_id_by_hash_id(hash_id):
    '''
        通过hash的id来获取团购的id
    '''
    gbt = GroupBuyTeam.objects.only('id').filter(hash_id=hash_id).first()
    if gbt:
        return gbt.id
    return None


def generate_groupbuy_team_hash_id():
    return int(time.time() * 1000000)


def get_groupbuy_team_info_by_hash_ids(hash_ids, need_user_info=False):
    '''
        通过hash的ids来获取groupbuy的team信息
    '''
    groupbuy_team_id_to_all_user_info = {}
    result = {}
    gbts = GroupBuyTeam.objects.filter(hash_id__in=hash_ids)

    if need_user_info:
        gbtids = [gbt.id for gbt in gbts]
        groupbuy_team_id_to_all_user_info = _get_groupbuy_team_user_info_by_groupbuy_team_ids(gbtids)

    for gbt in gbts:

        result[gbt.hash_id] = gbt.to_display_dict()

        if not need_user_info:
            continue

        members = []
        if gbt.id not in groupbuy_team_id_to_all_user_info:
            continue
        all_user_info = groupbuy_team_id_to_all_user_info[gbt.id]
        for user_id, user_info in all_user_info.items():
            if user_id == gbt.creator_user_id:
                members.insert(0, user_info)
            else:
                members.append(user_info)

        # add plus img when group buying is starting
        if gbt.status == GROUPBUY_STATUS.GROUPBUY_STARTED:
            members.append({"portrait": settings.GROUPBUY_PLUS_IMG_URL})
        result[gbt.hash_id]['members'] = members

    for hash_id in hash_ids:
        if hash_id in result:
            continue
        result[hash_id] = {}

    return result


def _get_groupbuy_team_user_info_by_groupbuy_team_ids(groupbuy_team_ids):
    '''
        通过groupbuy team ids来获取团购信息
    '''
    gti_to_userid_list = GroupBuyTeamOrder.objects.filter(
        groupbuy_team_id__in=groupbuy_team_ids, paid=True
    ).values_list('groupbuy_team_id', 'user_id').order_by('id')

    grouped = itertools.groupby(
        gti_to_userid_list,
        operator.itemgetter(0),
    )
    groupbuy_team_to_user_ids = {
        k: [e[1] for e in v]
        for k, v in grouped
    }

    user_ids = []
    for _, _user_ids in groupbuy_team_to_user_ids.items():
        # 默认最多取10个人的信息
        user_ids.extend(_user_ids[:10])
    user_ids = set(user_ids)
    user_extras = UserExtra.objects.filter(user_id__in=user_ids).only('user_id', 'portrait')
    user_id_to_user_info = {}
    for user_extra in user_extras:
        user_id_to_user_info[user_extra.user_id] = {"portrait": user_extra.get_portrait()}

    groupbuy_team_id_to_all_user_info = {}
    for groupbuy_team_id, user_ids in groupbuy_team_to_user_ids.items():
        data = {}
        for user_id in user_ids:
            if user_id not in user_id_to_user_info:
                continue
            data[user_id] = user_id_to_user_info[user_id]
        groupbuy_team_id_to_all_user_info[groupbuy_team_id] = data

    return groupbuy_team_id_to_all_user_info


def get_groupbuy_team_info_by_order_ids(order_ids, need_user_info=False):
    '''
        通过订单id来获取团购信息
    '''
    result = {}
    groupbuy_team_id_to_all_user_info = {}
    #参团用户组
    gbtos = GroupBuyTeamOrder.objects.filter(order_id__in=order_ids).prefetch_related('groupbuy_team')

    #是否需要用户信息
    if need_user_info:
        groupbuy_team_ids = [gbto.groupbuy_team_id for gbto in gbtos]
        groupbuy_team_id_to_all_user_info = _get_groupbuy_team_user_info_by_groupbuy_team_ids(groupbuy_team_ids)

    for gbto in gbtos:
        result[gbto.order_id] = gbto.groupbuy_team.to_display_dict()

        if not need_user_info:
            continue
        #获取参团用户信息
        members = []
        if gbto.groupbuy_team_id not in groupbuy_team_id_to_all_user_info:
            continue

        all_user_info = groupbuy_team_id_to_all_user_info[gbto.groupbuy_team_id]
        for user_id, user_info in all_user_info.items():
            if user_id == gbto.groupbuy_team.creator_user_id:
                members.insert(0, user_info)
            else:
                members.append(user_info)

        # add plus img when group buying is starting
        if gbto.groupbuy_team.status == GROUPBUY_STATUS.GROUPBUY_STARTED:
            members.append({"portrait": settings.GROUPBUY_PLUS_IMG_URL})
        result[gbto.order_id]['members'] = members

        #视角
        result[gbto.order_id]["view_angle"]="guest"

    for order_id in order_ids:
        if order_id in result:
            continue
        result[order_id] = {}

    return result


def get_groupbuy_info_by_groupbuy_ids(groupbuy_ids):
    pass


def try_join_groupbuy_team(user_id, groupbuy_code, lock_groupbuy_team=False, now=None):
    """
    试着加入团购
    :param groupbuy_code:
    :return: None or GroupBuyTeam, ERROR_CODES or None
    """
    if now is None:
        now = datetime.datetime.now()

    groupbuy_team_id = get_groupbuy_id_by_hash_id(groupbuy_code)

    if groupbuy_team_id:
        q = GroupBuyTeam.objects.select_for_update() if lock_groupbuy_team else GroupBuyTeam.objects
        groupbuy_team = q.get(id=groupbuy_team_id)

        time_valid = groupbuy_team.start_time <= now <= groupbuy_team.end_time

        if not time_valid:
            return None, CODES.GROUPBUY_IS_FINISHED

        status_valid = groupbuy_team.status == GROUPBUY_STATUS.GROUPBUY_STARTED
        team_has_left = groupbuy_team.left_user_number > 0

        if not status_valid or not team_has_left:
            return None, CODES.GROUPBUY_IS_FINISHED

        must_new_groupbuy_user = groupbuy_team.gb_type == GROUPBUY_TYPE.OLD_TO_NEW

        if must_new_groupbuy_user:
            # 检查是否 拼团新用户
            groupbuy_new_user_order_status = (
                ORDER_STATUS.NOT_PAID, ORDER_STATUS.PAYING, ORDER_STATUS.CANCEL,
                ORDER_STATUS.REFUNDED  # 拼团要求加入的额外状态判断
            )

            user_has_order = Order.objects.filter(
                user_id=user_id).exclude(
                status__in=groupbuy_new_user_order_status
            ).exists()

            if user_has_order:
                return None, CODES.GROUPBUY_ONLY_NEW_USER_CAN_JOIN  # 拼团只限新用户参加

        user_has_join = GroupBuyTeamOrder.objects.filter(
            groupbuy_team_id=groupbuy_team.id, user_id=user_id, paid=True
        ).exists()

        if user_has_join:
            return None, CODES.GROUPBUY_USER_ALREADY_JOINED

        return groupbuy_team, None
    else:
        # 要参加的团肯定不存在
        return None, CODES.GROUPBUY_NOT_EXISTS


def join_groupbuy(user_id, groupbuy_team, order_id):
    """
        用户通过下单加入拼团的处理，注意用户此时没有支付并且不一定会支付

    :param user_id:
    :param groupbuy_team:
    :param order_ids:
    :return:
    """
    to_insert_groupbuy_team_order = [
        GroupBuyTeamOrder(
            user_id=user_id,
            groupbuy_team=groupbuy_team,
            order_id=order_id,
            paid=False,
        )
    ]

    with transaction.atomic():
        GroupBuyTeamOrder.objects.bulk_create(to_insert_groupbuy_team_order)

        row_count = GroupBuyTeam.objects \
            .filter(id=groupbuy_team.id) \
            .update(current_user_number=F('current_user_number') + 1)


def create_groupbuy(
        user_id, order_id,
        groupbuy_type, groupbuy_nums,
        service_item_id, price_id,
        groupbuy_start_time, groupbuy_end_time,
):
    """
        开团用户在支付时候的处理，此时才真正的创建一个新的拼团

    :param user_id:
    :param service_item_id:
    :return: GroupBuyTeam
    """
    left_user_number = groupbuy_nums - 1
    gbt = GroupBuyTeam(
        min_user_number=groupbuy_nums,
        left_user_number=left_user_number,
        current_user_number=1,
        gb_type=groupbuy_type,
        status=GROUPBUY_STATUS.GROUPBUY_STARTED,
        service_item_id=service_item_id,
        price_id=price_id,
        creator_user_id=user_id,
        start_time=groupbuy_start_time,
        end_time=groupbuy_end_time,
        success_time=None,
    )
    groupbuy_team = _create_groupbuy_team(gbt)

    GroupBuyTeamOrder.objects.create(
        user_id=user_id,
        groupbuy_team=groupbuy_team,
        order_id=order_id,
        paid=True,
    )
    return groupbuy_team


def _create_groupbuy_team(groupbuy_team):
    while True:
        hid = str(generate_groupbuy_team_hash_id())
        groupbuy_team.hash_id = hid
        try:
            with transaction.atomic():
                groupbuy_team.save()
                return groupbuy_team
        except IntegrityError:
            logging_exception()


def try_lock_groupbuy_team(groupbuy_team_id):
    '''
        锁定拼团
    '''
    gbt = None
    groupbuy_exist = GroupBuyTeam.objects.filter(id=groupbuy_team_id)
    if groupbuy_exist:
        gbt = GroupBuyTeam.objects.select_for_update().get(id=groupbuy_team_id)
    return gbt


def groupbuy_user_paid(groupbuy_team, order_id):
    from api.tasks.push_task import push_groupbuy_success_message

    if groupbuy_team.status == GROUPBUY_STATUS.GROUPBUY_STARTED and groupbuy_team.left_user_number > 0:
        # left_user_number--
        groupbuy_team.left_user_number -= 1

        groupbuy_success = False
        if groupbuy_team.left_user_number == 0:
            groupbuy_success = True

        if groupbuy_success:
            groupbuy_team.status = GROUPBUY_STATUS.GROUPBUY_SUCCESSED
            groupbuy_team.success_time = datetime.datetime.now()

            all_order_ids = set(GroupBuyTeamOrder.objects.filter(
                groupbuy_team=groupbuy_team
            ).values_list('order_id', flat=True))
            Order.objects.filter(id__in=all_order_ids).update(groupbuy_status=GROUPBUY_STATUS.GROUPBUY_SUCCESSED)

            # 增加push消息。 到时候会将整个消息通知移动到事务commit 之后, 延时调用， 避免事务未提交获取到旧的 拼团状态
            push_groupbuy_success_message.apply_async((groupbuy_team.id,), countdown=60)

        # 千万记得update
        groupbuy_team.save(update_fields=["left_user_number", "status", "success_time"])

    elif groupbuy_team.status == GROUPBUY_STATUS.GROUPBUY_SUCCESSED:
        Order.objects.filter(id=order_id).update(groupbuy_status=GROUPBUY_STATUS.GROUPBUY_SUCCESSED)

    elif groupbuy_team.status == GROUPBUY_STATUS.GROUPBUY_FAIL:
        Order.objects.filter(id=order_id).update(groupbuy_status=GROUPBUY_STATUS.GROUPBUY_FAIL)

    GroupBuyTeamOrder.objects.filter(
        groupbuy_team=groupbuy_team,
        order_id=order_id
    ).update(paid=True)


def do_groupbuy_fail_actions(groupbuy_id):
    pass


def check_groupby_is_success(groupbuy_id):
    pass


def get_groupbuy_unfinished(service_item_ids, service_id=None, limit=10):
    '''
    根据指定的service_id或service_item_ids获取对应sku待完成的拼团
    注：
        1.先检验service_item_id, 是否有库存, 是否有效
        2. 检查价格是否有效及价格规则是否有效
    '''
    from django.db import connection
    if not service_item_ids:
        if service_id:
            service_item_ids = Service.get_groupbuy_item_ids_by_service_id(service_id)
    else:
        service_item_ids = ServiceItem.filter_valid_item_ids(service_item_ids)

    result = {}
    if not service_item_ids:
        return result

    now = datetime.datetime.now()
    cursor = connection.cursor()
    query_sql = '''
        select t.hash_id, t.service_item_id, t.end_time, t.left_user_number, creator_user_id
        from api_groupbuy_team t, api_serviceitemprice p, api_skupricerule pr where
            t.price_id = p.id and p.selling_rule_id = pr.id
            and p.is_enable is true and pr.is_enable is true and p.sale_limit > 0
            and t.service_item_id in ({ids_str}) and t.status = {status} and t.end_time >= '{now}'
            order by t.service_item_id, t.left_user_number, t.end_time
    '''
    params = {}
    params['ids_str'] = ','.join([str(x) for x in service_item_ids])
    params['status'] = GROUPBUY_STATUS.GROUPBUY_STARTED
    params['now'] = str(now)
    query_sql = query_sql.format(**params)
    cursor.execute(query_sql)
    result_tuple = cursor.fetchall()
    col_names = [des[0] for des in cursor.description]
    query_result = []
    for res in result_tuple:
        query_result.append(dict(zip(col_names, res)))
    item_id_groups = itertools.groupby(query_result, operator.itemgetter('service_item_id'))
    for siid, group in item_id_groups:
        result[siid] = list(group)[:limit]
    for siid, gbts in result.items():
        for gbt in gbts:
            end_time = gbt.pop('end_time')
            user_id = gbt.pop('creator_user_id')
            team_id = gbt.pop('hash_id')
            countdown = (end_time - now).total_seconds()
            user_obj = get_user_by_id(user_id)
            user_info = {
                'leader_name': filter_user_nick_name(user_obj),
                'leader_portrait': user_obj.userextra.get_portrait()
            }
            gbt.update(user_info)
            gbt['team_id'] = team_id
            gbt['countdown'] = countdown
    return result

def get_groupbuy_success_show_info(limit=10):
    '''
    获取全场范围内的拼团成功提示
    '''
    cache_key = 'global_suc_info'
    cache_result = groupbuy_cache.get(cache_key)
    if cache_result:
        return json.loads(cache_result)
    now = datetime.datetime.now()
    one_day_before = now + datetime.timedelta(days=-1)
    top_groupbuy_list = GroupBuyTeam.objects.filter(
        status=GROUPBUY_STATUS.GROUPBUY_SUCCESSED
    ).filter(success_time__gte=one_day_before).values('creator_user_id').distinct().order_by('-success_time')[:limit]
    result_list = []
    for tgb in top_groupbuy_list:
        user_id = tgb.get('creator_user_id')
        user_obj = get_user_by_id(user_id)
        user_info = {
            'leader_name': filter_user_nick_name(user_obj),
            'leader_portrait': user_obj.userextra.get_portrait()
        }
        result_list.append(user_info)
    groupbuy_cache.setex(cache_key, 5 * 60, json.dumps(result_list))
    return result_list

@shared_task
def test_celery_beat():
    info_logger.info("celery-beat test---")
    result=random.sample([True,False],1)[0]
    GroupBuyTeam.objects.all().update(hour4_notify=result)

@shared_task
def cover_groupbuy_with_users():
    '''
        使用马甲用户对团购订单进行补位
    '''
    order_logger.info("[GROUPBUY_COVER] groupbuy cover starting !!!")
    groupbuyteam_list=GroupBuyTeam.objects.filter(status=GROUPBUY_STATUS.GROUPBUY_STARTED)
    def _cover_groupbuy(groupbuyteam):
        #修改成团组状态
        order_logger.info('[GROUPBUY_COVER] try to cover groupbuyteam(%s)' % (groupbuyteam.id))
        left_user_number=groupbuyteam.left_user_number

        groupbuyteam.current_user_number+=left_user_number
        groupbuyteam.left_user_number=0
        groupbuyteam.status=GROUPBUY_STATUS.GROUPBUY_SUCCESSED
        groupbuyteam.success_time = datetime.datetime.now()
        groupbuyteam.save()

        #更新发起用户订单状态
        groupbuyteam_order_list=groupbuyteam.groupbuyteamorder_set.all()

        for groupbuyteam_order in groupbuyteam_order_list:
            if groupbuyteam_order.order_id:
                Order.objects.filter(id=groupbuyteam_order.order_id, status=ORDER_STATUS.PAID).update(groupbuy_status=GROUPBUY_STATUS.GROUPBUY_SUCCESSED)

        #马甲用户id列表
        majia_user_id_list=User.objects.values_list("id",flat=True).all()[0:1000]

        #补位小组订单
        for majia_id in random.sample(majia_user_id_list,left_user_number):
            GroupBuyTeamOrder.objects.create(user_id=majia_id,groupbuy_team=groupbuyteam,order_id=0,paid=True)
        order_logger.info('[GROUPBUY_COVER] cover groupbuyteam(%s) finished' % (groupbuyteam.id))


    for groupbuyteam in groupbuyteam_list:

        # old_user=Person.objects.get(user_id=groupbuyteam.creator_user_id).settlement_set.filter(status=SETTLEMENT_STATUS.PAID).exists()
        # info_logger.info("user_id:{0}是{1}用户".format(old_user))

        myorder=groupbuyteam.groupbuyteamorder_set.get(user_id=groupbuyteam.creator_user_id)
        orders=Order.objects.filter(user_id=groupbuyteam.creator_user_id).exclude(id=myorder.order_id)
        old_user=orders.exclude(status__in=(ORDER_STATUS.CANCEL, ORDER_STATUS.NOT_PAID)).exists()

        if not old_user:
            span_time=groupbuyteam.end_time-datetime.datetime.now()
            total_seconds=span_time.total_seconds()

            #成团限制时间
            groupbuy_span=groupbuyteam.end_time- groupbuyteam.start_time
            if groupbuy_span.total_seconds()<8*60*60 and total_seconds<60*60:
                order_logger.info("[GROUPBUY_COVER] trigger cover groupbuyteam(%s) for 8h" % (groupbuyteam.id))
                _cover_groupbuy(groupbuyteam)
            elif total_seconds<4*60*60:
                order_logger.info("[GROUPBUY_COVER] trigger cover groupbuyteam(%s) for lost time less than 4h" % (groupbuyteam.id))
                _cover_groupbuy(groupbuyteam)

    order_logger.info("[GROUPBUY_COVER] groupbuy cover finished !!!")

@shared_task
def hour4_or_hour24_notify():
    '''
        用户在开团【4小时】【24小时】 后未完成拼团，触发消息模板唤醒
    '''
    groupbuy_team_list=GroupBuyTeam.objects.filter(status=GROUPBUY_STATUS.GROUPBUY_STARTED)

    #result=random.sample([True,False],1)[0]
    #GroupBuyTeam.objects.all().update(hour4_notify=result)


    access_token=get_wechat_access_token()

    #info_logger.info("access_token---")
    #info_logger.info(access_token)

    for groupbuy_team in groupbuy_team_list:
        #获取美购的tag_name
        service_item = ServiceItem.objects.only('id', 'service').prefetch_related('service').get(id=groupbuy_team.service_item_id)
        #拼团发起者
        creator_user_id=groupbuy_team.creator_user_id

        creator_user=User.objects.get(id=creator_user_id)

        settlement=Settlement.objects.filter(person=creator_user.person,status=SETTLEMENT_STATUS.PAID).last()

        #info_logger.info("settlement---")
        #info_logger.info(settlement)

        form_id=settlement.form_id

        #info_logger.info("form_id is -----")
        #info_logger.info(form_id)

        #提醒用户拼团
        tag_name=service_item.service.show_tags
        left_user_number=groupbuy_team.left_user_number

        #拼团未成功
        if left_user_number!=0:
            message="您发起的【{tag_name}】拼团还差{left_user_number}，快去叫小伙伴来一起变美吧!".format(tag_name=tag_name,left_user_number=left_user_number)
            
            #小程序推送
            #uw=UserExtraWechatInfo.objects.get(user_id=creator_user_id)

            #info_logger.info("message---")
            #info_logger.info(message)
            #info_logger.info("creator_user_id:{}".format(creator_user.id))

            user_info=PlatformUser.objects.filter(user_id=creator_user.id,platform_type__in=[LOGIN_AUTH_TYPE.Wechat]).last()

            try:
                #info_logger.info("extra_info----")
                #info_logger.info(user_info.extra_info)

                open_id=""
                if user_info.extra_info:
                    extra_info=json.loads(user_info.extra_info)
                    open_id=extra_info.get("openId")

                if not open_id:
                    open_id=user_info.platform_id

                template_id=settings.TEMPLATE_GROUPBUY_UNFINISHED

                #info_logger.info("open_id:{0}".format(open_id))
                #info_logger.info("template_id:{0}".format(template_id))

                #获取订单信息
                groupbuyteamorder=groupbuy_team.groupbuyteamorder_set.get(user_id=creator_user_id)
                order=Order.objects.get(id=groupbuyteamorder.order_id)


                data={
                    "keyword1": {
                      "value": service_item.service.name
                    },
                    "keyword2": {
                      "value": order.service_price
                    },
                    "keyword3": {
                      "value": order.id
                    },
                    "keyword4": {
                      "value": message
                    }
                }

                #推送
                def push_notice():
                    info_logger.info(template_id)
                    return applet_template_push(
                        access_token,
                        open_id,
                        template_id,
                        form_id,
                        data=data,
                    )

                if open_id:
                    span_time=datetime.datetime.now()-groupbuy_team.start_time
                    if span_time.total_seconds()>4*60*60 and not groupbuy_team.hour4_notify:
                        result=push_notice()
                        #推送成功后
                        if result.get('errmsg')=="ok":
                            groupbuy_team.hour4_notify=True
                            groupbuy_team.save()
                        else:
                            info_logger.info(result)

                    if span_time.total_seconds()>24*60*60 and not groupbuy_team.hour24_notify:
                        result=push_notice()
                        #推送成功后
                        if result.get('errmsg')=="ok":
                            groupbuy_team.hour24_notify=True
                            groupbuy_team.save()
                        else:
                            info_logger.info(result)
            except Exception as e:
                pass
                #info_logger.info(e)

            #info_logger.info("拼团未完成消息提醒---")

@shared_task
def success_groupbuy_notify():
    '''
        团购成功通知
        只有2019-10-10号之后的拼团成功用户才接受通知
    '''

    # result=random.sample([True,False],1)
    # GroupBuyTeam.objects.all().update(hour4_notify=True)

    groupbuyteam_list=GroupBuyTeam.objects.filter(status=GROUPBUY_STATUS.GROUPBUY_SUCCESSED,success_notify=False,create_time__gt="2019-10-10")

    access_token=get_wechat_access_token()
    for groupbuy_team in groupbuyteam_list:
        #获取美购的tag_name
        service_item = ServiceItem.objects.only('id', 'service').prefetch_related('service').get(id=groupbuy_team.service_item_id)
        #拼团发起者
        creator_user_id=groupbuy_team.creator_user_id

        creator_user=User.objects.get(id=creator_user_id)

        settlement=Settlement.objects.filter(person=creator_user.person,status=SETTLEMENT_STATUS.PAID).last()

        #info_logger.info("settlement---")
        #info_logger.info(settlement)

        #提醒用户拼团
        tag_name=service_item.service.show_tags

        user_info=PlatformUser.objects.filter(user_id=creator_user.id,platform_type__in=[LOGIN_AUTH_TYPE.Wechat]).last()

        message="您发起的【{tag_name}】拼团已完成，快和小伙伴们约起来吧!".format(tag_name=tag_name)

        try:
            form_id=settlement.form_id

            #info_logger.info("form_id is -----")
            #info_logger.info(form_id)
            #info_logger.info("extra_info----")
            #info_logger.info(user_info.extra_info)

            open_id=""
            if user_info.extra_info:
                extra_info=json.loads(user_info.extra_info)
                open_id=extra_info.get("openId")

            if not open_id:
                open_id=user_info.platform_id

            template_id=settings.TEMPLATE_GROUPBUY_FINISHED

            groupbuyteamorder=groupbuy_team.groupbuyteamorder_set.get(user_id=creator_user_id)

            order_id=groupbuyteamorder.order_id

            order=Order.objects.get(id=order_id)

            data={
                "keyword1": {
                  "value": service_item.service.name
                },
                "keyword2": {
                  "value": order.service_price
                },
                "keyword3": {
                  "value": order.id
                },
                "keyword4": {
                  "value": order.password
                },
                "keyword5": {
                  "value": message
                }
            }

            #推送
            def push_notice():
                return applet_template_push(
                    access_token,
                    open_id,
                    template_id,
                    form_id,
                    data=data,
                )
            if open_id:
                result=push_notice()
                if result.get('errmsg')=="ok":
                    groupbuy_team.success_notify()
                else:
                    pass
                    #info_logger.info(result)
        except Exception as e:
            pass
            #info_logger.info(e)
