#!/usr/bin/env python
#-*- coding: utf-8 -*-

from django.core.urlresolvers import reverse
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response,RequestContext
from django.contrib.auth.decorators import login_required
from swyzxwb_photovote.common.CommonPaginator import SelfPaginator
from swyzxwb_photovote.common.CommonFilter import CommonFilter,FilterCondition
from UserManage.views.permission import PermissionVerify
from UserManage.xlsusers import processxls
from UserManage.models import User,RoleList,GroupList
import hashlib
from django.contrib.auth.hashers import make_password
from django.contrib import auth
from django.contrib.auth import get_user_model
from UserManage.forms import LoginUserForm,SignInUserForm,ChangePasswordForm,AddUserForm,EditUserForm,XLSFileForm,RemoveUsersForm,ChangeUserForm,AddAdminForm
from swyzxwb_photovote.common.DataConvert import UniqueID

def LoginUser(request):
    '''用户登录view'''
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')

    if request.method == 'GET' and request.GET.has_key('next'):
        next = request.GET['next']
    else:
        next = '/'

    if request.method == "POST":
        form = LoginUserForm(request, data=request.POST)
        if form.is_valid():
            auth.login(request, form.get_user())
            return HttpResponseRedirect(request.POST['next'])
    else:
        form = LoginUserForm(request)

    kwvars = {
        'request':request,
        'form':form,
        'next':next,
    }

    return render_to_response('UserManage/login.html',kwvars,RequestContext(request))


def SignUp(request):
    '''用户注册view'''
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')

    if request.method=='POST':
        form = SignInUserForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data['password'])
            user.role=RoleList.objects.get(name=u'学生')
            user.is_active = False
            user.is_superuser = False
            form.save()
            return HttpResponseRedirect(reverse('loginurl'))
    else:
        form = SignInUserForm()

    kwvars = {
        'form':form,
        'request':request,
    }

    return render_to_response('UserManage/user.signup.html',kwvars,RequestContext(request))

@login_required
def LogoutUser(request):
    auth.logout(request)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

