import requests
import json
import redis
from django.conf import settings
from wx.models import WxApp

rd=redis.StrictRedis(host='localhost', port=settings.RD['port'], password=settings.RD['password'], decode_responses=True)

class WxMiniprogram():

    def __init__(self, wx_app_id, wx_secret=None):
        self.WX_APP_ID = wx_app_id
        self.WX_ID = 0
        if not wx_secret:
            wxapp = WxApp.objects.filter(appid=wx_app_id)
            if wxapp:
                self.WX_SECRET = wxapp[0].appsecret
                self.WX_ID = wxapp[0].id
            else:
                raise Exception('无WxApp配置信息')
        else:
            self.WX_SECRET = wx_secret

    def postJson(self, url, postData):
        headers = {
            "Content-Type": "application/json; charset=UTF-8"
        }
        return json.loads(requests.post(url,data=json.dumps(postData), headers=headers).text)

    def getAccessToken(self):
        data = {'e': '', 'access_token': ''}
        token_key = 'wx_accesstoken_'+self.WX_APP_ID
        token = rd.get(token_key)
        if not token:
            url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={self.WX_APP_ID}&secret={self.WX_SECRET}'
            res = json.loads(requests.get(url).text)
            if 'errcode' in res:
                data['e']=res['errmsg']
            else:
                data['access_token'] = res['access_token']
                rd.set(token_key, res['access_token'], 7000)
        else:
            data['access_token'] = token
        return data

    def getPhoneNumber(self, code):
        data = {'e': '', 'phone_info': ''}
        tokenInfo = self.getAccessToken()
        if tokenInfo['e'] == '':
            access_token = tokenInfo['access_token']
            url = f'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={access_token}'
            postData = { 'code': code }
            res = self.postJson(url, postData)
            if 'errcode' in res and res['errcode'] != 0:
                data['e']=res['errmsg']
            else:
                data['phone_info'] = res['phone_info']
        else:
            data['e'] = tokenInfo['e']
        return data

    def getSessionByCode(self, code):
        data = {'e': '', 'openid': '', 'unionid': ''}
        url = f'https://api.weixin.qq.com/sns/jscode2session?appid={self.WX_APP_ID}&secret={self.WX_SECRET}&js_code={code}&grant_type=authorization_code'
        res = json.loads(requests.get(url).text)
        if 'errcode' in res and res['errcode'] != 0:
            data['e'] = res['errmsg']
        else:
            data['openid'] = res['openid']
            if 'unionid' in res:
                data['unionid'] = res['unionid']
        return data