__author__ = 'liumx'
# -*- coding: utf-8 -*-
from testzh.models import ArTicle1
from testzh.models import ArTicle2
from testzh.models import Usercenter
from  django.shortcuts import render_to_response
from django.views.decorators.http import require_http_methods
from django.http import HttpResponseRedirect, HttpResponse
import re
from django.db.models import Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import When, F, Q
from django import forms
from django.shortcuts import render_to_response
from django.template.context_processors import csrf
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
import re
class registForm(forms.Form):
    username = forms.CharField(label='用户名：', max_length=20)
    passworld1 = forms.CharField(label='密码：', widget=forms.PasswordInput())
    passworld2 = forms.CharField(label='密码：', widget=forms.PasswordInput())
    email = forms.EmailField(label='电子邮件：',widget=forms.EmailInput)


class loginForm(forms.Form):
    passworld = forms.CharField(label='密码：', widget=forms.PasswordInput())
    username = forms.CharField(label='用户名：', max_length=20)

@require_http_methods(["GET", "POST"])
def regist(request):
    # error=[]
    if request.method == "POST":
        uf = registForm(request.POST)
        #print uf
        #u=request.POST.get("userName")
        #print u
        # print u"注册"
        if uf.is_valid():  # 获取表单信息
            username = uf.cleaned_data['username']
            passworld1 = uf.cleaned_data['passworld1']
            # print passworld1
            passworld2 = uf.cleaned_data['passworld2']
            # print passworld2
            email = uf.cleaned_data['email']

            # print username, passworld1,passworld2, email
            # 将表单写入数据库
            # Usercenter.objects.create(username=username,passworld=passworld,email=email)
            user = Usercenter()
            # print username
            #判断用户名
            if not Usercenter.objects.all().filter(uname=username):
                if len(username)>=2 and len(username)<=16:
                    print "ok"
                    a = re.search(u"[^\u4e00-\u9fa5-A-Za-z]+", username)
                    if a:
                        messages.error(request,u"用户名必须是英文，中文")
                        # error.append(u"用户名必须是英文，中文")
                        # print error
                        #a.group()
                        #print 'seccess:',a.group()
                        #for key in a:
                        #print key
                    else:
                        user.uname = username
                else:
                    messages.error(request,u"用户名格式不正确，必须2-16位")
                    # error.append(u"用户名格式不正确，必须2-16位")
                    # print error

            else:
                messages.error(request,u"用户名已经被注册")
                # error.append(u"用户名已经被注册")
                # print error
            #判断邮箱
            if Usercenter.objects.all().filter(email=email):
                messages.error(request,u"邮箱已经注册")
            else:
                if len(email)>=6 and len(email)<=30:
                    a = re.search("^[a-zA-Z0-9]([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]*.(cn|com|net|org|CN|COM|ENT|ORG)$", email)

                    if a:
                        user.email = email
                        #print u"用户名必须是英文，中文"
                        #a.group()
                        # print 'seccess:',a.group()
                        #for key in a:
                        #print key
                    else:
                        messages.error(request,u"'邮箱格式不正确'")
                else:
                    messages.error(request,u"邮箱格式不正确，必须6-30位")
            #判断密码
            if passworld1 ==passworld2:
                if len(passworld1)>=6 and len(passworld1)<=16:
                    a = re.search("[^a-zA-Z0-9_]+", passworld1)

                    if a:
                        #print u"用户名必须是英文，中文"
                        #a.group()
                        messages.error(request, u'密码格式不正确，必须字符数字，字母，_')
                        #for key in a:
                        #print key
                    else:
                        user.psword = passworld1
                else:
                    messages.error(request, u"密码格式不正确，必须6-16位")
            else:
                messages.error(request,u"两次密码不一致")

            user.save()
            # email.save()
            # passworld1.save()
        # request.session['username'] = username

            # return index(request)
        return render_to_response('regist.html', {"uf": uf}, context_instance=RequestContext(request))
        #print "regist sccuess"
    else:
        uf = registForm()
        # us=uf.username
        # ps=uf.passworld
        # em=uf.email
        # messages.error(request,u"所有必填")
    return render_to_response('regist.html', {"uf": uf}, context_instance=RequestContext(request))
    # return render_to_response('regist.html',{"uf":uf,'us':us,"ps":ps,"em":em})




def out(request):
    del request.session['username']  # 删除session
    uf = loginForm()
    return render_to_response('login.html', {"uf": uf}, context_instance=RequestContext(request))
    # render_to_response('login.html')



def login(request):
    if request.method == "POST":
        uf = loginForm(request.POST)
        #print u"登录"
        if uf.is_valid():  # 获取表单信息
            username = uf.cleaned_data['username']
            passworld = uf.cleaned_data['passworld']
            # print passworld
            user = Usercenter.objects.filter(uname__exact=username, psword__exact=passworld)

            if user:
                # username=user.uname
                # print u"比较成功",username
                # 把获取表单的用户名传递给session对象
                request.session['username'] = username
                # 比较成功，跳转index
                response = HttpResponseRedirect('/index/')
                # 将username写入浏览器cookie,失效时间为3600
                response.set_cookie('username', username, 60)
                return response
                # return render_to_response('index.html',context_instance=RequestContext(request))
            else:
                # 比较失败，还在login
                messages.error(request,u"用户名或者密码不正确")
            # return HttpResponseRedirect('login.html', {"messages":messages})
    else:
        uf = loginForm()
    return render_to_response('login.html', {'uf': uf}, context_instance=RequestContext(request))
