# -*- coding: utf-8 -*-
# from django import forms
from django.forms import ModelForm
from .models import *
from django import forms
from company.models import *
from product.models import *

#2020-06-25
class AwardForm(ModelForm):
    class Meta:
        model = Award
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),            
            'user': forms.HiddenInput(),            
            'send_hb_after_get': forms.HiddenInput(),    
            'send_hb_after_hexiao': forms.HiddenInput(),              
        }

    #2020-06-26
    def clean_amount(self):
        amount = self.cleaned_data.get('amount')
        if self.instance.awardcat_id ==4 and not amount:
            raise forms.ValidationError("微信红包必填折合金额") 
        #if not self.instance.id:   
        #    cs=Company.objects.filter(name=name,hierarchy_id=self.instance.hierarchy_id,version=self.instance.version)
        #    if cs:
        #        c=cs[0]                
        #        s=name+" 已于"+c.tm.strftime('%Y-%m-%d %H:%M:%S')+"添加, 操作人:"+c.user.username
        #        raise forms.ValidationError(s)          
        return amount


   

class ActivitiesForm(ModelForm):
    class Meta:
        model = Activities
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),            
            'user': forms.HiddenInput(),
            'agents': forms.HiddenInput(), 
            'products': forms.HiddenInput(), 
            'agent_lvs': forms.HiddenInput(), 
            'adm_ids': forms.HiddenInput(), 
            'user_closed':forms.HiddenInput(),  
            'batch_ids':forms.HiddenInput(),    # 2022-12-22 这个字段今后删除，使用delivery_batches
            # 2022-12-22
            'delivery_batches':forms.HiddenInput(),
            'timebucket':forms.HiddenInput(),
        }    
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(ActivitiesForm, self).__init__(*args, **kwargs)
        self.fields['tm_start'].widget.attrs['class'] = "datetimepicker"
        self.fields['tm_end'].widget.attrs['class'] = "datetimepicker"    
        if self._user.id!=1:
            self.fields['wx_account'].queryset =WxOfficialAccounts.objects.filter(company_id=self._user.company_id)
                    

class ActivityAwardsForm(ModelForm):
    class Meta:
        model = ActivityAwards
        fields = '__all__'
        widgets = {                
            'activity': forms.HiddenInput(),
            'name': forms.HiddenInput(),
            'award': forms.HiddenInput(),
            'alternative': forms.HiddenInput(),  
            # 2022-12-22
            'adms': forms.HiddenInput(), 
            'terminal_rebate_points': forms.HiddenInput(), 
            'terminal_rebate_awards': forms.HiddenInput(), 
        }
ActivityAwardsFormset=forms.models.inlineformset_factory(Activities, ActivityAwards, ActivityAwardsForm, extra=0, can_delete=True)

class ActivityAgentAreasForm(ModelForm):
    class Meta:
        model=ActivityAgentAreas
        fields = ['award','saldivision_id','subdivision_id','qty','dt_fr','dt_to']


#2020-09-09
class ChannelPromotionsForm(ModelForm):
    class Meta:
        model = ChannelPromotions
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),            
            'user': forms.HiddenInput(),
            'agents': forms.HiddenInput(), 
            'products': forms.HiddenInput(),  
            'div_ids': forms.HiddenInput(),
            'subdiv_ids': forms.HiddenInput(),            
            'user_closed':forms.HiddenInput(),  
            'rebates':forms.HiddenInput(), 
        }    
    def __init__(self, *args, **kwargs):
        super(ChannelPromotionsForm, self).__init__(*args, **kwargs)
        self.fields['tm_start'].widget.attrs['class'] = "datetimepicker"
        self.fields['tm_end'].widget.attrs['class'] = "datetimepicker"
        self.fields['dt_delivery'].widget.attrs['class'] = "datepicker"
        
        
#2020-09-09
class ChannelRebateForm(ModelForm):
    class Meta:
        model = ChannelPromtionsRebate
        fields = '__all__'
        widgets = {                
            'promotion': forms.HiddenInput(),       
            'pvals': forms.HiddenInput(),
        }
    #2020-09-10
    def __init__(self, *args, **kwargs):
        super(ChannelRebateForm, self).__init__(*args, **kwargs)
        self.fields['level'].widget.attrs['class'] = "sel-lv"
        self.fields['pvals'].widget.attrs['class'] ="pvals"
        self.fields['level'].queryset = Level.objects.filter(id__in=[2, 4])
ChannelRebateFormset=forms.models.inlineformset_factory(ChannelPromotions,ChannelPromtionsRebate, ChannelRebateForm, extra=0, can_delete=True)


class MemberForm(ModelForm):
    class Meta:
        model = Member
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
            'consumer': forms.HiddenInput(),
            'user': forms.HiddenInput(),
        }

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

