from django.shortcuts import render,redirect,HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.http import JsonResponse
from django.contrib.auth.decorators import user_passes_test,login_required
from django.core.paginator import Paginator
from stocks.models import *
from utils.models import *
import datetime
from django.contrib.auth.models import User
from django.db.models import Sum
# Create your views here.
def basis(request):
	context = dict()
	#context['actual_institution'] = Institution.objects.first() 
	if request.user.is_authenticated:
		context["actual_institution"] = request.user.personnel.m_actual_institution
		request.session["actual_institution"] = context["actual_institution"].id
		if request.user.is_staff:
			context["role"] = "Admin"
		else:
			context["role"] = "Commercial"
		try:
			if request.session["is_log"] == True:
				context["loader"] = True
				request.session["is_log"] = None
		except:
			pass
		try:
			if request.session["structure"] == None:
				context["actual_structure"] = Structure.objects.first()
				request.session["structure"] = structure_id
			else:
				context["actual_structure"] = Structure.objects.get(id=request.session["structure"])
		except:
			context["actual_structure"] = Structure.objects.first()
			if context["actual_structure"] != None:
				request.session["structure"] = context["actual_structure"].id
		context["structures"] = Structure.objects.filter()
	return context

def set_structure(request,structure_id):
	request.session["structure"] = structure_id
	return index(request)

def index(request):
	context = basis(request)
	if request.user.is_authenticated:
		context['link']=1
		if request.user.is_staff:
			template = "utils/dashboard.html"
			context['nb_ventes']=Transaction.objects.filter(m_institution=context["actual_institution"]).count()
			context['benefice'] =0
			for t in Transaction.objects.filter(m_institution=context["actual_institution"]).iterator():
				context['benefice'] += t.montant()
			context['staff'] = User.objects.count()
			try:
				if request.session["structure"] != None:
					context['produits']=Product.objects.filter(m_structure=request.session["structure"]).count()
				else:
					context['produits']=Product.objects.count()
			except:
				context['produits']=Product.objects.count()
			context["customers_count"]=Customer.objects.filter(m_institution=context["actual_institution"]).count()
			actual_date = datetime.date.today()
			code_date = actual_date.toordinal()
			week_date = actual_date.weekday()
			
			date_start = datetime.date.fromordinal(code_date-week_date)
			context["totals"] = list()
			context["ventes"] = list()
			for i in range(7):
				tmp_date = datetime.date.fromordinal((code_date-week_date+i))
				solds = Transaction.objects.filter(m_date__date=tmp_date,m_institution=context["actual_institution"])
				tmp = 0
				tmp2 = 0
				for s in solds:
					tmp += int(s.montant())
					tmp2 += int(s.products().count())
				context["totals"].append(tmp)
				context["ventes"].append(tmp2)
			products = Product.objects.filter(m_institution=context["actual_institution"])

			context["prds"] = products
			context["nbps"] = list()

			for prd in products:
				trs = TransactionProduct.objects.filter(m_product=prd).aggregate(Sum('m_qte'))['m_qte__sum']
				context["nbps"].append(trs)
			#TransactionProduct.objects.filter().aggregate(Sum('fees'))['fees__sum']

			response = render(request,template,context)




		else:
			#template = "utils/salers_shop.html"
			#context["tr_row1"] = [0,0,0,0,0]
			#context['trans'] = Transaction.objects.filter()
			response = saler_shop(request)



	else:
		template = "utils/index.html"
		response = render(request,template,context)

	"""
	sales = {
	"lun":,

	}
	"""
	#Student.objects.filter(family=self).aggregate(Sum('fees'))['fees__sum']
	#Solds.objects
	


	return response

# View which return the tool to edit bills
def saler_shop(request):
	template = "utils/salers_shop.html"
	context = basis(request)
	context['link']=6
	context["products"] = Product.objects.filter(m_type__m_institution=context["actual_institution"])
	return render(request,template,context)	

def dashboard(request):
	template = "utils/dashboard.html"
	context = {'link':1}
	return render(request,template,context)	


