# -*- 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 swyzxwb_photovote.common.DataConvert import CheckPOST,str2int
from UserManage.views.permission import PermissionVerify
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.conf import settings
from vote.models import *
from UserManage.models import *
from vote.genemptyxls import GenEmptyXLSFunc
from swyzxwb_photovote.common.DataConvert import UniqueID
from UserManage.forms import XLSFileForm
from vote.xlsadd import processPWXLS
import uuid
#import traceback

@login_required
@PermissionVerify()
def sysRestart(request):
	kwvars = {'request':request}
	return render_to_response('vote/restart.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def ListContestants(request):
	mList = Contestants.objects.all()

	#筛选器
	classobjs = GroupList.objects.all()
	allclass=map(lambda x:x.name,classobjs)
	fco = FilterCondition()
	fco.addTextContain("sid","参赛者用户名","user__username")
	fco.addTextContain("nick","参赛者姓名","user__nickname")
	fco.addTextContain("nick","作品ID","works_set__uuid")
	fco.addTextContain("title","作品标题","works_set__title")
	fco.addMultiChoice("class","组别","classid__name",allclass)
	
	fList = CommonFilter(request,fco,mList)
	#分页功能
	lst = SelfPaginator(request,fList, 20)

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

	return render_to_response('vote/contestant.list.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def ListVoteRecords(request):
	mList = VoteRecords.objects.all()

	#筛选器
	fco = FilterCondition()
	fco.addTextContain("cun","参赛者用户名","target__author__user__sid")
	fco.addTextContain("cnk","参赛者姓名","target__author__user__nickname")
	fco.addTextContain("vun","投票者用户名","voter__username")
	fco.addTextContain("vnk","投票者姓名","voter__nickname")
	fco.addTextContain("pwid","作品ID","target__uuid")
	fco.addTextContain("pwtt","作品标题","target__title")
	
	fList = CommonFilter(request,fco,mList)
	#分页功能
	lst = SelfPaginator(request,fList, 20)

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

	return render_to_response('vote/vr.list.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def ListPhotoWorks(request):
	mList = PhotoWorks.objects.all()

	#筛选器
	classobjs = GroupList.objects.all()
	allclass=map(lambda x:x.name,classobjs)
	fco = FilterCondition()
	fco.addTextContain("uuid","作品ID","uuid")
	fco.addTextContain("author","作者用户名","author__user__username")
	fco.addTextContain("anick","作者姓名","author__user__nickname")
	fco.addTextContain("title","作品标题","title")
	fco.addTextContain("file","文件名","filename")
	fco.addMultiChoice("ext","扩展名","fileext",['jpg','png','gif'])
	fco.addMultiChoice("cls","作者组别","author__user__classid__name",allclass)
	fco.addNumberGreatThan("score","分数大于等于","score",True)
	fco.addNumberLessThan("score","分数小于等于","score",True)
	fco.addNumberEqual("importid","导入批号","ipid")

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

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

	return render_to_response('vote/pw.list.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def ListTopPhotoWorks(request):
	mList = PhotoWorks.objects.all().order_by('-score')

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

	kwvars = {
		'lPage':lst,
		'request':request
	}

	return render_to_response('vote/pw.toplist.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def ListPersonalPW(request):
	mList = PhotoWorks.objects.filter(author__user=request.user)

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

	kwvars = {
		'lPage':lst,
		'request':request
	}

	return render_to_response('vote/pw.plist.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def DeletePhotoWorks(request,ID):
	PhotoWorks.objects.filter(id = ID).delete()
	return HttpResponseRedirect(reverse('pwlist'))

@login_required
@PermissionVerify()
def RemovePW_ByIpid(request,ID):
	try:
		PhotoWorks.objects.filter(importid=ID).delete()
		return HttpResponseRedirect(reverse("pwlist"))
	except Exception,e:
		kwvars = {"msg":"按批号删除作品失败","detail":"按批号删除作品失败","error":str(e)}
		return render_to_response('error.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def ExpPW_ByIpid(request,ID):
	try:
		pwobj = PhotoWorks.objects.filter(importid=ID)[:10]
		lst=map(lambda x:unicode(x.author.user.username)+u"&nbsp;&nbsp;&nbsp;"+unicode(x.title),pwobj)
		ret=u"<br />".join(lst)
		return HttpResponse(ret)
	except Exception,e:
		return HttpResponse(u"错误："+unicode(e))

def ViewPhotoWorks(request,uuid):
	try:
		pwobj = PhotoWorks.objects.get(uuid=uuid)
		try:
			npwobj = PhotoWorks.objects.get(id=pwobj.id+1)
			hasnext = True
			nextuuid = npwobj.uuid
		except PhotoWorks.DoesNotExist:
			hasnext = False
			nextuuid = ""
		if request.user.is_authenticated():
			try:
				vrobj = VoteRecords.objects.get(voter=request.user)
				hadvoted = True
				votedpw = vrobj.target.title
			except VoteRecords.DoesNotExist:
				hadvoted = False
				votedpw = ""
		else:
			hadvoted = False
			votedpw = ""
		kwvars = {'request':request,'pwobj':pwobj,'pwurl':settings.PHOTO_DIR_URL,'hasnext':hasnext,'nextuuid':nextuuid,'hadvoted':hadvoted,'votedpw':votedpw}
		return render_to_response('vote/pw.view.html',kwvars,RequestContext(request))
	except PhotoWorks.DoesNotExist:
		kwvars = {"msg":"404 作品不存在","detail":"您所查看的摄影作品不存在","error":"PhotoWorks '%s' Not Found."%uuid}
		return render_to_response('error.html',kwvars,RequestContext(request))

def FrontListPhotoWorks(request):
	pwlist = PhotoWorks.objects.all()
	lst = SelfPaginator(request,pwlist, 16)
	kwvars = {'request':request,'lPage':lst,'pwurl':settings.PHOTO_DIR_URL,'thumbargs':settings.THUMB_ARGS}
	return render_to_response('vote/pw.flist.html',kwvars,RequestContext(request))

def VotePhotoWorks(request,uuid):
	try:
		pwobj = PhotoWorks.objects.get(uuid=uuid)
		if request.method=='POST':
			chkpr=CheckPOST(['comment',],request.POST.keys())
			if not chkpr == "" :
				kwvars = {"msg":"投票失败","detail":"POST参数错误","error":"Invalid POST Data. Field '"+chkpr+"' Not Found."}
				return render_to_response('error.html',kwvars,RequestContext(request))
			cmt = request.POST['comment']
			try:
				vrobj = VoteRecords.objects.get(voter=request.user)
				oldpw = vrobj.target
				vrobj.target = pwobj
				vrobj.comment = cmt
				vrobj.save()
				oldpw.score = VoteRecords.objects.filter(target=oldpw).count()
				oldpw.save()
			except VoteRecords.DoesNotExist:
				vrobj = VoteRecords.objects.create(voter=request.user,target=pwobj,comment=cmt)
			pwobj.score = VoteRecords.objects.filter(target=pwobj).count()
			pwobj.save()
			return HttpResponseRedirect(reverse('pwflist'))
		else:
			kwvars = {'request':request,'pwobj':pwobj,'pwurl':settings.PHOTO_DIR_URL}
			return render_to_response('vote/pw.vote.html',kwvars,RequestContext(request))
	except PhotoWorks.DoesNotExist:
		kwvars = {"msg":"404 作品不存在","detail":"您所投票的摄影作品不存在","error":"PhotoWorks '%s' Not Found."%uuid}
		return render_to_response('error.html',kwvars,RequestContext(request))

@login_required
def PersonalVoteRec(request):
	try:
		vrobj = VoteRecords.objects.get(voter=request.user)
		hadvoted = True
	except VoteRecords.DoesNotExist:
		hadvoted = False
		vrobj = None
	kwvars = {'request':request,'hadvoted':hadvoted,'vrobj':vrobj,'pwurl':settings.PHOTO_DIR_URL}
	return render_to_response('vote/vr.flist.html',kwvars,RequestContext(request))

@login_required
@PermissionVerify()
def GenEmptyXLS(request):
	if request.method=='POST':
		chkpr=CheckPOST(['nor',],request.POST.keys())
		if not chkpr == "" :
			kwvars = {"msg":"创建空表失败","detail":"POST参数错误","error":"Invalid POST Data. Field '"+chkpr+"' Not Found."}
			return render_to_response('error.html',kwvars,RequestContext(request))
		else:
			try:
				xlsname=GenEmptyXLSFunc(str2int(request.POST['nor']))
				kwvars = {'request':request,'xlsname':xlsname}
				return render_to_response('vote/pw.xlsgendown.html',kwvars,RequestContext(request))
			except Exception,e:
				kwvars = {"msg":"创建空表失败","detail":"生成进程抛出异常","error":e}
				return render_to_response('error.html',kwvars,RequestContext(request))
			
	else:
		kwvars = {'request':request}
		return render_to_response('vote/pw.xlsgen.html',kwvars,RequestContext(request))

def DeleteContestant(request,ID):
	cobj = Contestants.objects.get(id=ID)
	cobj.works_set.all().delete()
	cobj.delete()
	return HttpResponseRedirect(reverse('contestantslist'))

@login_required
@PermissionVerify()
def XLSFilePW(request):
	if request.method=='POST':
		form = XLSFileForm(request.POST,request.FILES)
		if form.is_valid():
			try:
				userdata=processPWXLS(request.FILES['xls'])
			except Exception,e:
				kwvars = {"msg":u"导入作品失败","detail":u"解析xls文件失败","error":unicode(e)}
				return render_to_response('error.html',kwvars,RequestContext(request))
			try:
				ipid = UniqueID()
				querysetlist=[]
				for ud in userdata:
					try:
						cobj = Contestants.objects.get(user__username=ud[1])
					except Contestants.DoesNotExist:
						try:
							auobj = User.objects.get(username=ud[1])
							cobj = Contestants.objects.create(user=auobj)
							cobj.save()
						except User.DoesNotExist:
							kwvars = {"msg":u"导入作品失败","detail":u"参赛者用户名错误","error":u"不存在的参赛者用户名: %s （在作品ID为%s的行）"%(ud[1],ud[0])}
							return render_to_response('error.html',kwvars,RequestContext(request))
					if ud[0]!="":
						try:
							t_data=PhotoWorks(uuid=ud[0],
											  author=cobj,
											  title=ud[2],
											  desc=ud[3],
											  filename=ud[4],
											  fileext=ud[5],
											  importid=ipid,
											  score=0)
											 
							#t_user.set_password(ud[3])
							querysetlist.append(t_data)
						except Exception,e:
							kwvars = {"msg":u"导入作品失败","detail":u"导入参赛作品到数据库失败","error":unicode(e)}
							return render_to_response('error.html',kwvars,RequestContext(request))
				PhotoWorks.objects.bulk_create(querysetlist)
			except Exception,e:
				kwvars = {"msg":"导入作品失败","detail":"从xls文件导入参赛作品失败","error":unicode(e)}
				#kwvars = {"msg":u"导入作品失败","detail":unicode(e),"error":traceback.format_exc()}
				return render_to_response('error.html',kwvars,RequestContext(request))
			return HttpResponseRedirect(reverse('pwlist'))
			
	else:
		form = XLSFileForm()

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

	return render_to_response('vote/pw.addxls.html',kwvars,RequestContext(request))
