# -*- coding: utf-8 -*-
from django import forms
from django.forms import ModelForm
from .models import *
from product.models import Product,Series
from django.utils.translation import gettext_lazy as _


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



#2021-03-07
class DepartmentForm(ModelForm):
    class Meta:
        model = Department
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),       
            'parent':forms.HiddenInput(),           
            'sub_division':forms.HiddenInput(),
            'level':forms.HiddenInput(),
        }
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(DepartmentForm, self).__init__(*args, **kwargs)
        self.fields['division'].queryset = SalesDivision.objects.filter(company_id=self._user.ancestor_id)
        self.fields['name'].widget.attrs['class'] = "form-control"
        self.fields['sn'].widget.attrs['class'] = "form-control"
        self.fields['division'].widget.attrs['class'] = "form-control"
        self.fields['subsidiary'].widget.attrs['class'] = "form-control"

class PositionForm(ModelForm):
    class Meta:
        model=Position
        fields='__all__'
        widgets={
            'company': forms.HiddenInput(),       
            'group_id':forms.HiddenInput(),    
            'is_delete':forms.HiddenInput(), 
        }
    def __init__(self, *args, **kwargs):        
        super(PositionForm, self).__init__(*args, **kwargs)
        self.fields['remark'].widget.attrs['class'] = "form-control"
        self.fields['name'].widget.attrs['class'] = "form-control"
        

class StaffForm(ModelForm):
    class Meta:
        model=Staff
        fields='__all__'
        widgets={
            'company': forms.HiddenInput(),       
            'user':forms.HiddenInput(),
            'department':forms.HiddenInput(),
        }
    def __init__(self, *args, **kwargs):   
        self._user = kwargs.pop('user')
        super(StaffForm, self).__init__(*args, **kwargs)
        self.fields['remark'].widget.attrs['class'] = "form-control"
        self.fields['name'].widget.attrs['class'] = "form-control"
        self.fields['cellphone'].widget.attrs['class'] = "form-control"
        self.fields['position'].widget.attrs['class'] = "form-control"
        self.fields['is_department_head'].widget.attrs['class'] = "form-control"
        self.fields['position'].queryset = Position.objects.filter(company_id=self._user.ancestor_id).order_by('name')
       


class BrandRecommenderForm(ModelForm):
    class Meta:
        model = BrandRecommender
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput()
            
        }
    def __init__(self, *args, **kwargs):
        super(BrandRecommenderForm, self).__init__(*args, **kwargs)
        self.fields['user'].choices = User.objects.filter(phone=self.instance.cellphone,ancestor_id=20445).values_list('id','last_name')
        self.fields['agent'].choices = Company.objects.filter(ancestor_id=20445).values_list('id','name')


class PlantForm(ModelForm):
    class Meta:
        model = PrdPlant
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
        }
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(PlantForm, self).__init__(*args, **kwargs)       
#2022-01-04
class PrdShopForm(ModelForm):
    class Meta:
        model = PrdWorkshop
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
        }
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(PrdShopForm, self).__init__(*args, **kwargs)     
        self.fields['prd_plant'].queryset = PrdPlant.objects.filter(company_id=self._user.ancestor_id).order_by('name')
class PrdLineForm(ModelForm):
    class Meta:
        model = PrdLine
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
        }
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(PrdLineForm, self).__init__(*args, **kwargs)   
        self.fields['prd_plant'].queryset = PrdPlant.objects.filter(company_id=self._user.ancestor_id).order_by('name')
        self.fields['prd_workshop'].queryset = PrdWorkshop.objects.filter(company_id=self._user.ancestor_id).order_by('name')
class PrdTeamForm(ModelForm):
    class Meta:
        model = PrdTeam
        fields = '__all__'
        widgets = {
            'company': forms.HiddenInput(),
        }
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(PrdTeamForm, self).__init__(*args, **kwargs)   
        self.fields['prd_plant'].queryset = PrdPlant.objects.filter(company_id=self._user.ancestor_id).order_by('name')
        self.fields['prd_workshop'].queryset = PrdWorkshop.objects.filter(company_id=self._user.ancestor_id).order_by('name')
        self.fields['prd_line'].queryset = PrdLine.objects.filter(company_id=self._user.ancestor_id).order_by('name')
        





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

    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(SalesDivisionForm, self).__init__(*args, **kwargs)       
        self.fields['manager'].queryset = User.objects.filter(company=self._user.company)


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

    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')        
        super(SalSubDivisionForm, self).__init__(*args, **kwargs)
        self.fields['manager'].queryset = User.objects.filter(company=self._user.company)
        #2020-04-10
        self.fields['division'].queryset=SalesDivision.objects.filter(company_id=self._user.company_id)



