# -*- coding:utf-8 -*-

'''
微信相关服务
'''

from django.conf import settings
from gm_types.gaia import WECHAT_PLATFORM_TYPE

from rpc.decorators import bind
from api.tool.log_tool import wechat_account_logger, logging_exception
from api.util.wechat_util import record_wechat_info
from api.tool.wechat_push import get_wechat_access_token
from utils.wechat_applet_tools import applet_subscribe_msg_push
from api.util.user_util import get_open_id_by_user_id

WECHAT_APP_MAP = {
    settings.WECHAT_SMALL_APPID: WECHAT_PLATFORM_TYPE.GM_SMALL,      ### 更美小程序
    settings.CLIENT_WECHAT_APP_ID: WECHAT_PLATFORM_TYPE.CLIENT_APP,  ### 客户端
}


@bind('api/wechat/record_union_open_id')
def record_union_open_id(user_id, appid, unionid, openid):
    '''
    记录union_id-open_id,
    触发时机: 用户登录时, 异步触发
    :param union_id:
    :param open_id:
    :return:
    '''
    if appid not in WECHAT_APP_MAP:
        wechat_account_logger.warn('[WECHAT_ACCOUNT] app_id(%s) not config' % (appid))
        logging_exception()
        return

    wechat_platform_type = WECHAT_APP_MAP[appid]
    record_wechat_info(user_id, wechat_platform_type, unionid, openid)



@bind('api/wechat/subscribe_msg')
def send_applet_subscribe_msg(user_id, template_id, data=None, page=None):
    access_token = get_wechat_access_token()
    open_id = get_open_id_by_user_id(user_id)
    return applet_subscribe_msg_push(access_token, open_id, template_id, data=data, page=page)