# Stock Views Management
# ---------------------------------------------------------------
def stock(request,search = None):
	context = basis(request)
	if request.user.is_authenticated:
		if request.user.is_staff:
			template = "utils/stocks.html"
		else:
			template = "utils/stocks2.html"
		context['link'] = 2
		items = Product.objects.filter()
		if True:
			if context["actual_institution"] !=  None:
				items = items.filter(m_type__m_institution=context["actual_institution"])#m_structure=request.session["structure"]
			else:
				items = items.filter(m_structure=None)
		else:
			pass
		if search != None:
			items1 = list(items.filter(m_code__contains=search))
			items2 = list(items.filter(m_name__contains=search))
			items = items1 + items2
			context["search"] = search

		paginator = Paginator(items,12)
		page_number = request.GET.get('page')
		page_obj = paginator.get_page(page_number)
		context['pages']=page_obj
		context['num_pages']=paginator.num_pages
		context['page_range']=paginator.page_range

	return render(request,template,context)		

def stock_search(request):
	return stock(request,request.POST["search"])

def stock_add(request,product_id=0):
	context = basis(request)
	if product_id != 0:
		product = Product.objects.get(id=product_id)
		context["product"] = product
		context["typeproduct"] = product.m_type
	template = "utils/stock_add.html"
	context['link'] = 2
	context['types'] = TypeProduct.objects.filter(m_institution=context["actual_institution"])
	return render(request,template,context)		

def stock_type_add(request,cat_id=0):
	template = "utils/stock_type_add.html"
	context = basis(request)
	if cat_id != 0:
		product =  TypeProduct.objects.filter(id=cat_id).first()
		context["product"] = product
	return render(request,template,context)		
	

def stock_infos(request,type_element,element_id):
	context = basis(request)
	if type_element == "prd":
		return stock_add(request,element_id)

def stock_add_form(request):
	context = basis(request)
	name = request.POST['name']
	try:
		prix = int(request.POST['prix'])
	except:
		prix = None
	unite = request.POST["unite"]
	try:
		qte = int(request.POST['qte'])
	except:
		qte = None
	typ = TypeProduct.objects.get(id=int(request.POST['typ']))
	attributes = request.POST['attributes']
	#desc = request.POST['desc']
	product_id = int(request.POST["edit_id"])
	if product_id != 0:
		product = Product.objects.get(id=product_id)
		product.m_name=name
		product.m_price=prix
		product.m_qte=qte
		product.m_type=typ
		product.m_description=attributes
		product.m_unite=unite
	else:
		product = Product(m_name=name,m_price=prix,m_qte=qte,m_type=typ,m_description=attributes,m_unite=unite,m_institution=context["actual_institution"])
	try:
		if request.session["structure"] != None:
			product.m_structure = Structure.objects.get(id=request.session["structure"])
	except:
		pass
	product.save()
	product.m_code = product.m_type.m_name[:3] + str(( 1000 + product.id))
	product.save()
	return redirect('/stock/')

def stock_trans(request,date_start="#",date_end="#",produit=0):
	context = basis(request)
	context['link'] = 9
	#'transactions':Transaction.objects.filter()
	template = "utils/stocks_trans.html"

	transactions = Transaction.objects.filter()
	try:
		structure = request.session["session"]
		if structure != None:
			transactions = transactions.objects.filter(m_structure=structure)
	except:
		pass
	if date_start not in ["",None,"#"] :
		transactions = transactions.filter(m_date__gte=date_start)
	if date_end not in ["",None,"#"]:
		transactions = transactions.filter(m_date__lte=date_end)
	if produit != 0:
		context["produit"] = produit
		transactions2 = TransactionProduct.objects.filter(m_product=produit).values("m_transaction")
		ids = list()
		for t in transactions2:
			ids.append(t["m_transaction"])
		transactions = transactions.filter(id__in=ids)
	context["products"] = Product.objects.filter()
	context["date_start"] = date_start
	context["date_end"] = date_end
	paginator = Paginator(transactions,10)
	page_number = request.GET.get('page')
	page_obj = paginator.get_page(page_number)
	context['pages']=page_obj
	context['num_pages']=paginator.num_pages
	context['page_range']=paginator.page_range	
	return render(request,template,context)	

