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

import base64

from datetime import datetime
from django.core.files.base import ContentFile
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView, View, ListView
from core.views import LoginRequiredMixin, OwnerRequiredMixin, OrderStatusMixin
from simulation.models import *
from order_contract.models import OrderContract, OptionQuantity, ProductQuantity
from django.http import Http404
from order_contract.supply_price.views import *
import json


class ContractView(LoginRequiredMixin, OwnerRequiredMixin, OrderStatusMixin, TemplateView):
    template_name = 'order_contract/contract/contract.html'

    def get_context_data(self, **kwargs):
        context = super(ContractView, self).get_context_data(**kwargs)
        context["final_set"] = []
        context["option_set"] = []

        order = OrderContract.objects.get(id=self.kwargs['order_id'])
        final = FinalFittingSet.objects.get(order_contract=order)

        for set in final.selectedcoupleset_set.all().order_by(
                'couple__boy_fitting__fitting_category__style',
                '-couple__boy_fitting__fitting_category__season'):

            boy_fitting = set.couple.boy_fitting
            girl_fitting = set.couple.girl_fitting

            product_set = {
                girl_fitting.fitting_category.gender: girl_fitting.product_set.all().order_by('product__product_type_id'),
                boy_fitting.fitting_category.gender: boy_fitting.product_set.all().order_by('product__product_type_id')
            }

            for key, values in product_set.iteritems():
                temp = []
                for product in values:
                    discount_rate = set.discount_rate
                    if product.product.product_type.name == 'acc':
                        discount_rate = set.acc_discount_rate

                    temp = dict(
                        final_couple_id=set.id,
                        couple_id=set.couple.id,
                        product=product,
                        include_tax_price=discountPrice(product.price, discount_rate),
                        exclude_tax_price=excludeTaxPrice(discountPrice(product.price, discount_rate)),
                        gender=key,
                        style=set.couple.boy_fitting.fitting_category.get_style_display(),
                        season=set.couple.boy_fitting.fitting_category.get_season_display()
                    )
                    context["final_set"].append(temp)

        for option_quantity in order.optionquantity_set.all():
            temp = dict(
                quantity_id = option_quantity.id,
                include_tax_price=discountPrice(option_quantity.option.price, option_quantity.discount_rate),
                exclude_tax_price=excludeTaxPrice(discountPrice(option_quantity.option.price, option_quantity.discount_rate)),
                option = option_quantity.option
            )
            context["option_set"].append(temp)

        context['order'] = order
        context["kindergarten"] = order.kindergarten.name
        return context

@method_decorator(csrf_exempt, name='dispatch')
class ContractSubmit(LoginRequiredMixin, View):

    def post(self, request, *args, **kwargs):
        order_id = self.request.POST.get('order_id')
        quantity_dict = json.loads(self.request.POST.get('quantity_dict'))
        option_dict = json.loads(self.request.POST.get('option_dict'))
        special_note = self.request.POST.get('special_note')
        contract_date = self.request.POST.get('contract_date')
        sign_image = self.request.POST.get('sign_image').split(',')[1]
        decode_img = base64.b64decode(sign_image)

        order = OrderContract.objects.get(id=order_id)
        image_filename = str(order.id) + ".png"
        order.sign_image.save(image_filename, ContentFile(decode_img))
        order.contract_date = datetime.strptime(contract_date, '%Y-%m-%d')
        order.special_note=special_note
        order.save()

        order.productquantity_set.all().delete()

        for item in quantity_dict:
            supply_price = 0

            fabric = MainFabric.objects.get(id=item['input_id'])
            selected_couple = SelectedCoupleSet.objects.get(
                final_uniform_set__order_contract=order,
                couple__boy_fitting__fitting_category__style=fabric.product.style,
                couple__boy_fitting__fitting_category__season=fabric.product.season
            )

            if fabric.product.product_type.name == 'acc':
                supply_price = discountPrice(fabric.price, selected_couple.acc_discount_rate)
            else:
                supply_price = discountPrice(fabric.price, selected_couple.discount_rate)

            ProductQuantity.objects.create(
                order_contract=order,
                main_fabric_id=item['input_id'],
                quantity=item['quantity'],
                supply_price = supply_price,
                gender=item['gender']
            )

        for item in option_dict:
            option = order.optionquantity_set.get(option_id=item['input_id'])
            option.quantity = item['quantity']
            option.save()

        order_status = 5
        if order.order_status < order_status:
            order.order_status = order_status
            order.save()

        variables = {'success': True, 'url': reverse('order_contract:completion_index', kwargs={'order_id': order_id})}
        return HttpResponse(json.dumps(variables), content_type='application/json')


