# -*- coding: utf-8 -*-
# from django import forms

from django.forms import ModelForm
from .models import *
from company.models import CategoryProp
from django import forms
from django.utils.translation import gettext_lazy as _
from promotion.models import Material

class ProductForm(ModelForm):
    class Meta:
        model = Product
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
            'shelf_life': forms.HiddenInput(),
            # 2022-12-09
            'components': forms.HiddenInput(),
        }

    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(ProductForm, self).__init__(*args, **kwargs)        
        self.fields['series'].queryset = Series.objects.filter(company=self._user.company)
        self.fields['desc'].widget.attrs['class'] = "form-control"
        self.fields['desc'].widget.attrs['rows'] = "4"



class SeriesForm(ModelForm):
    class Meta:
        model = Series
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
            'icon': forms.HiddenInput(),
        }
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(SeriesForm, self).__init__(*args, **kwargs)


class PropForm(ModelForm):
    class Meta:
        model = ProductProp
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
        }

    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(PropForm, self).__init__(*args, **kwargs)        
        self.fields['categoryprop'].queryset = CategoryProp.objects.filter(category=self._user.company.category)        
        

    def clean_value(self):
        v = self.cleaned_data['value'].strip()
        if self.cleaned_data['categoryprop'].name == 'package':
            t = True
            if v:
                if not '*' in v:
                    t = False
                else:
                    for i in v.split('*'):
                        if not i.isdigit():
                            t=False
            if not t:
                raise forms.ValidationError(_('箱盒瓶之间请用*分隔：如1*6，1*9*2'), code='invalid value')
        elif self.cleaned_data['categoryprop'].type == 'n':
            vv=v
            if vv.count('.')==1:
                vv=vv.replace('.','')
            if not vv.isdigit():
                raise forms.ValidationError(_('此属性值应为数值型'), code='invalid value')
        return v


#2020-09-23
class PromatForm(ModelForm):
    class Meta:
        model=Material
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
        }



# 2024-06-24
class ExcemptionsForm(ModelForm):
    class Meta:
        model=Excemptions
        fields = '__all__'
        widgets = {           
            'products': forms.HiddenInput(),
            'company': forms.HiddenInput(),
        }