def stock_trans_sort(request):
	try:
		date_start = request.POST["date_start"]
	except:
		date_start = "#"
	try:
		date_end = request.POST["date_end"]
	except:
		date_end = "#"
	try:
		produit = int(request.POST["produit"])
	except:
		produit = 0
	request.POST["date_end"]
	return stock_trans(request,date_start,date_end,produit)

def stock_benef(request):
	def tmp(dates):
		r = list()
		for d in dates:
			trans = Transaction.objects.filter(m_date__date=d)
			tmp_som = 0
			tmp_lost = 0
			tmp_ventes = 0
			for tran in trans :
				if tran.m_sens %2 == 1:
					tmp_lost += tran.montant()
				else:
					tmp_som += tran.montant()
					tmp_ventes += 1
			benef = {
				'date':d,
				'som':tmp_som,
				'lost':tmp_lost,
				'nb_ventes':tmp_ventes
			}
			r.append(benef)
		return r

	template = "utils/stocks_benef.html"
	base = datetime.date.today()
	date_list = [base - datetime.timedelta(days=x) for x in range(31)]
	benefs = list()
	benefs_week = list()
	week_day = base.weekday()
	date_week_list = [base - datetime.timedelta(days=x) for x in range(week_day,0,-1)]
	date_week_list += [base + datetime.timedelta(days=y) for y in range(week_day-1,6)]

	date_pre_weeks = [base - datetime.timedelta(days=x+7) for x in range(7)]

	benefs = tmp(date_list)
	benefs_week = tmp(date_week_list)
	benefs_pre_weeks = tmp(date_pre_weeks)
	context = basis(request)
	context['link'] = 2
	context['links2'] = 3
	context['benefices'] = benefs
	context['benefs_week'] = benefs_week
	context['benefs_pre_weeks'] = benefs_pre_weeks
	return render(request,template,context)	

def stock_rapport(request):
	template = "utils/stocks_rapport.html"
	tps = TypeProduct.objects.filter()
	total = 0
	for t in tps:
		total += t.nb_ventes()
	context = basis(request)
	context['link'] = 2
	context['links2'] = 4
	context['products'] = tps
	context['products_short'] = tps[:5]
	context['total'] = total
	return render(request,template,context)	

def stock_ravit(request):
	template = "utils/stocks_ravit.html"
	produits = list()
	for p in Product.objects.iterator():
		if p.ravitaille_urgent():
			produits.append(p)
	context = basis(request)
	context['link']=2
	context['links2']=5
	context['produits']=produits
	return render(request,template,context)	

def stock_promo(request):
	template = "utils/stocks_promo.html"
	promo_products = list()
	is_p= False
	to_p=False
	products_to_prom = list()
	for p in Product.objects.iterator():
		if p.in_promotion() == True:
			promo_products.append(p)
			is_p = True
		if p.to_promote() == True:
			products_to_prom.append(p)
			to_p = True
	context = basis(request)
	context['link']=2
	context['links2']=6
	context['promo_products']=promo_products
	context['products_to_prom']=products_to_prom
	context['is_p']=is_p
	context['to_p']=to_p
	context['products']=Product.objects.filter()
	return render(request,template,context)	


# Solds Views Management
# ---------------------------------------------------------------
def solds(request,search = None):
	context = basis(request)
	if request.user.is_authenticated:
		template = "utils/solds.html"
		context['link'] = 6
		trans = Transaction.objects.filter(m_institution=context["actual_institution"],m_sens=0)
		try:
			if request.session["structure"] !=  None:
				items = trans.filter()#m_structure=request.session["structure"]
			else:
				items = trans.filter(m_structure=None)
		except:
			pass
		if search != None:
			items1 = list(items.filter(m_code__contains=search))
			items2 = list(items.filter(m_name__contains=search))
			items = items1 + items2
			context["search"] = search

		paginator = Paginator(items,12)
		page_number = request.GET.get('page')
		page_obj = paginator.get_page(page_number)
		context['pages']=page_obj
		context['num_pages']=paginator.num_pages
		context['page_range']=paginator.page_range

	return render(request,template,context)		

