# -*- coding: utf-8 -*-
from __future__ import absolute_import

from django.db.models.functions import Coalesce
from django.views.generic import TemplateView
from django.db.models import Case, When, IntegerField

from core.views import LoginRequiredMixin, AdminRequiredMixin
from company.models import *
from kindergarten.models import Kindergarten
from order_contract.models import ProductQuantity
from simulation.models import ProductType
from django.db.models import Sum, F



class SalesStatusView(LoginRequiredMixin, AdminRequiredMixin, TemplateView):
	template_name = 'order_contract/custom_admin/business_status/sales_status.html'

	def get_context_data(self, **kwargs):
		context = super(SalesStatusView, self).get_context_data(**kwargs)
		context["company_set"] = []
		context["area_set"] = []
		context["product_set"] = {}

		type_list = [
			{'season': 'winter', 'style': 'formal', 'p_type': 'jacket'},
			{'season': 'winter', 'style': 'training', 'p_type': 'shirts'},
			{'season': 'summer', 'style': 'formal', 'p_type': 'shirts'},
			{'season': 'summer', 'style': 'training', 'p_type': 'shirts'},
		]
		area_list = ["서울", "인천", "강원", "전라", "경북", "경기", "서부", "부산"]
		product_type = {
			'winterformal': {
				'title': '동복정복',
				'items': ['jacket', 'vest', 'shirts', 'pants', 'skirt', 'one-piece', 'overall', 'dress', 'acc']
			},
			'wintertraining': {
				'title': '동복체육복',
				'items': ['shirts', 'pants']
			},
			'summerformal': {
				'title': '하복정복',
				'items': ['shirts', 'pants', 'skirt', 'acc']
			},
			'summertraining': {
				'title': '하체육복',
				'items': ['shirts', 'pants']
			}
		}

		# 유통별 낙찰 현황
		company_list = Company.objects.all().order_by('id')
		for company in company_list:
			under_contract = Kindergarten.objects.filter(
				user_profile__company=company,
				ordercontract__order_status__lt=5
			).distinct().count()

			company_quantity_list = ProductQuantity.objects.filter(
				order_contract__kindergarten__user_profile__company=company,
				order_contract__order_status=5
			)

			set = {
				'name': company.name,
				'winterformal': {},
				'wintertraining': {},
				'summerformal': {},
				'summertraining': {},
				'under_contract': under_contract
			}

			subtotal_kindergarten = 0
			subtotal_product = 0
			for type in type_list:
				q = {
					'{0}__{1}'.format('main_fabric__product', 'season'): type['season'],
					'{0}__{1}'.format('main_fabric__product', 'style'): type['style'],
					'{0}__{1}'.format('main_fabric__product__product_type', 'name'): type['p_type']
				}

				quantity_list = company_quantity_list.filter(**q)
				kindergarten = Kindergarten.objects.filter(
					ordercontract__productquantity__in=quantity_list
				).distinct().count()

				if quantity_list.exists():
					product_count = sumQuantity(quantity_list)
				else:
					product_count = 0

				keyword = type['season'] + type['style']
				set[keyword] = {
					'kindergarten': kindergarten,
					'product': product_count
				}

				subtotal_kindergarten = subtotal_kindergarten + kindergarten
				subtotal_product = subtotal_product + product_count

			set['subtotal_kindergarten'] = subtotal_kindergarten
			set['subtotal_product'] = subtotal_product
			context["company_set"].append(set)



		# 상권별 낙찰 현황
		for area in area_list:
			under_contract = Kindergarten.objects.filter(
				smart_kindergarten__area=area,
				ordercontract__order_status__lt=5
			).distinct().count()

			area_quantity_list = ProductQuantity.objects.filter(
				order_contract__kindergarten__smart_kindergarten__area=area,
				order_contract__order_status=5
			)

			set = {
				'name': area,
				'winterformal': {},
				'wintertraining': {},
				'summerformal': {},
				'summertraining': {},
				'under_contract': under_contract
			}

			subtotal_kindergarten = 0
			subtotal_product = 0
			for type in type_list:
				q = {
					'{0}__{1}'.format('main_fabric__product', 'season'): type['season'],
					'{0}__{1}'.format('main_fabric__product', 'style'): type['style'],
					'{0}__{1}'.format('main_fabric__product__product_type', 'name'): type['p_type']
				}
				quantity_list = area_quantity_list.filter(**q)
				kindergarten = Kindergarten.objects.filter(
					ordercontract__productquantity__in=quantity_list
				).distinct().count()

				if quantity_list.exists():
					product_count = sumQuantity(quantity_list)
				else :
					product_count = 0

				keyword = type['season'] + type['style']
				set[keyword] = {
					'kindergarten': kindergarten,
					'product': product_count
				}

				subtotal_kindergarten = subtotal_kindergarten + kindergarten
				subtotal_product = subtotal_product + product_count

			set['subtotal_kindergarten'] = subtotal_kindergarten
			set['subtotal_product'] = subtotal_product
			context["area_set"].append(set)


		# 제품별 판매 현황
		products = ProductQuantity.objects.filter(order_contract__order_status=5)

		product_set = []
		for type in type_list:
			keyword = str(type['season'] + type['style'])
			context['product_set']['items'] = []

			temp = {
				'name': product_type[keyword]['title'],
				'child': []
			}
			for key in product_type[keyword]['items']:
				q = {
					'{0}__{1}'.format('main_fabric__product', 'season'): type['season'],
					'{0}__{1}'.format('main_fabric__product', 'style'): type['style'],
					'{0}__{1}'.format('main_fabric__product__product_type', 'name'): key,
				}
				product_of_type = products.filter(**q)

				list = product_of_type.aggregate(
					price1 = Coalesce(Sum(
						Case(When(
							supply_price__gte=0,
							supply_price__lt=20000,
							then='quantity')
						),
						output_field=IntegerField()
					),0),
					price2=Coalesce(Sum(
						Case(When(
							supply_price__gte=20000,
							supply_price__lte=25000,
							then='quantity')
						),
						output_field=IntegerField()
					),0),
					price3=Coalesce(Sum(
						Case(When(
							supply_price__gte=25001,
							supply_price__lt=30000,
							then='quantity')
						),
						output_field=IntegerField()
					),0),
					price4=Coalesce(Sum(
						Case(When(
							supply_price__gte=30001,
							supply_price__lt=35000,
							then='quantity')
						),
						output_field=IntegerField()
					),0),
					price5=Coalesce(Sum(
						Case(When(
							supply_price__gte=35001,
							supply_price__lt=40000,
							then='quantity')
						),
						output_field=IntegerField()
					),0),
					price6=Coalesce(Sum(
						Case(When(
							supply_price__gte=40001,
							supply_price__lt=45000,
							then='quantity')
						),
						output_field=IntegerField()
					),0),
					price7=Coalesce(Sum(
						Case(When(
							supply_price__gte=45001,
							supply_price__lt=50000,
							then='quantity')
						),
						output_field=IntegerField()
					),0),
					price8=Coalesce(Sum(
						Case(When(
							supply_price__gte=50001,
							supply_price__lt=60000,
							then='quantity')
						),
						output_field=IntegerField()
					), 0),
					price9=Coalesce(Sum(
						Case(When(
							supply_price__gte=60001,
							supply_price__lt=70000,
							then='quantity')
						),
						output_field=IntegerField()
					), 0),
					price10=Coalesce(Sum(
						Case(When(
							supply_price__gte=70001,
							then='quantity')
						),
						output_field=IntegerField()
					), 0)
				)
				list['name'] = ProductType.objects.get(name=key).get_name_display()
				temp['child'].append(list)

			product_set.append(temp)
			context['product_set']['items'] = product_set

		context['selectedCategory'] = 'order'
		context['sales_status'] = 'select'
		return context

def sumQuantity(obj):
	return obj.aggregate(Sum('quantity'))['quantity__sum']