class AgentForm(ModelForm):
    class Meta:
        model = Company
        fields = '__all__'
        widgets = {
            'parent': forms.HiddenInput(),
            'category': forms.HiddenInput(),
            'is_active': forms.HiddenInput(),   
            'lng_lat': forms.HiddenInput(),  
            #2020-09-14
            'province_gis_id': forms.Select(),   
            'city_gis_id': forms.Select(),    
            'county_gis_id': forms.Select(),   
            #2020-09-29
            'products':forms.HiddenInput(),
            'adm_ids':forms.HiddenInput(),
            #2021-07-23
            'franchise_series':forms.HiddenInput(),
            'franchise_status':forms.HiddenInput(),
            #2021-09-25
            'parents':forms.HiddenInput(),
            
            #2021-10-19 一些公司要求自己定义经销商层级
            'level':forms.HiddenInput(), 
            
            'channel_level_ids':forms.HiddenInput(), 
            'series_more':forms.HiddenInput(), 
        }          

    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(AgentForm, self).__init__(*args, **kwargs)
        #self.fields['level'].queryset = Level.objects.filter(sn__gt=self._user.company.level.sn)  

        #2020-01-05
        self.fields['division'].queryset=SalesDivision.objects.filter(company_id=self._user.company_id)
        #self.fields['parent'].queryset=Company.objects.filter(ancestor_id=self._user.company.ancestor_id)
        #2020-04-10
        self.fields['sub_division'].queryset=SubSalDivision.objects.filter(company_id=self._user.company_id)
        #20211-10-13
        self.fields['qry_time'].widget.attrs['class'] = "datetimepicker"
        
        self.fields['channel'].queryset=Channel.objects.filter(ancestor_id=self._user.ancestor_id) 
    
    #2019-11-15
    def clean_name(self):
        name = self.cleaned_data.get('name')
        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 name



#class UserForm(ModelForm):  
#    class Meta:
#        model = User
#        fields = ['password','username','phone','company','last_name']
#        widgets = {            
#            'password':forms.PasswordInput(),
#            'company':forms.HiddenInput(),
#        }   

class UserForm(ModelForm):  
    class Meta:
        model = User
        fields = ['username','phone','company','last_name']
        widgets = { 
            'company':forms.HiddenInput(),
            'product_series':forms.HiddenInput(), 
        }   


#2020-12-17
class UserCreateForm(ModelForm):  
    class Meta:
        model = User
        fields = ['password','username','phone','company','last_name','product_series','is_active']
        widgets = {            
            'password':forms.PasswordInput(),
            'company':forms.HiddenInput(),
            'product_series':forms.HiddenInput(), 

            # 2024-05-31
            'is_active':forms.HiddenInput(),
        } 


class UserChangeForm(ModelForm):  
    class Meta:
        model = User
        fields = ['username','phone','company','last_name','product_series','is_active']
        widgets = {   
            'company':forms.HiddenInput(),
            'product_series':forms.HiddenInput(), 
            
            # 2024-05-31
            'is_active':forms.HiddenInput(),
        } 







class CompanyCfgForm(ModelForm):  
    class Meta:
        model = CompanyCfg
        fields = '__all__'        
    def __init__(self, *args, **kwargs):        
        super(CompanyCfgForm, self).__init__(*args, **kwargs)
        self.fields['company'].queryset = Company.objects.filter(level_id=1) 



class AgentOrderBatchForm(ModelForm):
    class Meta:
        model=AgentOrderBatch
        fields = '__all__'
        widgets = {
            'vendor': forms.HiddenInput(),
            'company': forms.HiddenInput(),
            'user': forms.HiddenInput(),
            'ancestor_id': forms.HiddenInput(),            
        } 
    def __init__(self, *args, **kwargs):
        super(AgentOrderBatchForm, self).__init__(*args, **kwargs)
        self.fields['code'].widget.attrs['class'] = "form-control"
        self.fields['remark'].widget.attrs['class'] = "form-control"
        self.fields['dt_expect'].widget.attrs['class'] = "form-control datepicker"   
        


class AgentOrderDetailsForm(ModelForm):
    class Meta:
        model=AgentOrderDetails
        fields = '__all__'
        widgets = {
            'vendor': forms.HiddenInput(),
            'company': forms.HiddenInput(),
            'product': forms.HiddenInput(),
            'ancestor_id': forms.HiddenInput(),            
        }   
AgentOrderDetailsFormset=forms.models.inlineformset_factory(AgentOrderBatch,AgentOrderDetails,AgentOrderDetailsForm,extra=0,can_delete=True)


class StaffSaldivForm(ModelForm):
    class Meta:
        model=StaffSaldiv
        #fields=('saldiv_ids','subsaldiv_ids','agent_ids')
        fields='__all__'
        widgets = {
            'company': forms.HiddenInput(),
            'user': forms.HiddenInput(),
            'group_ids':forms.HiddenInput(),
            'saldiv_ids': forms.HiddenInput(),
            'subsaldiv_ids': forms.HiddenInput(),
            'agent_ids': forms.HiddenInput(),
        }