def solds_add(request,search=None):
	context = basis(request)
	template = "utils/salers_shop.html"
	context["tr_row1"] = [0 for i in range(20)]
	context["products"] = Product.objects.filter(m_type__m_institution=context["actual_institution"])
	items = Transaction.objects.filter(m_institution=context["actual_institution"])
	if search != None:
		items = items.filter(m_code__contains=search)

	paginator = Paginator(items,15)
	page_number = request.GET.get('page')
	page_obj = paginator.get_page(page_number)
	context['pages']=page_obj
	context['num_pages']=paginator.num_pages
	context['page_range']=paginator.page_range


	context['link']=6
	return render(request,template,context)		

def solds_search(request):
	return solds_add(request,request.POST["search"])

def ajax_get_facture(request):
	data = dict()
	id_facture = request.GET.get('id_facture')
	transaction = Transaction.objects.filter(id=id_facture).first()
	
	facture = Facture.objects.first()
	
	data["facture"] = facture.parse(transaction)
	return JsonResponse(data,safe=False)

# Customers Views Management
# ------------------------------------------------------------------
def customers(request):
	context = basis(request)
	template = "utils/customers.html"
	context['link'] = 7
	items = Customer.objects.filter()

	paginator = Paginator(items,12)
	page_number = request.GET.get('page')
	page_obj = paginator.get_page(page_number)
	context['pages']=page_obj
	context['num_pages']=paginator.num_pages
	context['page_range']=paginator.page_range
	return render(request,template,context)		

def customers_add(request):
	context = basis(request)
	context['link'] = 7
	roles = Role.objects.filter()
	context["roles"] = roles
	template = "utils/customers_add.html"
	return render(request,template,context)

def customers_add_form(request):
	name = request.POST['name']
	actual_institution = request.user.personnel.m_actual_institution
	try:
		tel = int(request.POST['tel'])
	except:
		tel = None
	try:
		mail = int(request.POST['mail'])
	except:
		mail = None
	#desc = request.POST['desc']
	product_id = int(request.POST["edit_id"])
	if product_id != 0:
		product = Customer.objects.get(id=product_id)
		product.m_name=name
		product.m_tel=tel
		product.m_gmail=mail
	else:
		product = Customer(m_name=name,m_tel=tel,m_gmail=mail,m_institution=actual_institution)
	product.save()
	product.m_code = "CLT" + str(( 1000 + product.id))
	product.save()
	return redirect('/customers/')

# Personnel Views Management
# ---------------------------------------------------------------
def RH(request):
	context = basis(request)
	items = Personnel.objects.filter(m_actual_institution=context["actual_institution"])

	paginator = Paginator(items,12)
	page_number = request.GET.get('page')
	page_obj = paginator.get_page(page_number)
	context['pages']=page_obj
	context['num_pages']=paginator.num_pages
	context['page_range']=paginator.page_range

	template = "utils/RH.html"
	context['link'] = 3
	return render(request,template,context)	

def RH_add(request):
	context = basis(request)
	context['link'] = 3
	roles = Role.objects.filter(m_institution=context["actual_institution"])
	context["roles"] = roles
	template = "utils/RH_add.html"
	return render(request,template,context)

def RH_add_form(request):
	prenom = request.POST['prenom']
	nom = request.POST["nom"]
	email = request.POST["email"]
	tel = request.POST["tel"]
	user = User(username=tel,first_name=prenom,last_name=nom,email=email)
	user.set_password("user1234")
	user.save()

	actual_institution = request.user.personnel.m_actual_institution
	personnel = Personnel(m_actual_institution=actual_institution,m_user=user,m_tel=tel)
	personnel.save()
	
	return redirect('/RH/')

