from django.shortcuts import render, HttpResponse
from django.http import JsonResponse

from app01 import models


# Create your views here.
def register(request):
    if request.method == 'POST':
        back_dic = {'code': 200, 'msg': '注册成功'}
        # 接收参数
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        re_pwd = request.POST.get('re_pwd')
        email = request.POST.get('email')
        avatar = request.FILES.get('myfile')
        # 验证参数
        if not username:
            back_dic['code'] = 201
            back_dic['msg'] = '用户名必须填写'
            return JsonResponse(back_dic)
        if not pwd:
            back_dic['code'] = 202
            back_dic['msg'] = '密码必须填写'
            return JsonResponse(back_dic)
        if pwd != re_pwd:
            back_dic['code'] = 203
            back_dic['msg'] = '两次密码不一致'
            return JsonResponse(back_dic)
        if not email:
            back_dic['code'] = 204
            back_dic['msg'] = '邮箱必须填写'
            return JsonResponse(back_dic)
        res = models.UserInfo.objects.filter(username=username).first()
        if res:
            back_dic['code'] = 205
            back_dic['msg'] = '用户名已经存在'
            return JsonResponse(back_dic)
        data_dic = {}
        if avatar:
            data_dic['avatar'] = avatar
        import hashlib
        m = hashlib.md5()
        m.update(pwd.encode('utf-8'))
        pwd = m.hexdigest()
        data_dic['username'] = username
        data_dic['password'] = pwd
        data_dic['email'] = email
        models.UserInfo.objects.create(**data_dic)
        back_dic['url'] = '/login/'
        return JsonResponse(back_dic)
    return render(request, 'register.html')


def login(request):
    return render(request, 'login.html')


from PIL import Image, ImageDraw, ImageFont
from io import BytesIO, StringIO
import random


def get_random():
    return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)


def get_code(request):
    img_obj = Image.new('RGB', (430, 35), get_random())
    img_draw = ImageDraw.Draw(img_obj)
    img_font = ImageFont.truetype('static/font/ziti.ttf', 30)
    code = ''
    for i in range(5):
        random_upper = chr(random.randint(65, 90))
        random_lower = chr(random.randint(97, 122))
        random_int = str(random.randint(0, 9))
        tmp = random.choice([random_lower, random_upper, random_int])
        img_draw.text((i * 60 + 60, -2), tmp, get_random(), img_font)
        code += tmp
    print(code)
    request.session['code']