#步奖
class BuJiang_Form(ModelForm):
    class Meta:
        model=BuJiang_Labels
        fields=('label_code','award','is_active','remark')
    
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(BuJiang_Form, self).__init__(*args, **kwargs)
        self.fields['award'].queryset = Award.objects.filter(
            company_id=self._user.company.id)
            

#步奖
class LOTTERY_SINGLE_Form(ModelForm):
    class Meta:
        model=LotterySeeds
        fields=('activity','award','label_code','label_pkg','label_id','remark','award2')
    
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(LOTTERY_SINGLE_Form, self).__init__(*args, **kwargs)
        self.fields['activity'].queryset = Activities.objects.filter(
            company_id=self._user.company.id)
            

class Lottery_Winner_Form(ModelForm):
    class Meta:
        model=LotteryWinnerSeeds
        fields=('activity','award','phone','remark')
    
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(Lottery_Winner_Form, self).__init__(*args, **kwargs)
        self.fields['activity'].queryset = Activities.objects.filter(
            company_id=self._user.company.id)

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

class RebateInvoiceForm(ModelForm):
    class Meta:
        model = RebateInvoice
        exclude = ['dt','tm']
        widgets = {
            'company': forms.HiddenInput(),
            'agent': forms.HiddenInput(),
            'salesdivision': forms.HiddenInput(),
            'user': forms.HiddenInput(),
        }

    def __init__(self, *args, **kwargs):       
        super(RebateInvoiceForm, self).__init__(*args, **kwargs)       
        self.fields['dt_billing'].widget.attrs['class'] = "form-control datepicker"
        

class RbInvAttachForm(ModelForm):
    class Meta:
        model=RebateInvoiceAttach
        fields='__all__'
    #def __init__(self, *args, **kwargs):       
    #    super(RbInvAttachForm, self).__init__(*args, **kwargs)       
    #    self.fields['img'].widget.attrs['onchange'] = "verificationPicFile(this)"


RbInvAttachFormset=forms.models.inlineformset_factory(RebateInvoice,RebateInvoiceAttach, RbInvAttachForm, extra=1, can_delete=True)


class RbClosingForm(ModelForm):
    class Meta:
        model=RebateClosing
        fields='__all__'
        widgets = {
            'company': forms.HiddenInput(),            
            'user': forms.HiddenInput(),
            'application_checked_user':forms.HiddenInput(),
            'payable_checked_user':forms.HiddenInput(),
            'payable_checked_user':forms.HiddenInput(),
            #2021-06-30            
            'terms':forms.HiddenInput(),
        }

    def __init__(self, *args, **kwargs):       
        super(RbClosingForm, self).__init__(*args, **kwargs)   
        self.fields['dt_fr'].widget.attrs['class'] = "form-control datepicker"
        self.fields['dt_fr'].widget.attrs['placeholder'] = "开始日期"
        self.fields['dt_to'].widget.attrs['class'] = "form-control datepicker"
        self.fields['dt_to'].widget.attrs['placeholder'] = "结束日期"
        
        self.fields['lv1_dt_fr'].widget.attrs['class'] = "form-control datepicker"
        self.fields['lv1_dt_fr'].widget.attrs['placeholder'] = "开始日期"
        self.fields['lv1_dt_to'].widget.attrs['class'] = "form-control datepicker"
        self.fields['lv1_dt_to'].widget.attrs['placeholder'] = "结束日期"
        self.fields['remark'].widget.attrs['class'] = "form-control"
        self.fields['name'].widget.attrs['class'] = "form-control"
        self.fields['period'].widget.attrs['class'] = "form-control"



    def clean(self):
        cleaned_data = super(RbClosingForm, self).clean()
        if not self.instance.id:
            cur=connection.cursor()
            #二级商
            dt1=cleaned_data['dt_fr']
            dt2=cleaned_data['dt_to']   
            cur.execute("select min(dt_fr),max(dt_to) from sales_rebateclosing where company_id="+str(self.instance.company_id))
            r=cur.fetchone()
            if r:
                if r[0]:
                    if max(dt1,r[0])<min(dt2,r[1]):                      
                        self._errors["dt_fr"] = self.error_class(['二级商开始和结束日期与已有会计期日期有重叠！'])   
            #平台商
            lv1_dt1=cleaned_data['lv1_dt_fr']
            lv1_dt2=cleaned_data['lv1_dt_to']   
            cur.execute("select min(lv1_dt_fr),max(lv1_dt_to) from sales_rebateclosing where company_id="+str(self.instance.company_id))
            r=cur.fetchone()
            if r:
                if r[0]:
                    if max(lv1_dt1,r[0])<min(lv1_dt2,r[1]):                      
                        self._errors["lv1_dt_fr"] = self.error_class(['平台商开始和结束日期与已有会计期日期有重叠！'])   
                    
            cur.close()       
        return cleaned_data

