#
# -*- coding:utf8 -*-
from django.shortcuts import render,HttpResponse
from app01 import models
from app01 import forms

import json
# Create your views here.

def bookmodel(request):
    if request.method == 'GET':
        Form = forms.BookModelForm()
    elif request.method == 'POST':
        Form = forms.BookModelForm(request.POST)
        if Form.is_valid():
            form_data = Form.cleaned_data
            print(form_data)
            Form.save()
    return render(request,'app01/book.html',{"bk":Form})


def book(request):
    Froms = forms.BookForm()
    if request.method == "POST":
        Froms = forms.BookForm(request.POST)
        if Froms.is_valid():
            print(Froms.cleaned_data)

    return render(request,"app01/book.html",{"bk":Froms})

def resgiter(request):



    # 增
    # models.UserInfo.objects.create(username="liujin",password="123",age=18)
    # models.UserInfo.objects.create(username="owasp",password="123",age=18)

    if request.method == "POST":
        response_data_ok = {"status":"ok"}
        response_data_no = {"status":"no"}
        val = request.POST
        print("val:",val)
        print("username:",val["username"])
        u = models.UserInfo.objects.filter(username=val["username"])
        if len(u) != 0:
            print("user exist")
            return HttpResponse(json.dumps(response_data_no))
        else:
            print("add user")
            models.UserInfo.objects.create(username=val["username"],password=val["password"],age=val["age"])
            return HttpResponse(json.dumps(response_data_ok))

    # 删
    # models.UserInfo.objects.filter(username='ds').delete()
    # 改
    # models.UserInfo.objects.filter(age=18).update(age=20)
    # models.UserInfo.objects.all().update(age=19)
    # 查
    else:
       return  render(request,"app01/Resgiter.html")

        # models.UserInfo.objects.filter(username='ds')
        # models.UserInfo.objects.filter(age=18).first()



def admin(request):
    userlist_obj = models.UserInfo.objects.all()
    return render(request, "app01/admin.html", {"li":userlist_obj})

def login(request):
    # content = open("templates/app01/login.html","r").read()
    # return HttpResponse(content)
    if request.method == "POST":
        user = request.POST["username"]
        pawd =request.POST["password"]
        u_li_obj = models.UserInfo.objects.filter(username=user)
    return render(request,"app01/login.html")


def news(request,nid1):
    return HttpResponse("Your page is %s"%(nid1))


def home(request,n2,n1):
    return HttpResponse("Your page is %s %s"%(n1,n2))


def start(request,n2,n1):
    return HttpResponse("Your page is %s %s"%(n1,n2))