class CGroupForm(ModelForm):
    class Meta:
        model=CGroup
        fields='__all__'
        widgets={
            'company':forms.HiddenInput(),    
            'group':forms.HiddenInput(),
        }
        
    def __init__(self, *args, **kwargs):
        super(CGroupForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs['class'] = "form-control"
        self.fields['remark'].widget.attrs['class'] = "form-control"
       

        
#Jonathan
#2020-12-15
class WhiteDomainForm(ModelForm):
    class Meta:
        model=White_Domain
        fields = ['domain','domain_type','is_active']


class Third_Party_Company_Form(ModelForm):
    class Meta:
        model=Third_Party_Company
        fields = ['name','is_active']

        
class Label_Bind_Rule_Form(ModelForm):
    class Meta:
        model=Label_Bind_Rule
        fields = ['level_1','level_2','level_3','is_active']


class Benefit_Form(ModelForm):
    class Meta:
        model=Benefit
        fields = ['name','is_face_to_agent','is_face_to_terminal','is_face_to_business','remark','is_active']


class Benefit_Rule_Form(ModelForm):
    class Meta:
        model=Benefit_Rule
        fields = ['name','rule_category','discount','remark']

class Brands_Form(ModelForm):
    class Meta:
        model=Brands
        fields = ['third_party_company','name','level_up_method','is_active','remark','settle_method']

    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(Brands_Form, self).__init__(*args, **kwargs)
        self.fields['third_party_company'].queryset = Third_Party_Company.objects.filter(company_id=self._user.company.id)


class Brands_Level_Form(ModelForm):
    class Meta:
        model=Brands_Level
        fields = ['name','level','photo','need_money','need_num','remark','benefit']

class Sale_Task_Form(ModelForm):
    class Meta:
        model=Sale_Task
        fields = ['name','start_tm','end_tm','remark','is_active']

class Sale_Task_Allocate_Form(ModelForm):
    class Meta:
        model=Sale_Task_Allocate
        fields = ['agent','sale_money','remark','is_active']

class Page_Banners_Form(ModelForm):
    class Meta:
        model=Page_Banners
        fields = ['image','sort_id','is_active']

class News_Form(ModelForm):
    class Meta:
        model=News
        fields = ['news_from','subtitle','desc','poster','content','is_active','remark','pub_date']




#2021-02-24
class BulletinboardForm(ModelForm):
    class Meta:
        model=BulletinBoard
        fields = '__all__'
        widgets = {
            'user': forms.HiddenInput(),
            'company': forms.HiddenInput(),    
            'salesdivisions': forms.HiddenInput(),             
        }  

class BulletinBoardAttachForm(ModelForm):
    class Meta:
        model=BulletinBoardAttach
        fields = '__all__'
        widgets = {      
            'bulletinboard': forms.HiddenInput(),             
        }   
BulletinBoardAttachFormset=forms.models.inlineformset_factory(BulletinBoard,BulletinBoardAttach,BulletinBoardAttachForm,extra=1,can_delete=True)



#2021-07-22
class OutletForm(ModelForm):
    class Meta:
        model=Outlet
        fields='__all__'
        widgets={
            'ancestor_id':forms.HiddenInput(),
            'company':forms.HiddenInput(),    
            'province_gis':forms.HiddenInput(), 
            'city_gis':forms.HiddenInput(), 
            'county_gis':forms.HiddenInput(), 
            'lng_lat':forms.HiddenInput(),             
        } 
    def __init__(self, *args, **kwargs):
        super(OutletForm, self).__init__(*args, **kwargs)
        self.fields['province_gis'].widget.attrs['class'] = "province_gis"
        self.fields['city_gis'].widget.attrs['class'] = "city_gis"
        self.fields['county_gis'].widget.attrs['class'] = "county_gis"
        self.fields['lng_lat'].widget.attrs['class'] = "lng_lat"
        self.fields['name'].widget.attrs['class'] = "name"
        self.fields['address'].widget.attrs['class'] = "address"
        self.fields['series'].widget.attrs['class'] = "series"
        self.fields['qry_time'].widget.attrs['class'] = "datetimepicker"
OutletFormset=forms.models.inlineformset_factory(Company,Outlet,OutletForm,extra=1,can_delete=True)



class Company_Channel_Form(ModelForm):
    class Meta:
        model=Channel
        fields = ['name','remark']


class Company_Channel_Level_Form(ModelForm):
    class Meta:
        model=Channel_Level
        fields = ['name','series','level','remark']
        
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(Company_Channel_Level_Form, self).__init__(*args, **kwargs)        
        self.fields['series'].queryset = Series.objects.filter(company=self._user.company)



class Company_UploadFiles_Form(ModelForm):
    class Meta:
        model=UploadFiles
        fields = ['media_type','category','url','remark']
        
    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(Company_UploadFiles_Form, self).__init__(*args, **kwargs)    
        self.fields['category'].queryset = FileCategory.objects.all()

class BonusPoints_Form(ModelForm):
    class Meta:
        model=BonusPoints
        fields = ['points','remark']

    def __init__(self, *args, **kwargs):
        self._user = kwargs.pop('user')
        super(BonusPoints_Form, self).__init__(*args, **kwargs)
        self.fields['points'].queryset = BonusPoints.objects.filter(company_id=self._user.company.id)


class InspectionReport_Form(ModelForm):
    class Meta:
        model=InspectionReport
        fields = ['title','contents','remark','is_active','dt']


class WorkCard_Form(ModelForm):
    class Meta:
        model=WorkCard
        fields=['org_name','group_name','level_name','company_name','name','sex','photo','id_card_code','birthday','tel','code','position_name']
