from django.http import HttpResponse
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException,InvalidAppIdException
from wechatpy.crypto import WeChatCrypto
from wechatpy import WeChatClient
from wechatpy import parse_message

from sales.models import WxOfficialAccounts

def handle_wx(request,company_id):

    wx=WxOfficialAccounts.objects.filter(company_id=company_id)
    if wx:
        wx=wx[0]
        appid=wx.wx_appid
        token=wx.token
        encoding_aes_key=wx.encoding_aes_key

        if request.method == 'GET':
            signature = request.GET.get('signature', '')
            timestamp = request.GET.get('timestamp', '')
            nonce = request.GET.get('nonce', '')
            echo_str = request.GET.get('echostr', '')
            try:
                check_signature(token, signature, timestamp, nonce)
            except InvalidSignatureException:
                echo_str = '错误的请求'
            response = HttpResponse(echo_str)
            return response
        else:
            xml=request.body
            msg=parse_message(xml)
            print(msg)
            # if encoding_aes_key:
            #     crypto = WeChatCrypto(token, encoding_aes_key, appid)
            #     try:
            #         decrypted_xml = crypto.decrypt_message(
            #             xml,
            #             msg_signature,
            #             timestamp,
            #             nonce
            #         )
            #     except (InvalidAppIdException, InvalidSignatureException):
            #         # 处理异常或忽略
            #         pass

    else:
        return HttpResponse('无公司信息')