from rest_framework.views import APIView
from rest_framework.response import Response
import requests
from etc.settings.local import code2Session, AppId, AppSecret
from common.accounts.models import Users, Accounts
from rest_framework_jwt.settings import api_settings
import json
from common.utils.return_structure import general_message, error_message
from common.utils.service_code import VERIFICATION_ERROR
from rest_framework import status


def get_login_info(code):
    code_url = code2Session.format(AppId, AppSecret, code)
    response = requests.get(code_url)
    json_response = response.json()  # 把它变成json的字典
    if json_response.get("session_key"):
        return json_response
    else:
        return False


class Login(APIView):
    def post(self, request):
        code = request.data.get('code')
        if not code:
            return Response({'message': '缺少code'},
                            status=status.HTTP_400_BAD_REQUEST)

        url = "https://api.weixin.qq.com/sns/jscode2session?" + \
            "appid={0}&secret={1}&js_code={2}&grant_type=authorization_code" \
            .format(AppId, AppSecret, code)
        r = requests.get(url)
        res = json.loads(r.text)
        openid = res['openid'] if 'openid' in res else None
        # session_key = res['session_key'] if 'session_key' in res else None
        if not openid:
            return Response(
                data=error_message(code=VERIFICATION_ERROR, msg_show="微信调用失败"))

        # 判断用户是否第一次登录
        try:
            user = Users.objects.get(openid=openid)
        except Exception:
            # 微信用户第一次登陆,新建用户
            acc = Accounts.objects.create(username=str(openid))
            acc.set_password("1qa@WS3ed")
            user = Users.objects.\
                create(account=acc, wechat=openid, deleted=0, nickname=openid)
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        resp_data = {
            "user_id": user.id,
            "username": user.nickname,
            "token": token,
        }
        return Response(data=general_message(msg_show="数据请求成功",
                                             bean=resp_data),
                        status=status.HTTP_200_OK)
