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

from django.db import models

from kindergarten.models import Kindergarten
from simulation.models import Product, MainFabric, FinalFittingSet, Couple, SelectedCoupleSet, Option
from core.models import TimeStampedModel
# Create your models here.


def sign_file_name(instance, filename):
    return '/'.join(['sign_image', str(instance.id)+'_'+instance.kindergarten.name+'_'+str(instance.key), filename])

def pdf_file_name(instance, filename):
    return '/'.join(['pdf_file', str(instance.id)+'_'+instance.kindergarten.name+'_'+str(instance.key), filename])


class OrderContract(TimeStampedModel):
    order_status_all = (
        (1, u'little_smart'),
        (2, u'custom_design_offer'),
        (3, u'add_option'),
        (4, u'supply_price'),
        (5, u'contract_complete')
    )
    order_status = models.IntegerField(choices=order_status_all, default=1)
    kindergarten = models.ForeignKey(Kindergarten, on_delete=models.CASCADE)
    sign_image = models.ImageField('서명', upload_to=sign_file_name, null=True, blank=True)
    delivery_text = models.TextField('납품관련요청', null=True, blank=True)
    special_note = models.TextField('특이사항', null=True, blank=True)
    order_main_fabric_set = models.ManyToManyField(MainFabric, through='ProductQuantity')
    order_option_set = models.ManyToManyField(Option, through='OptionQuantity')
    key = models.PositiveIntegerField(null=True, blank=True)
    # key는 각 유치원의 몇번째 주문인지 자동저장해준다 admin site에선 자동저장안해주니 주의
    # final_fitting_set = models.OneToOneField(FinalFittingSet, null=True, blank=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=40, null=True, blank=True)
    estimate_pdf = models.FileField(upload_to=pdf_file_name, null=True, blank=True)
    contract_pdf = models.FileField(upload_to=pdf_file_name, null=True, blank=True)
    pamphlet_pdf = models.FileField(upload_to=pdf_file_name, null=True, blank=True)
    contract_date = models.DateField(null=True, blank=True)
    authentication_code = models.PositiveIntegerField(null=True, blank=True)

    class Meta:
        db_table = 'oc_order_contract'
        unique_together = ('key', 'kindergarten')

    def __unicode__(self):
        return unicode(self.kindergarten.name + '_' + str(self.key))

    def save(self, *args, **kwargs):
        if not self.id:
            key = cal_key(self.kindergarten)
            self.key = key
            # 주문 이름을 사용자한테 직접받게 수정
            # self.name = self.kindergarten.name + '_' + str(self.key)
        super(OrderContract, self).save(*args, **kwargs)

    def get_selected_couple(self, season, style):

        selected_couple_through_list = self.finalfittingset.selectedcoupleset_set.filter(
            couple__boy_fitting__fitting_category__season__icontains=season,
            couple__girl_fitting__fitting_category__season__icontains=season,
            couple__boy_fitting__fitting_category__style__icontains=style,
            couple__girl_fitting__fitting_category__style__icontains=style
        ).order_by('-id')

        try:
            selected_couple_through = selected_couple_through_list[0]
            selected_couple = selected_couple_through.couple
            # for delete_couple_through in selected_couple_through_list.exclude(id=selected_couple_through.id):
            #     delete_couple_through.delete()
        except:
            selected_couple = None

        return selected_couple


class ProductQuantity(models.Model):
    GENDER_CHOICES = (
        ('boy', u'남아'),
        ('girl', u'여아')
    )

    order_contract = models.ForeignKey(OrderContract)
    main_fabric = models.ForeignKey(MainFabric)
    quantity = models.IntegerField(default=0)
    supply_price = models.IntegerField(default=0)
    gender = models.CharField(max_length=10, choices=GENDER_CHOICES)

    class Meta:
        db_table = 'oc_product_quantity'

    def __unicode__(self):
        return unicode(self.main_fabric.name + '_' + str(self.quantity))


class OptionQuantity(models.Model):
    order_contract = models.ForeignKey(OrderContract)
    option = models.ForeignKey(Option)
    quantity = models.IntegerField(default=0)
    discount_rate = models.IntegerField(default=0)
    supply_price = models.IntegerField(default=0)

    class Meta:
        db_table = 'oc_option_quantity'

    def __unicode__(self):
        return unicode(self.option.name + '_' + self.quantity)


# 각 유치원의 마지막 주문을 확인하고 다음 숫자를 리턴
def cal_key(kindergarten):
    present_keys = OrderContract.objects.filter(kindergarten=kindergarten).order_by('-key').values_list('key',flat=True)
    if present_keys:
        return present_keys[0]+1
    else:
        return 1
