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

import base64

from django.core.files.base import ContentFile
from django.http import HttpResponse
from django.shortcuts import render_to_response

from django.views.generic import TemplateView, View
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from core.views import LoginRequiredMixin, OwnerRequiredMixin, OrderStatusMixin
from simulation.models import *
from order_contract.models import *
from order_contract.supply_price.views import *

import json


def getMaximumDiscountRate(style):
    max_rate = 0
    print style
    if style == 'formal':
        max_rate = 45
    elif style == 'training':
        max_rate = 50

    return max_rate

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

    def get_context_data(self, **kwargs):
        context = super(EstimateView, self).get_context_data(**kwargs)
        order_id = self.kwargs['order_id']
        context["order_id"] = order_id

        order_contract = OrderContract.objects.get(id=order_id)

        order_status = 4
        if order_contract.order_status < order_status:
            order_contract.order_status = order_status
            order_contract.save()

        context["final_set"] = []
        final_list = SelectedCoupleSet.objects.filter(final_uniform_set__order_contract=order_contract)\
            .order_by('couple__girl_fitting__fitting_category_id')
        for set in final_list:
            total_count = total_count=MainFabric.objects.filter(fitting__boy__selectedcoupleset__exact=set.id).count() \
                                      + MainFabric.objects.filter(fitting__girl__selectedcoupleset__exact=set.id).count()

            temp = dict(final_couple_id=set.id,
                        max_rate = getMaximumDiscountRate(set.couple.boy_fitting.fitting_category.style),
                        discount_rate = set.discount_rate,
                        acc_discount_rate = set.acc_discount_rate,
                        couple_id=set.couple.id, image=set.couple.front_image,
                        boy_product_set=MainFabric.objects.filter(fitting__boy__selectedcoupleset__exact=set.id)
                                            .order_by('product__product_type__id'),
                        girl_product_set=MainFabric.objects.filter(fitting__girl__selectedcoupleset__exact=set.id)
                                            .order_by('product__product_type__id'),
                        option_set = OptionQuantity.objects.filter(order_contract=order_contract),
                        loop_range=range(total_count, 10))
            context["final_set"].append(temp)

        context["kindergarten"] = order_contract.kindergarten.name
        return context


@method_decorator(csrf_exempt, name='dispatch')
class UpdateEstimateFinalView(LoginRequiredMixin, TemplateView):
    template_name = 'order_contract/estimate/final_list.html'

    def post(self, request, *args, **kwargs):
        order_id = self.request.POST.get('order_id')
        old_id = self.request.POST.get('oldId')
        new_id = self.request.POST.get('newId')
        final_function = self.request.POST.getlist('finalFunction[]')

        final_couple = SelectedCoupleSet.objects.get(final_uniform_set__order_contract_id=order_id, couple_id=old_id)

        if old_id != new_id:
            final_couple.couple_id = new_id
            final_couple.save()

            favorite_couple = SelectedFavoriteCoupleSet.objects.get(final_uniform_set__order_contract_id=order_id, couple_id=new_id)
            favorite_couple.couple_id = old_id
            favorite_couple.save()

        final_couple.function_set.set(Function.objects.filter(id__in=final_function))

        set = SelectedCoupleSet.objects.get(final_uniform_set__order_contract_id=order_id, couple_id=new_id)
        total_count = MainFabric.objects.filter(fitting__boy__selectedcoupleset__exact=set.id).count()\
                      + MainFabric.objects.filter(fitting__girl__selectedcoupleset__exact=set.id).count()
        update_couple = dict(final_couple_id=set.id,
                            max_rate=getMaximumDiscountRate(set.couple.boy_fitting.fitting_category.style),
                            discount_rate = set.discount_rate,
                             acc_discount_rate=set.acc_discount_rate,
                            couple_id=set.couple.id, image=set.couple.front_image,
                            boy_product_set=MainFabric.objects.filter(fitting__boy__selectedcoupleset__exact=set.id)
                                                .order_by('product__product_type__id'),
                            girl_product_set=MainFabric.objects.filter(fitting__girl__selectedcoupleset__exact=set.id)
                                                .order_by('product__product_type__id'),
                            loop_range=range(total_count, 10))

        return render_to_response(self.template_name, {'set': update_couple})

@method_decorator(csrf_exempt, name='dispatch')
class UpdateDiscountRateView(LoginRequiredMixin, View):
    def post(self, request, *args, **kwargs):
        order_id = self.request.POST.get('orderId')
        couple_id = self.request.POST.get('updateId')
        rate = self.request.POST.get('rate')
        acc_rate = self.request.POST.get('acc_rate')

        final_couple = SelectedCoupleSet.objects.get(final_uniform_set__order_contract=order_id, id=couple_id)
        final_couple.discount_rate = rate
        final_couple.acc_discount_rate = acc_rate
        final_couple.save()

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


@method_decorator(csrf_exempt, name='dispatch')
class UpdateOptionDiscountRateView(LoginRequiredMixin, View):
    def post(self, request, *args, **kwargs):
        order_id = self.request.POST.get('orderId')
        option_id = self.request.POST.get('updateId')
        rate = self.request.POST.get('rate')

        order = OrderContract.objects.get(id=order_id)
        option = Option.objects.get(id=option_id)

        option_quantity = order.optionquantity_set.get(option=option)
        option_quantity.discount_rate = rate
        supply_price = discountPrice(option.price ,rate)
        option_quantity.supply_price = supply_price
        option_quantity.save()

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

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

    if order.estimate_pdf.name != '' or order.estimate_pdf.name != None:
        order.estimate_pdf.delete()

    image_filename = unicode("리틀스마트_공급금액.pdf", 'utf-8')
    order.estimate_pdf.save(image_filename, ContentFile(decode_img))

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