# ================================================
def partners(request):
	context = basis(request)
	template = "utils/partners.html"
	context['link'] = 8
	items = Fournisseur.objects.filter()
	paginator = Paginator(items,12)
	page_number = request.GET.get('page')
	page_obj = paginator.get_page(page_number)
	context['pages']=page_obj
	context['num_pages']=paginator.num_pages
	context['page_range']=paginator.page_range
	return render(request,template,context)	

def partners_details(request,partner_id):
	context = basis(request)
	template = "utils/partners_details.html"
	context['link'] = 8
	partner = Fournisseur.objects.filter(id=partner_id).first()
	context["partner"] = partner
	items = partner.users()
	paginator = Paginator(items,15)
	page_number = request.GET.get('page')
	page_obj = paginator.get_page(page_number)
	context['pages']=page_obj
	context['num_pages']=paginator.num_pages
	context['page_range']=paginator.page_range
	return render(request,template,context)	

def partners_add(request,partner_id,mode_add):
	context = basis(request)
	template = "utils/partners_add.html"
	context['link'] = 8
	if mode_add == 1:
		partner = Fournisseur.objects.filter(id=partner_id).first()
		context["partner"] = partner
		context['partners'] = Fournisseur.objects.filter() 
		response = render(request,template,context)	
	elif mode_add == 3:
		prenom = request.POST['prenom']
		nom = request.POST["nom"]
		email = request.POST["email"]
		tel = request.POST["tel"]
		user = User(username=tel,first_name=prenom,last_name=nom,email=email)
		user.set_password("user1234")
		user.save()
		fournisseur = Fournisseur.objects.get(id=int(request.POST["fournisseur"]))
		four = FournisseurUser(m_user=user,m_fournisseur=fournisseur,m_tel=tel)
		four.save()
		response = redirect("/partners/"+str(fournisseur.id)+"/")
	return response

def ajax_get_type_product(request):
	type_id = int(request.GET.get('id',None))
	tmp = TypeProduct.objects.get(id=type_id)
	result = {
		'desc':tmp.m_fields
	}
	return JsonResponse(result,safe=False)

def ajax_get_product(request):
	code = request.GET.get('code',None)

	product = Product.objects.filter(m_code=code).first()
	result = {
		'code':product.m_code,
		'name':product.m_name,
		'price':product.m_price
	}
	return JsonResponse(result,safe=False)

def ajax_get_transaction(request):
	code = request.GET.get('code',None)
	transaction = Transaction.objects.get(m_code=code)
	products = transaction.products()
	result = {
		'code':code
	}
	products_name = list()
	products_code = list()
	products_qte = list()
	products_prix = list()
	for p in products:
		products_name.append(p.m_product.m_name)
		products_code.append(p.m_product.m_code)
		products_qte.append(p.m_qte)
		products_prix.append(p.m_product.m_price)
	result["products_name"] = products_name
	result["products_code"] = products_code
	result["products_qte"] = products_qte
	result["products_prix"] = products_prix
	return JsonResponse(result,safe=False)

def ajax_promo(request):
	id_prd = int(request.GET.get('id',None))
	product = Product.objects.get(id=id_prd)	
	product.promo_date = datetime.datetime.today()
	product.promo_duration = 7
	product.save()
	result = {
		'product':product.m_name,
		'date':str(product.promo_date)
	}
	return JsonResponse(result,safe=False)

