# coding: utf8
import json

import requests
from django.conf import settings

from rpc.tool.error_code import gen, CODES
from api.util.wechat_util import get_wechat_access_token


def wechat_template_push(open_id, template_type, form_id, data):
    """
    小程序模板消息推送
    :param open_id: str
    :param template_type: template_type=vote 投票通知 template_check 为模板审核失败通知
    :param form_id: str
    :param data: dict
    :return:
    """
    if not all([open_id, data, template_type, form_id]):
        return gen(CODES.PARAMS_INCOMPLETE)

    access_token = get_wechat_access_token()

    # if not access_token:
    #     raise Exception('获取access_token失败！')
    # 小程序模板消息推送api
    url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={token}'
    if template_type == "vote":
        template_id = settings.TEMPLATE_VOTE_TEST if settings.DEBUG \
            else settings.TEMPLATE_VOTE
    elif template_type == "template_check":
        template_id = settings.TEMPLATE_CHECK_TEST if settings.DEBUG \
            else settings.TEMPLATE_CHECK
    page = "/pages/activity/upload/main?from=notpk" if template_type == "template_check" \
        else "/pages/activity/viewResults/main?from_upgrade=1&from=level"
    push_data = {
        "touser": open_id,
        "template_id": template_id,
        "page": page,
        "form_id": form_id
    }
    push_data.update({'data': data})
    result = requests.post(
                url=url.format(token=access_token),
                data=json.dumps(push_data)
    )
    # error_code 为0 表示成功，其他为失败
    error_code = json.loads(result.content.decode('utf-8')).get('errcode', '')
    return error_code