class ContractComplete(LoginRequiredMixin, OwnerRequiredMixin, TemplateView):
    template_name = 'order_contract/contract/contract_complete.html'

    def get_context_data(self, **kwargs):
        order_id = self.kwargs['order_id']
        order = OrderContract.objects.get(id=order_id)

        context = super(ContractComplete, self).get_context_data(**kwargs)

        context["final_set"] = []
        context["option_set"] = []

        final = FinalFittingSet.objects.get(order_contract=order)
        for set in final.selectedcoupleset_set.all().order_by(
                'couple__boy_fitting__fitting_category__style',
                '-couple__boy_fitting__fitting_category__season'):

            boy_fitting = set.couple.boy_fitting
            girl_fitting = set.couple.girl_fitting

            product_set = {
                girl_fitting.fitting_category.gender: girl_fitting.product_set.all().order_by('product__product_type_id'),
                boy_fitting.fitting_category.gender: boy_fitting.product_set.all().order_by('product__product_type_id')
            }

            for key, values in product_set.iteritems():
                for product in values:
                    product_quantity = order.productquantity_set.get(main_fabric = product, order_contract=order, gender=key)
                    discount_rate = set.discount_rate
                    if product.product.product_type.name == 'acc':
                        discount_rate = set.acc_discount_rate

                    temp = dict(
                        final_couple_id=set.id,
                        couple_id=set.couple.id,
                        product=product,
                        quantity = product_quantity.quantity,
                        supply_exclude_tax_price=excludeTaxPrice(product_quantity.supply_price),
                        supply_include_tax_price=product_quantity.supply_price,
                        consumer_exclude_tax_price=excludeTaxPrice(product_quantity.supply_price) * product_quantity.quantity,
                        consumer_include_tax_price=product_quantity.supply_price * product_quantity.quantity,
                        gender=key,
                        style=set.couple.boy_fitting.fitting_category.get_style_display(),
                        season=set.couple.boy_fitting.fitting_category.get_season_display()
                    )
                    context["final_set"].append(temp)

        for obj_option_quantity in order.optionquantity_set.all():
            option_quantity = obj_option_quantity.quantity

            temp = dict(
                quantity_id=obj_option_quantity,
                quantity=option_quantity,
                supply_include_tax_price=discountPrice(obj_option_quantity.option.price, obj_option_quantity.discount_rate),
                supply_exclude_tax_price=excludeTaxPrice(discountPrice(obj_option_quantity.option.price, obj_option_quantity.discount_rate)),
                consumer_include_tax_price=discountPrice(obj_option_quantity.option.price, obj_option_quantity.discount_rate) * option_quantity,
                consumer_exclude_tax_price=excludeTaxPrice(discountPrice(obj_option_quantity.option.price, obj_option_quantity.discount_rate)) * option_quantity,
                option=obj_option_quantity.option
            )
            context["option_set"].append(temp)

        context['order'] = order
        context['kindergarten'] = order.kindergarten.name

        return context


class ContractPamphlet(LoginRequiredMixin, ListView):
    template_name = 'order_contract/contract/contract_pamphlet.html'

    def get_queryset(self):
        return FinalFittingSet.objects.get(order_contract_id=self.kwargs['order_id']).selectedcoupleset_set.all()

    def get_context_data(self, **kwargs):
        context = super(ContractPamphlet, self).get_context_data(**kwargs)
        order_id = self.kwargs['order_id']
        order = OrderContract.objects.get(id=order_id)

        context["formal_function"] = Function.objects.filter(default_formal=True)
        context["training_function"] = Function.objects.filter(default_training=True)
        context["order_id"] = order_id
        context["kindergarten"] = order.kindergarten.name
        return context


@csrf_exempt
def saveContractPdf(request):
    order_id = request.POST.get('order_id')
    pdf_file = request.POST.get('pdf_file').split(',')[1]
    order = OrderContract.objects.get(id=order_id)

    if order.contract_pdf.name == '':
        decode_img = base64.b64decode(pdf_file)
        image_filename = unicode("리틀스마트_공급계약서.pdf", 'utf-8')
        order.contract_pdf.save(image_filename, ContentFile(decode_img))
    else:
        pass

    return HttpResponse(json.dumps({'success': True}), content_type='application/json')


@csrf_exempt
def savePamphletPdf(request):
    order_id = request.POST.get('order_id')
    pdf_file = request.POST.get('pdf_file').split(',')[1]
    order = OrderContract.objects.get(id=order_id)

    if order.pamphlet_pdf.name == '':
        decode_img = base64.b64decode(pdf_file)
        image_filename = unicode("리틀스마트_선정디자인.pdf", 'utf-8')
        order.pamphlet_pdf.save(image_filename, ContentFile(decode_img))
    else :
        pass

    return HttpResponse(json.dumps({'success': True}), content_type='application/json')


class CompletionIndex(LoginRequiredMixin, TemplateView):
    template_name = 'order_contract/contract/completion_index.html'

    def get_context_data(self, **kwargs):
        context = super(CompletionIndex, self).get_context_data(**kwargs)

        order_id = self.kwargs['order_id']
        order = OrderContract.objects.get(id=order_id)

        if order.order_status < 5:
            raise Http404

        context['order_id'] = order_id
        return context