def ajax_save_trans(request):
	result = {
		'success':False
	}
	if True:
		nb_pa = int(request.GET.get('nb_pa'))
		codes = request.GET.get('codes').split("#")
		nums = request.GET.get('nums').split("#") 
		prices = request.GET.get('prices').split('#')

		client_code = request.GET.get("client")
		#is_client
		pr_acts = list()
		t=Transaction(m_institution=request.user.personnel.m_actual_institution)
		t.save()

		t.m_code = "TRS"+str(1000+t.id)
		t.m_staff = User.objects.get(username = request.GET.get('staff',None))
		t.m_sens = 0
		if client_code != "#":
			client = Customer.objects.filter(m_code=client_code).first()
			t.m_customer = client
			#pass 
		t.save()
		
		for i in range(nb_pa):
			if True:
				code = codes[i]
				qte = nums[i]
				prix = prices[i]

				product = Product.objects.filter(m_code=code).first()
				if product is not None:
					product.m_qte -= int(qte)
					product.save()
					t2 = TransactionProduct(m_transaction = t,m_product = product, m_qte=qte,m_forced_value=prix)
					t2.save()

			else:
				pass
		result['success'] = True
		result['id'] = t.id
		result['code'] = t.m_code
		result['date'] = str(t.m_date)
		result['montant'] = int(t.montant())
		result['sens'] = t.readable_sense()
		result['client'] = t.client()
	else:
		pass
	return JsonResponse(result,safe=False)

def ajax_search_client(request):
	nom = request.GET.get('nom',None)
	prenom = request.GET.get('prenom',None)
	tel = request.GET.get('tel',None)
	clients = Customer.objects.filter()
	if nom not in ["",None]:
		clients = clients.filter(m_name__contains=nom)
	if prenom not in ["",None]:
		clients = clients.filter(m_name__contains=prenom)
	if tel not in ["",None]:
		clients = clients.filter(m_tel=tel)
	clients = list(clients.values('m_code','m_name'))
	data = { "result":clients }
	return JsonResponse(data,safe=False)

def save_type_product(request):
	test = False
	actual_institution = request.user.personnel.m_actual_institution
	try:
		name = request.GET.get('name_typ',None)
		message = str(request.GET.get('message',None))
		typ = TypeProduct(m_name = name,m_fields=message,m_institution=actual_institution)
		typ.save()
		test = True
	except:
		pass
	result = {
		'test':test
	}
	return JsonResponse(result,safe=False)

def compta(request):
	context = basis(request)
	template = "utils/compta.html"
	context['link'] = 4
	return render(request,template,context)		

def ravit(request):
	context = basis(request)
	template = "utils/ravit.html"
	context['link'] = 16
	items = Ravitaillement.objects.filter()
	paginator = Paginator(items,15)
	page_number = request.GET.get('page')
	page_obj = paginator.get_page(page_number)
	context['pages']=page_obj
	context['num_pages']=paginator.num_pages
	context['page_range']=paginator.page_range

	return render(request,template,context)	

def ravit_add(request,mode_add):
	context = basis(request)
	context['link'] = 16
	if mode_add == 1:
		template = "utils/ravit_add.html"
		context["fournisseurs"] = Fournisseur.objects.filter()
		context["personnels"] = FournisseurUser.objects.filter()
		context["products"] = Product.objects.filter()
		response = render(request,template,context)	
	elif mode_add == 3:
		product_id = request.POST["product_id"]
		product = Product.objects.get(id=product_id)
		ravitailleur = FournisseurUser.objects.get(id=int( request.POST["ravitailleur"] ))
		qte = int( request.POST["qte"] )
		product.m_qte += qte
		product.save()
		ravit = Ravitaillement(m_ravitailleur=ravitailleur,m_produit=product,m_qte=qte)
		ravit.save()
		#ravit
		response = redirect('/ravit/')
	return response

def tasks(request):
	context = basis(request)
	template = "utils/tasks.html"
	context['link'] = 5
	return render(request,template,context)		

def enterprise(request):
	context = basis(request)
	template = "utils/enterprise.html"
	context['link'] = 14
	return render(request,template,context)	

def xerxes(request):
	template = "utils/xerxes.html"
	context = {'link':8}
	return render(request,template,context)	

def log(request):
	username = request.POST['username']
	password = request.POST['password']
	user = authenticate(request, username=username, password=password)
	if user is not None:
		login(request, user)
		request.session["is_log"] = True
	return redirect('/')

def log_out(request):
	logout(request)
	return redirect('/')