class KangNian_InventoryManipulationForm(ModelForm):
    class Meta:
        model = KangNian_InventoryManipulation
        exclude = ['dt','tm']
        widgets = {
            'tm':forms.HiddenInput(),
            'update_tm':forms.HiddenInput()
        }

    def __init__(self, *args, **kwargs):     
        #self._user = kwargs.pop('user')  
        super(KangNian_InventoryManipulationForm, self).__init__(*args, **kwargs)       
        self.fields['storehouse'].choices = Storehouse.objects.filter(company_id=31917).values_list('id','name') 
        self.fields['agent'].choices = Company.objects.filter(ancestor_id=31917,is_terminal=True).values_list('id','name')
        self.fields['product'].choices = Product.objects.filter(company_id=31917).values_list('id','name')

class KangNian_StorehouseManagementDeatilForm(ModelForm):
    class Meta:
        model = KangNian_StorehouseInventoryManipulation
        exclude = ['dt','agent','tm']
        widgets = {
            'tm':forms.HiddenInput()
        }

    def __init__(self, *args, **kwargs):       
        super(KangNian_StorehouseManagementDeatilForm, self).__init__(*args, **kwargs)      
        self.fields['storehouse'].choices = Storehouse.objects.filter(company_id=31917).values_list('id','name') 
        self.fields['product'].choices = Product.objects.filter(company_id=31917).values_list('id','name')
        

class MarketActCategory_Form(ModelForm):
    class Meta:
        model=Market_ActCategory
        fields=('name','remark') 
        

class ActionCategory_Form(ModelForm):
    class Meta:
        model=Action_Category
        fields=('name','remark') 


class VoidLabelForm(ModelForm):
    class Meta:
        model = VoidLabel
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
            'user': forms.HiddenInput(),
        }


# 2023-05-04
class AccumulationForm(ModelForm):
    class Meta:
        model=ChannelPromotionAccumulations
        #fields=('company','promotion','awardcategory','label_pkg','amount','remark')


        fields='__all__' 
        widgets = {
            'company': forms.HiddenInput(),
            #'agent': forms.HiddenInput(),
            #'salesdivision': forms.HiddenInput(),
            #'user': forms.HiddenInput(),
        }

    #def __init__(self, *args, **kwargs):
    #    super(AccumulationForm, self).__init__(*args, **kwargs)
    #    exclude = ['dt','tm']
    #    widgets = {
    #        'company':forms.HiddenInput(),            
    #    }
AccumulattionFormset=forms.models.inlineformset_factory(ChannelPromotions,ChannelPromotionAccumulations, AccumulationForm, extra=0, can_delete=True)




# 2023-05-25
class CustomizeRebateForm(ModelForm):
    class Meta:
        model=CustomizeRebate
        fields='__all__'

    def __init__(self, *args, **kwargs):       
        super(CustomizeRebateForm, self).__init__(*args, **kwargs)       
        self.fields['trigger_lv'].widget.attrs['class'] = "form-control"
        self.fields['label_pkg'].widget.attrs['class'] = "form-control"
        self.fields['scan_type'].widget.attrs['class'] = "form-control"
        #self.fields['target_lv'].widget.attrs['class'] = "form-control"
        #self.fields['amount'].widget.attrs['class'] = "form-control"
        #self.fields['amt_award'].widget.attrs['class'] = "form-control"

CustomizeRebateFormset=forms.models.inlineformset_factory(ChannelPromotions,CustomizeRebate,CustomizeRebateForm, extra=0, can_delete=True)

class Activity_Lottery_Plan_Form(ModelForm):
    class Meta:
        model = Activity_Lottery_Plan
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
        }
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(Activity_Lottery_Plan_Form, self).__init__(*args, **kwargs)
        self.fields['tm_start'].widget.attrs['class'] = "datetimepicker"
        self.fields['tm_end'].widget.attrs['class'] = "datetimepicker" 
        self.fields['activity'].queryset = Activities.objects.filter(company_id=self._user.company.id)

class Activity_Person_Lottery_Plan_Form(ModelForm):
    class Meta:
        model = Activity_Person_Lottery_Plan
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
            'win_scan_num': forms.HiddenInput(),
        }
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(Activity_Person_Lottery_Plan_Form, self).__init__(*args, **kwargs)
        self.fields['tm_start'].widget.attrs['class'] = "datetimepicker"
        self.fields['tm_end'].widget.attrs['class'] = "datetimepicker" 
        self.fields['activity'].queryset = Activities.objects.filter(company_id=self._user.company.id)




