import hashlib
from sanic import Blueprint, response
from sanic.views import HTTPMethodView
from pot_libs.logger import log
from pot_libs.mysql_util.mysql_util import MysqlUtil
from pot_libs.settings import SETTING
from unify_api.modules.wechat_message.procedures.register_pds import \
    WechatMpMSg, wechatMp

wechat_blueprint = Blueprint("wechat", url_prefix="/api/common")


class RegisterView(HTTPMethodView):
    """用户注册"""

    async def get(self, request, *args, **kwargs):
        try:
            log.info("RegisterView get")
            args = request.args
            signature = args.get("signature")
            timestamp = args.get("timestamp")
            nonce = args.get("nonce")
            echostr = args.get("echostr")
            token = SETTING.wechat_mp_token  # 请按照公众平台官网\基本配置中信息填写
            list = [token, timestamp, nonce]
            list.sort()
            sha1 = hashlib.sha1()
            # map(sha1.update, list)
            sha1.update(''.join(list).encode())
            hashcode = sha1.hexdigest()
            if hashcode == signature:
                return response.text(echostr)
            else:
                return response.text("")
        except:
            return response.text('error')

    async def post(self, request):
        log.info("RegisterView post")
        # sanic获取参数
        # body = request.json
        body = request.body
        msg = WechatMpMSg(body)
        requestUtil = wechatMp()
        sql_wechat_mp = "select id, openid, unionid, subscribe from " \
                        "wechat_mp_user where openid = %s"
        openid = msg.getOpenId()
        async with MysqlUtil() as conn:
            wechat_mp = await conn.fetchone(sql_wechat_mp,
                                            args=(openid,))
        if msg.getType() == 'event' and msg.getEvent() == 'subscribe':
            # 关注事件
            # 创建新的用户
            # 暂时不使用公众号注册
            await requestUtil.getUserInfoAndUpdateUser(openid)
            return response.text("")
        elif msg.getType() == 'event' and msg.getEvent() == 'unsubscribe':
            # 取消订阅
            if wechat_mp:
                update_sql = "UPDATE wechat_mp_user set subscribe = 0 " \
                             "where openid = %s"
                async with MysqlUtil() as conn:
                    await conn.execute(update_sql, args=(openid,))
        elif msg.getType() == "text":
            # 输入文本事件
            unionid = wechat_mp.get("unionid")
            sql_user = "select user_id from user where wechat_id = %s"
            async with MysqlUtil() as conn:
                user_info = await conn.fetchone(sql_user,
                                                args=(unionid,))
            if not user_info or wechat_mp["subscribe"] == '0':
                # content = "您暂无访问权限，无法登录，请联系管理员开通"
                content = "您还未绑定微信，请先绑定"
            else:
                log.info(f'userid:{user_info["user_id"]}, unionid:{unionid}')
                content = "您的用户ID是： %s" % user_info["user_id"]
            return response.text(msg.generateResonseXml(content))
        return response.text("")


wechat_blueprint.add_route(RegisterView.as_view(), "/wechat/mp")