@login_required
def ChangePassword(request):
    if request.method=='POST':
        form = ChangePasswordForm(user=request.user,data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('logouturl'))
    else:
        form = ChangePasswordForm(user=request.user)

    kwvars = {
        'form':form,
        'request':request,
    }

    return render_to_response('UserManage/password.change.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def ListUser(request):
    mList = get_user_model().objects.all()

    #筛选器
    classobjs = GroupList.objects.all()
    allclass=map(lambda x:x.name,classobjs)
    fco = FilterCondition()
    fco.addTextContain("sid","编号","sid")
    fco.addTextContain("name","用户名","username")
    fco.addTextContain("nick","姓名","nickname")
    fco.addTextContain("mail","邮箱","email")
    fco.addMultiChoice("class","班级","classid__name",allclass)
    fco.addDateRange("bthdy","生日","birthday")
    fco.addNumberEqual("importid","导入批号","ipid")
    fco.addSingleChoice("sex","性别","sex",["男","女"])

    fList = CommonFilter(request,fco,mList)
    #分页功能
    lst = SelfPaginator(request,fList, 20)

    kwvars = {
        'lPage':lst,
        'request':request,
        'FilterHTML':fco.RenderHTML(request)
    }

    return render_to_response('UserManage/user.list.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def AddUser(request):

    if request.method=='POST':
        form = AddUserForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data['password'])
            user.importid = UniqueID()
            print "Unique HASH",user.importid
            form.save()
            return HttpResponseRedirect(reverse('listuserurl'))
    else:
        form = AddUserForm()

    kwvars = {
        'form':form,
        'request':request,
    }

    return render_to_response('UserManage/user.add.html',kwvars,RequestContext(request))


@login_required
@PermissionVerify()
def AddAdmin(request):

    if request.method=='POST':
        form = AddAdminForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data['password'])
            user.role=RoleList.objects.get(name=u'管理员')
            user.importid = UniqueID()
            user.is_active = True
            user.is_superuser = True
            form.save()
            return HttpResponseRedirect(reverse('listuserurl'))
    else:
        form = AddAdminForm()

    kwvars = {
        'form':form,
        'request':request,
    }

    return render_to_response('UserManage/user.addadmin.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def EditUser(request,ID):
    user = get_user_model().objects.get(id = ID)
    if request.method=='POST':
        if not request.POST['role']==user.role.id:
            if request.POST['username']==request.user.username:
                kwvars = {'request':request,'xerror':"您不能修改自己的角色",}
                return render_to_response('UserManage/user.edit.error.html',kwvars,RequestContext(request))
            elif request.POST['role']=="1":
                if not request.user.is_superuser:
                    kwvars = {'request':request,'xerror':"您无权给用户赋予网站管理员权限",}
                    return render_to_response('UserManage/user.edit.error.html',kwvars,RequestContext(request))
        form = EditUserForm(request.POST,instance=user)
        if form.is_valid():
            form.save() 
            return HttpResponseRedirect(reverse('listuserurl'))
    else:
        form = EditUserForm(instance=user
        )

    kwvars = {
        'ID':ID,
        'form':form,
        'request':request,
    }

    return render_to_response('UserManage/user.edit.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def DeleteUser(request,ID):
    if ID == '1':
        return HttpResponse(u'超级管理员不允许删除!!!')
    else:
        get_user_model().objects.filter(id = ID).delete()

    return HttpResponseRedirect(reverse('listuserurl'))

@login_required
@PermissionVerify()
def ResetPassword(request,ID):
    user = get_user_model().objects.get(id = ID)

    newpassword = get_user_model().objects.make_random_password(length=10,allowed_chars='abcdefghjklmnpqrstuvwxyABCDEFGHJKLMNPQRSTUVWXY3456789')
    print '====>ResetPassword:%s-->%s' %(user.username,newpassword)
    user.set_password(newpassword)
    user.save()

    kwvars = {
        'object':user,
        'newpassword':newpassword,
        'request':request,
    }

    return render_to_response('UserManage/password.reset.html',kwvars,RequestContext(request))

@login_required
def AddXlsError(request):

    kwvars = {
        'request':request,
    }

    return render_to_response('UserManage/user.addxls.error.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def XLSFileUser(request):
    if request.method=='POST':
        form = XLSFileForm(request.POST,request.FILES)
        if form.is_valid():
            try:
                userdata=processxls(request.FILES['xls'])
            except Exception,e:
                kwvars = {'request':request,'xerror':e,}
                return render_to_response('UserManage/user.addxls.error.html',kwvars,RequestContext(request))
            try:
                studentrole=RoleList.objects.get(name = u'普通学生')
                ipid = UniqueID()
                querysetlist=[]
                for ud in userdata:
                    if ud[0]!=0:
                        try:
                            t_user=User(username=str(ud[0]),
                                     sid=ud[0],
                                     classid=GroupList.objects.get(classid = ud[4]),
                                     is_active=True,
                                     nickname=ud[1],
                                     sex=ud[2],
                                     birthday=ud[5],
                                     password=make_password(ud[3], None, "unsalted_md5"),
                                     role=studentrole,
                                     importid = ipid)
                            #t_user.set_password(ud[3])
                            querysetlist.append(t_user)
                        except GroupList.DoesNotExist:
                            kwvars = {'request':request,'xerror':u"无效的分组ID：%d （在学号为%d的行）"%(ud[4],ud[0])}
                            return render_to_response('UserManage/user.addxls.error.html',kwvars,RequestContext(request))
                        except Exception,e:
                            kwvars = {'request':request,'xerror':e,}
                            return render_to_response('UserManage/user.addxls.error.html',kwvars,RequestContext(request))
                User.objects.bulk_create(querysetlist)
            except Exception,e:
                kwvars = {'request':request,'xerror':e,}
                return render_to_response('UserManage/user.addxls.error.html',kwvars,RequestContext(request))
            return HttpResponseRedirect(reverse('listuserurl'))
            
    else:
        form = XLSFileForm()

    kwvars = {
        'form':form,
        'request':request,
    }

    return render_to_response('UserManage/user.addxls.html',kwvars,RequestContext(request))


@login_required
@PermissionVerify()
def RemoveUsers(request):
    #get_user_model().objects.filter(id = ID).delete()
    if request.method=='POST':
        form = RemoveUsersForm(request.POST)
        if form.is_valid():
            try:
                #classid = GroupList.objects.get(classid = form.cleaned_data["classid"])
                for cid in form.cleaned_data["classid"]:
                    users = get_user_model().objects.filter(classid = cid)
                
                    for i in users:
                        if i.id == 1:
                            raise Exception,u'超级管理员不允许删除!!!'
                    users.delete()
                return HttpResponseRedirect(reverse('listuserurl'))
            except Exception,e:
                kwvars = {'request':request,'xerror':e,}
                return render_to_response('UserManage/user.remove.error.html',kwvars,RequestContext(request))

    else:
        form = RemoveUsersForm()

    kwvars = {
        'form':form,
        'request':request,
    }

    return render_to_response('UserManage/user.removeusers.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def RemoveUsers_ByIpid(request,ID):
    try:
        uobj = User.objects.filter(importid=ID).delete()
        return HttpResponseRedirect(reverse("listuserurl"))
    except Exception,e:
        kwvars = {'request':request,'xerror':e,}
        return render_to_response('UserManage/user.remove.error.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def ExpUsers_ByIpid(request,ID):
    try:
        uobj = User.objects.filter(importid=ID)[:10]
        lst=map(lambda x:unicode(x.sid)+u"&nbsp;&nbsp;&nbsp;"+unicode(x.nickname),uobj)
        ret=u"<br />".join(lst)
        return HttpResponse(ret)
    except Exception,e:
        return HttpResponse(u"错误："+unicode(e))

@login_required
def ChangInfo(request):
    user = request.user

    if request.method=='POST':
        form = ChangeUserForm(request.POST,instance=user)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = ChangeUserForm(instance=user
        )

    kwvars = {
        'ID':user.id,
        'form':form,
        'request':request,
    }

    return render_to_response('UserManage/user.change.html',kwvars,RequestContext(request))
