# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# import sys
from django.db import models
from django.utils.translation import gettext_lazy as _
from inventory.models import Storehouse
from django.db import connection

# Create your models here.
from django.contrib.auth.models import AbstractUser
import pyodbc
from django.conf import settings
import os
from django.contrib.postgres.fields import ArrayField

# from django.db.models.signals import post_save, post_delete
# from django.dispatch import receiver
# from django.contrib.auth.validators import UnicodeUsernameValidator



# 2022-11-16
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation


MEDIA_ROOT=settings.MEDIA_ROOT

def company_upload_register(instance, filename):
   return  '/'.join([MEDIA_ROOT,instance.ancestor.name,'register', str(instance.parent.id),filename])


def company_upload_logo(instance, filename):
   return  '/'.join([MEDIA_ROOT, 'logo', filename])

def company_upload_banner(instance, filename):
   return  '/'.join([MEDIA_ROOT, 'image',instance.hierarchy.name, instance.name, 'banner', filename])

def company_upload_bg(instance, filename):
   return  '/'.join([MEDIA_ROOT, 'image',instance.hierarchy.name, instance.name, 'bg', filename])

def company_upload_id(instance, filename):
   return  '/'.join([MEDIA_ROOT, 'image',instance.hierarchy.name, instance.name, 'id', filename])


def company_upload_brand(instance,filename):
    return os.path.join(instance.company.name, 'level', filename)
    
def company_upload_page_banners(instance,filename):
    return os.path.join(instance.company.name, 'page_banners', filename)

def company_upload_page_poster(instance,filename):
    return os.path.join(instance.company.name, 'poster', filename)

class Category(models.Model):
    name = models.CharField(_('分类名称'), max_length=50, unique=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)
    tm = models.DateTimeField(_('生成时间'), auto_now_add=True)

    class Meta:
        verbose_name = _('公司类别')
        verbose_name_plural = _('公司类别')

    def __str__(self):
        return self.name




#2021-07-15
class Color(models.Model):
    en_name=models.CharField(_('英文名称'),max_length=20,blank=True,null=True)
    name=models.CharField(_('颜色名称'),max_length=20)
    code=models.CharField(_('颜色代码'),max_length=20)

    class Meta:
        verbose_name = _('颜色代码')
        verbose_name_plural = _('颜色代码')

    def __str__(self):
        return self.name




class FranchiseStatus(models.Model):
    company=models.ForeignKey('company.Company',verbose_name=_('所属企业'),related_name="franchisestatus_company",on_delete=models.CASCADE)
    category=models.SmallIntegerField(_('状态类别'),choices=(
	(0,_('未加盟')),(1,_('已加盟'))
    ))
    name=models.CharField(_('状态名称'),max_length=50)
    color=models.ForeignKey(Color,verbose_name=_('图例颜色'),blank=True,null=True,on_delete=models.CASCADE)
    remark=models.CharField(_('备注说明'),max_length=50,blank=True,null=True)
    is_delete = models.BooleanField(_('是否已删除'), default=False)

    class Meta:
        verbose_name = _('加盟商状态')
        verbose_name_plural = _('加盟商状态')

    def __str__(self):
        return self.name


class OutletStatus(models.Model):
    company=models.ForeignKey('company.Company',verbose_name=_('所属企业'),related_name="outletstatus_company",on_delete=models.CASCADE)    
    name=models.CharField(_('状态名称'),max_length=50)
    color=models.ForeignKey(Color,verbose_name=_('图例颜色'),blank=True,null=True,on_delete=models.CASCADE)
    remark=models.CharField(_('备注说明'),max_length=50,blank=True,null=True)

    class Meta:
        verbose_name = _('加盟商门店状态')
        verbose_name_plural = _('加盟商门店状态')

    def __str__(self):
        return self.name



#2020-04-23
class ErrCategory(models.Model):    
    name=models.CharField(_('类别说明'),max_length=100)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)
    tm = models.DateTimeField(_('生成时间'), auto_now_add=True)
    class Meta:
        verbose_name = _('错误类别')
        verbose_name_plural = _('错误类别')

    def __str__(self):
        return self.name


#2020-04-23
class ErrCode(models.Model):
    category=models.ForeignKey(ErrCategory, verbose_name=_('错误类别'),  on_delete=models.CASCADE)
    code=models.IntegerField(_('错误代码'),unique=True)
    name=models.CharField(_('错误说明'),max_length=100)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)
    tm = models.DateTimeField(_('生成时间'), auto_now_add=True)
    class Meta:
        verbose_name = _('错误代码')
        verbose_name_plural = _('错误代码')

    def __str__(self):
        return self.name
    


class Level(models.Model):
    name = models.CharField(_('层级名称'), max_length=50, unique=True)
    category = models.ForeignKey(Category, verbose_name=_('公司类别'), default=1, on_delete=models.CASCADE)
    sn = models.SmallIntegerField(_('层级序号'), blank=True, null=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = _('营销层级')
        verbose_name_plural = _('营销层级')
        ordering = ['sn']

    def __str__(self):
        return self.name


#2020-11-24
class Status(models.Model):
    name=models.CharField(_('状态名'),max_length=20)
    functions=models.CharField(_('功能操作'),max_length=50)
    remark=models.CharField(_('备注'),max_length=100,blank=True,null=True)

    class Meta:
        verbose_name = _('客户状态')
        verbose_name_plural = _('客户状态')




class Channel(models.Model):
    ancestor = models.ForeignKey('company.Company', verbose_name=_('企业名称'),
            on_delete=models.CASCADE,related_name='channel_company', default=1)
    name = models.CharField(_('渠道名称'), max_length=50, blank=True, null=True)
    remark = models.CharField(_('备注'), max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = _('客户渠道')
        verbose_name_plural = _('客户渠道')
    
    def __str__(self):
        return self.name


class Channel_Level(models.Model):
    ancestor = models.ForeignKey('company.Company', verbose_name=_('企业名称'),
            on_delete=models.CASCADE,related_name='channellevel_company')
    series=models.ForeignKey('product.Series',verbose_name=_('授权品牌/系列'),on_delete=models.CASCADE,blank=True,null=True)
    name = models.CharField(_('等级名称'), max_length=50)
    level = models.SmallIntegerField(_('等级'), blank=True, null=True)
    description = models.CharField(_('等级描述'), max_length=50)
    remark = models.CharField(_('备注'), max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = _('客户渠道等级')
        verbose_name_plural = _('客户渠道等级')
    
    def __str__(self):
        return self.name

class Company(models.Model):
    category = models.ForeignKey(Category, verbose_name=_('公司类别'), on_delete=models.CASCADE)
    level = models.ForeignKey(Level, verbose_name=_('层级'), on_delete=models.CASCADE, blank=True, null=True)
    parent = models.ForeignKey('self', verbose_name=_('父级'), on_delete=models.CASCADE, blank=True, null=True)
    hierarchy = models.ForeignKey('self', verbose_name=_('体系'), on_delete=models.CASCADE, blank=True, null=True, related_name='company_hierarchy')
    wx_account=models.ForeignKey('sales.WxOfficialAccounts', on_delete=models.CASCADE, verbose_name=_('官方微信公众号'),blank=True,null=True)
    parent = models.ForeignKey('self', verbose_name=_('父级'), on_delete=models.CASCADE, blank=True, null=True)
    status=models.SmallIntegerField(_('客户状态'),default=1,choices=((1,'正常'),(2,'锁定'),(3,'关闭')),blank=True,null=True)
    ancestor_id=models.IntegerField(_('族系'),blank=True,null=True, db_index=True)
    name = models.CharField(_('公司名称'), max_length=50, db_index=True)
    user = models.ForeignKey('company.User', verbose_name=_('操作人'), related_name='who_added', default=1, on_delete=models.CASCADE, blank=True, null=True)
    division = models.ForeignKey('company.SalesDivision', verbose_name=_('营销大区'), related_name='company_division', on_delete=models.CASCADE, blank=True, null=True)
    sub_division = models.ForeignKey('company.SubSalDivision', verbose_name=_('营销分区'), related_name='company_division', on_delete=models.CASCADE, blank=True, null=True)
    legacy_id = models.IntegerField(_('SqlSrvID'), null=True, blank=True)
    version = models.SmallIntegerField(_('体系版本'),default=0,blank=True,null=True)
    lar = models.CharField(_('法人代表'), blank=True, null=True, max_length=20)
    
    contacts=models.CharField(_('联系人'),max_length=50,blank=True,null=True)  
    title=models.CharField(_('职位'),max_length=50,blank=True,null=True)
    qry_teacher=models.CharField(_('查询老师'),max_length=20,blank=True,null=True)
    qry_time=models.DateTimeField(_('首查时间'),blank=True,null=True)

    ctyid = models.IntegerField(_('CTID'), blank=True, null=True)
    external_code = models.CharField(_('外部编码'), max_length=30, blank=True, null=True, help_text=_('企业自有编码，如SAP编码'),db_index=True)    
    external_category=models.CharField(_('公司类别外部编码'),max_length=20,blank=True,null=True)
    log_code = models.CharField(_('物流编码'), max_length=30, blank=True, null=True, help_text=_('企业原有物流码'))
    external_id = models.IntegerField(_('外部ID'), blank=True, null=True, unique=True)
    is_active = models.BooleanField(_('是否已激活'), default=True)
    is_delete = models.BooleanField(_('是否已删除'), default=False)
    is_terminal =  models.BooleanField(_('是否为终端店'),default=False,blank=True,null=True)
    is_franchised=models.BooleanField(_('是否为专卖店'),default=False)
    is_legacy = models.BooleanField(_('使用SqlSrvID'), default=False)
    is_microboss = models.BooleanField(_('是否是微商'), default=False)
    is_expense_account= models.BooleanField(_('是否为公司费用帐户'), default=False)
    has_logcode = models.BooleanField(_('是否已有物流码'), default=False)
    has_external_code = models.BooleanField(_('使用外部编码(SAP)'), default=False)
    has_plant = models.BooleanField(_('分工厂/厂区'), default=False)
    has_workshop = models.BooleanField(_('分车间'), default=False)
    has_saldiv_mgt = models.BooleanField(_('是否有站区管理'),default=False)
    is_manufacturing = models.BooleanField(_('是否为生产性企业'), default=False)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    tm_register = models.DateTimeField(_('注册时间'), blank=True, null=True)
    inv_mgt = models.BooleanField(_('库存管理'), default=False, blank=True, null=True)
    remark = models.CharField(_('备注说明'), max_length=100, null=True, blank=True)
    idnumber = models.CharField(_('身份证号码'), max_length=30, blank=True, null=True)    
    province = models.CharField(_('省份'), max_length=30, blank=True, null=True)
    province_gis_id = models.IntegerField(_('GIS省份ID'), blank=True, null=True)
    city = models.CharField(_('城市'), max_length=30, blank=True, null=True)
    city_gis_id = models.IntegerField(_('GIS城市ID'), blank=True, null=True)
    county = models.CharField(_('县/区'), max_length=30, blank=True, null=True)
    county_gis_id = models.IntegerField(_('GIS县区ID'), blank=True, null=True)
    address = models.CharField(_('详细地址'), max_length=100, blank=True, null=True)
    license_number=models.CharField(_('营业执照编号'),max_length=50,blank=True,null=True)   
    cell_phone = models.CharField(_('手机号码'), max_length=20, blank=True, null=True)   
    img_logo = models.ImageField(_('公司LOGO'), upload_to='logo', blank=True, null=True)
    img_banner = models.ImageField(_('网页banner'), upload_to=company_upload_banner, blank=True, null=True)
    img_bg = models.ImageField(_('网页背景'), upload_to=company_upload_bg, blank=True, null=True)
    img_id = models.ImageField(_('身份证'), upload_to=company_upload_id, blank=True, null=True)
    ty_id = models.IntegerField(_('酒鬼透云ID'), unique=True, blank=True, null=True)    
    #2020-07-21
    products=ArrayField(models.IntegerField(),verbose_name=_('授权产品'), blank=True, null=True)
    adm_ids=ArrayField(models.IntegerField(),verbose_name=_('授权区域'), blank=True, null=True)
    lng_lat=ArrayField(models.DecimalField(_('经纬度'),max_digits=12,decimal_places=8),blank=True,null=True)

    #2020-11-27
    #multi_parents=models.BooleanField(_('归属于多个父级'),default=False,blank=True,null=True)
    #parents_ids=ArrayField(models.IntegerField(),verbose_name=_('父级ID'),blank=True,null=True)
    
    #2021-09-24
    parents=models.JSONField(_('父级'),blank=True,null=True,default=list)



    #2020-12-03 是否买断工厂产品或包销(一级经销商使用扫码枪，是否同步工厂产品)
    is_exclusive = models.BooleanField(_('是否买断工厂产品或包销'),  default=False,blank=True,null=True)
    #2021-02-04
    rebate_payment=models.SmallIntegerField(_('返利支付方式'),default=1,choices=((1,'微信支付平台'),(2,'银行卡')),blank=True,null=True)
    wallet_bound=models.BooleanField(_('钱包是否已绑定'),default=False,blank=True,null=True)   
    #2021-07-15
    franchise_status=models.JSONField(_('加盟店状态'),default=list,blank=True,null=True)    
    franchise_series=models.JSONField(verbose_name=_('授权品牌/系列'),default=list,blank=True,null=True)
    franchise_products=models.JSONField(verbose_name=_('授权产品'),default=list,blank=True,null=True)
    create_by=models.ForeignKey('company.User',verbose_name=_('创建人'),related_name='company_create',on_delete=models.CASCADE,blank=True,null=True)
    create_tm=models.DateTimeField(_('创建时间'),blank=True,null=True)
    edit_by=models.ForeignKey('company.User',verbose_name=_('修改人'),related_name='company_edit',on_delete=models.CASCADE,blank=True,null=True)
    edit_tm=models.DateTimeField(_('修改时间'),blank=True,null=True)
    approve_by=models.ForeignKey('company.User',verbose_name=_('审核人'),related_name='company_approve',on_delete=models.CASCADE,blank=True,null=True)
    approve_tm=models.DateTimeField(_('审核时间'),blank=True,null=True)
    
 
    # 2021-11-17  单选加盟商状态与授权产品
    franchisestatus=models.ForeignKey('company.FranchiseStatus',related_name='company_franchisestatus',verbose_name=_('加盟商状态'),on_delete=models.CASCADE,blank=True,null=True)
    series=models.ForeignKey('product.Series',related_name='product_series',verbose_name=_('授权品牌/系列'),on_delete=models.CASCADE,blank=True,null=True)
    series_more = ArrayField(models.IntegerField('授权品牌/系列'), blank=True, null=True) 
    channel = models.ForeignKey(Channel,verbose_name=_('渠道'),on_delete=models.SET_NULL, blank=True, null=True)
    channel_level_ids = ArrayField(models.IntegerField(),verbose_name=_('渠道等级'), blank=True, null=True)

    
    #2022-04-23 长宇洒业(西凤375)
    is_golden=models.SmallIntegerField(_('是否为金牌客户'), choices=((0,'否'),(1,'是')), default=0, blank=True, null=True)
    
    class Meta:
        verbose_name = _('企业与经销商')
        verbose_name_plural = _('企业与经销商')
        unique_together = ('hierarchy', 'version', 'name')
        ordering = ['name']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if self.parent:
            #2019-11-14体系版本
            self.version=self.parent.version
            #2021-01-21
            if self.parent.ancestor_id:
                self.ancestor_id=self.parent.ancestor_id
            #2020-01-13
            self.has_external_code=self.parent.has_external_code
            
            # 保存层次体系（归属公司）
            if self.parent.hierarchy:
                self.hierarchy = self.parent.hierarchy
            else:
                self.hierarchy = self.parent
            # 保存销售层级
            if self.parent.level and not self.level:
                ls = Level.objects.filter(sn=(self.parent.level.sn+1))
                if ls:
                    self.level = ls[0]
                
                #2021-10-12 内参，自动添加外部编码
                #if self.ancestor_id==1644 and not self.external_code:
                #    #try:
                #        c=self.get_external_code()
                #        if c:
                #            self.external_code=c                    
                #    #except Exception:
                #    #    pass


            # 是否微商
            if self.parent.is_microboss:
                self.is_microboss = True
            else:
                # 保存战区和分区
                if not self.division and self.parent.division:
                    self.division = self.parent.division
                if not self.sub_division and self.parent.sub_division:
                    self.sub_division = self.parent.sub_division
        #else:
        #    self.ancestor_id = self.id
        super(Company, self).save(*args, **kwargs) 
        #if not self.parent:
        #    self.ancestor_id=self.id        
    
    def child_level(self):
        lv={'name':_('未知'),'id':0, 'max':''}        
        lv['max']=_('最高层级：')+Level.objects.all().order_by('-sn')[0].name
        if self.id:            
            lvs=Level.objects.filter(sn=self.level.sn+1)
            if lvs:
                lv['name']=lvs[0].name
                lv['id']=lvs[0].id
            else:
                lv['name']=_('营销层级错误')
                lv['id']=-1
        return lv   

    def get_cfg(self):
        company_cfg=None
        try:
            a=Company.objects.get(id=self.ancestor_id)
            company_cfg=a.cfg_company 
        except Exception:
            pass       
        return company_cfg 
    
    #2021-07-15
    def div_title(self):
        ns=CompanyDiv.objects.filter(id=self.id)
        if ns:
            return ns[0].div_name
        else:
            return '营销战区'

    def subdiv_title(self):
        ns=CompanyDiv.objects.filter(id=self.id)
        if ns:
            return ns[0].subdiv_name
        else:
            return '营销分区' 

    #2021-10-12 内参，自动添加外部编码
    def get_external_code(self):
        prfx=None
        if self.level.id==2:
            prfx='A'
            c=Company.objects.filter(parent_id=self.parent_id).order_by('-external_code')[0].external_code
        elif self.level.id==4:
            prfx='B'
            c=Company.objects.filter(ancestor_id=self.ancestor_id,level_id=4).order_by('-external_code')[0].external_code
        #elif self.level.id==5:
        #    prfx='C'
        #    c=Company.objects.filter(ancestor_id=self.ancestor_id,level_id=5).order_by('-external_code')[0].external_code

        if prfx:
            c=prfx+str(int(c[-5:])+1).zfill(5)
        else:
            c=None
        return c

#2021-07-15
class CompanyChangLog(models.Model):
    company=models.ForeignKey(Company,verbose_name=_('公司名称'),related_name='companychangelog_company',on_delete=models.CASCADE)
    user=models.ForeignKey('company.User',verbose_name=_('操作人'),related_name='companychangelog_user',on_delete=models.CASCADE)
    operation=models.CharField(_('执行操作'),max_length=20)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    dt = models.DateField(_('日期'), auto_now_add=True)

    class Meta:
        verbose_name = _('公司/客户信息修改日志')
        verbose_name_plural = _('公司/客户信息修改日志') 
    

#2021-04-24
class CGroup(models.Model):
    company=models.ForeignKey(Company,verbose_name=_('企业'),related_name='cgroupcompany',on_delete=models.CASCADE)
    group=models.ForeignKey('auth.Group',verbose_name=_('功能组别'),related_name='cgroupgroup',on_delete=models.CASCADE)
    name=models.CharField(_('组别角色名称'),max_length=50)   
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)
    is_delete=models.BooleanField(_('是否已删除'),default=False)
    tm = models.DateTimeField(_('时间'), auto_now_add=True) 
    tm_edit = models.DateTimeField(_('修改时间'), auto_now=True)     
    class Meta:
        verbose_name = _('企业角色(组别)')
        verbose_name_plural = _('企业角色(组别)')
        unique_together = ('company', 'group')


#2021-03-03
class Department(models.Model):
    company=models.ForeignKey(Company, verbose_name=_('公司名称'), related_name='department_company', on_delete=models.CASCADE)
    parent=models.ForeignKey('self',verbose_name=_('上级部门'),on_delete=models.PROTECT,blank=True,null=True) 
    division = models.ForeignKey('company.SalesDivision', verbose_name=_('营销大区'), related_name='department_division', on_delete=models.CASCADE, blank=True, null=True)
    sub_division = models.ForeignKey('company.SubSalDivision', verbose_name=_('营销分区'), related_name='department_division', on_delete=models.CASCADE, blank=True, null=True)  
    subsidiary=models.SmallIntegerField(_('外派机构'),choices=((0,_('否')),(1,_('是'))),default=0)
    name=models.CharField(_('部门名称'),max_length=20)    
    level=models.SmallIntegerField(_('层级'),default=0,blank=True,null=True)
    sn=models.SmallIntegerField(_('序号'),default=0,blank=True,null=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)

    class Meta:
        verbose_name = _('公司部门')
        verbose_name_plural = _('公司部门')
        unique_together = ('company', 'name')

    def save(self, *args, **kwargs):
        if self.parent:
            self.level=self.parent.level+1            
        super(Department, self).save(*args, **kwargs)

    def get_children(self):
        children=[]
        for d in Department.objects.filter(parent_id=self.id):
            children.append({'child':d,'headcount':d.staff_department.all().count()})
        return children

    def get_label(self):
        if self.level==0:
            return self.name
        elif self.level==1:
            return self.name
        elif self.level==2:
            return self.parent.name+' / '+self.name 
        elif self.level==3:
            return self.parent.parent.name+' / '+self.parent.name+' / '+self.name 

        

class Position(models.Model):
    company=models.ForeignKey(Company, verbose_name=_('公司名称'),on_delete=models.CASCADE)
    name=models.CharField(_('岗位职务'),max_length=20)
    group_id=models.IntegerField(_('功能组别'),blank=True,null=True)
    is_delete=models.BooleanField(_('是否已删除'),default=False)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)

    class Meta:
        verbose_name = _('岗位职务')
        verbose_name_plural = _('岗位职务')
        unique_together=('company','name')

    def __str__(self):
        return self.name
    

class Staff(models.Model):
    company=models.ForeignKey(Company, verbose_name=_('公司名称'), related_name='staff_company', on_delete=models.CASCADE)
    department=models.ForeignKey(Department,verbose_name=_('所属部门'),related_name='staff_department',on_delete=models.CASCADE)
    position=models.ForeignKey(Position,verbose_name=_('岗位职务'),related_name='staff_position',blank=True,null=True,on_delete=models.CASCADE)
    user=models.OneToOneField('company.User',verbose_name=_('登录帐号'),related_name='staff_user',on_delete=models.CASCADE,blank=True,null=True)
    name=models.CharField(_('员工姓名'),max_length=20)
    divisions=models.JSONField(_('授权战区'),default=list,blank=True,null=True)    
    cellphone=models.CharField(_('手机电话'),max_length=11,blank=True,null=True)    
    is_department_head=models.BooleanField(_('部门负责人'),default=False,blank=True,null=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)
    #2021-12-29
    subdivisions=models.JSONField(_('授权分区'),default=list,blank=True,null=True)
    agents=models.JSONField(_('授权经销商'),default=list,blank=True,null=True)
    
    class Meta:
        verbose_name = _('公司员工')
        verbose_name_plural = _('公司员工')

    def __str__(self):
        return self.name



class CompanyCert(models.Model):
    company=models.ForeignKey(Company, verbose_name=_('公司名称'), related_name='companycert_company', on_delete=models.CASCADE)
    appid=models.CharField(_('wxapp_id'),max_length=50)
    mch_no=models.CharField(_('商户号'),max_length=20)    
    api_key=models.CharField(_('API_KEY'),max_length=100)
    cert_file=models.CharField(_('证书存放相对路径'),max_length=100)
    key_file=models.CharField(_('密钥存放相对路径'),max_length=100)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)

    class Meta:
        verbose_name = _('微信支付证书文件')
        verbose_name_plural = _('微信支付证书文件')


#2021-06-28
#class CfgItem(models.Model):
#    name=models.CharField()
    

class CompanyCfg(models.Model):    
    company=models.OneToOneField(Company, verbose_name=_('公司名称'), related_name='cfg_company', on_delete=models.CASCADE)
    wx_account=models.ForeignKey('sales.WxOfficialAccounts',on_delete=models.CASCADE, verbose_name=_('微信公众号'),db_index=True,blank=True,null=True) 
    label_binding=models.CharField(_('跨段后绑定表名'),max_length=50,blank=True,null=True)
    
    #2021-01-16
    sms_sign=models.CharField(_('短信签名'),max_length=50,default='天鉴防伪')
    app_name=models.CharField(_('微信小程序名称'),max_length=50,default='天鉴物流终端')

    tjfwbase_oauth=models.SmallIntegerField(_('允许天鉴防伪微信静默授权'), choices=(
        (0,_('否')),
        (1, _('是')), ),default=1)
    tjfw_oauth=models.SmallIntegerField(_('使用天鉴防伪微信公众号授权'), choices=(
        (0,_('否')),
        (1, _('是')), ),default=0) 
    product_photo=models.SmallIntegerField(_('产品图片'), choices=(
        (0,_('无')),
        (1, _('有')), ),default=0)
    product_price=models.SmallIntegerField(_('产品价格'), choices=(
        (0,_('无')),
        (1, _('有')), ),default=0)
    inv_mgt = models.SmallIntegerField(_('是否有库存管理'), choices=(
        (0,_('无')),
        (1, _('有')), ),default=1)
    auth_area = models.SmallIntegerField(_('是否使用销售区域授权'), choices=(
        (0,_('否')),
        (1,_('简单授权(授权长期有效)')),
        (2,_('严格授权(定期增加授权记录)')), ),default=0)
    auth_product = models.SmallIntegerField(_('是否使用产品授权'), choices=(
        (0,_('否')),
        (1, _('是')), ),default=0)
    inbound_auto_lv1=models.SmallIntegerField(_('一级经销自动入库'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=1)   
    inbound_auto_lv2=models.SmallIntegerField(_('二级经销自动入库'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0) 
    outbound_cretiria_lv1=models.SmallIntegerField(_('一级经销出库规则'),choices=(
        (0, _('严格(先入库)')),      
        (1, _('不限制')),),default=0)  
    inbound_cretiria_lv2=models.SmallIntegerField(_('二级经销入库规则'),choices=(
        (0, _('有父级或总部直接发货记录')),
        (1, _('中等(父级有入库)')), 
        (2, _('宽松(工厂有发货)')),
        (3, _('超宽松(工厂有入库)')),
        (4, _('不限制')),),default=0)       
    outbound_cretiria_lv2=models.SmallIntegerField(_('二级经销出库库规则'),choices=(
        (0, _('严格(入库后才能出库)')),
        (1, _('中等(父级有发货)')), 
        (2, _('宽松(工厂有发货)')),        
        (4, _('不限制')),),default=0)  
    perm_inbound_lv1=models.SmallIntegerField(_('允许一级经销商入库'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0)   
    inbound_cretiria_lv1=models.SmallIntegerField(_('一级经销入库规则'),choices=(
        (0, _('严格(工厂有发货)')),
        (1, _('中等(工厂有入库)')), 
        (2, _('不限制')),),default=0) 
    multi_parents=models.SmallIntegerField(_('是否会有经销商归属于多个父级'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True)
    #2020-11-30
    saldiv_provincial=models.SmallIntegerField(_('战区是否区分省内省外'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True)
    saldiv_report=models.SmallIntegerField(_('报表区分战区分区'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True)
    #2020-12-03
    lv1_pkg_split=models.SmallIntegerField(_('一级经销商可按瓶发货'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True)
    #2020-12-18
    terminal_register_automatic_approve=models.SmallIntegerField(_('终端店注册系统自动审核通过'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True)
    #2021-01-11
    thirdparty_sync=models.SmallIntegerField(_('第三方信息同步'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True)    
    #2021-02-28
    bulletinboard=models.SmallIntegerField(_('公告信息管理'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True)    
    #2021-02-28
    orginazitionchart=models.SmallIntegerField(_('组织架构管理'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True)    
    #2021-03-08
    rebateinvoicecheck=models.SmallIntegerField(_('返利发票录入'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    membership=models.SmallIntegerField(_('会员管理'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    stack_mgt=models.SmallIntegerField(_('垛位管理'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    duplication_outbound_agent=models.SmallIntegerField(_('允许经销商多次出库'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    duplication_outbound_company=models.SmallIntegerField(_('允许工厂/公司多次出库'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    duplication_inbound_agent=models.SmallIntegerField(_('允许经销商多次入库'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    duplication_inbound_company=models.SmallIntegerField(_('允许工厂/公司多次入库'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    mes_mgt=models.SmallIntegerField(_('生产管理'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    mes_inbound_qc_check_needed=models.SmallIntegerField(_('入库材料是否区分有没有经过质检'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    channelrebate_agent_scan=models.SmallIntegerField(_('经销商扫码层级返利'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    channelrebate_consumer_scan=models.SmallIntegerField(_('消费者扫码层级返利'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    #2021-07-10 
    inbound_ticket=models.SmallIntegerField(_('是否使用销售启票'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 
    #2021-07-15 
    franchise_mgt=models.SmallIntegerField(_('加盟店管理'),choices=(
        (0, _('无加盟商管理')),
        (1, _('品牌/系列授权管理')),
        (2, _('产品授权管理'))),default=0,blank=True) 
    #2021-07-19
    wx_transfer_amt=models.IntegerField(_('微信单帐号当日累计转帐上限'),default=50000,blank=True,null=True)


    #2021-09-15
    menu_type=models.SmallIntegerField(_('企业菜单类别'),choices=(
        (0,_('left.html')),
        (1, _('动态加载')), ),default=0,blank=True) 
    batch_mgt=models.SmallIntegerField(_('产成品批次管理'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True) 

    #2021-11-05
    scanner_only_lv1=models.SmallIntegerField(_('扫码枪发货只显示一级经销商'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True)
    #2021-12-22
    terminal_return=models.SmallIntegerField(_('经销商接收终端店退货'),choices=(
        (0, _('严格(必须是发给当前终端的产品)')),
        (1, _('中等(经销商有发货记录)')), 
        (2, _('不限制')),),default=2)  
    
    #2022-01-12 ERP 销售订单
    erp_salesorder=models.SmallIntegerField(_('启用ERP销售订单'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0,blank=True)
    #2022-01-14 
    product_depend_on=models.SmallIntegerField(_('产品名称'),choices=(
        (0, _('操作时的选择')),
        (1, _('入库时品名优先')), ),default=0,blank=True)

    #2022-06-12
    shelf_life=models.SmallIntegerField(_('产品保质期管理'),choices=(
        (0, _('不需要')),
        (1, _('需要')), ),default=0,blank=True)
    
    #2022-06-21 经销商使用扫描枪发货时,产品的同步方式
    agent_products=models.SmallIntegerField(_('产品同步方式'),choices=(
        (0,_('同步所属企业的全部产品')),
        (1,_('只同步被授权产品')),),default=0,blank=True)
    #2021-12-30 内参小程序是否可扫码
    mp_scanner_enabled=models.SmallIntegerField(_('小程序是否可扫码'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=1,blank=True)  
    #2021-12-30 小程序是否需要选择产品
    mp_choose_product=models.SmallIntegerField(_('小程序是否需要选择产品'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=1,blank=True)
    # 2022-09-24 企业是否对产品实行生产批次(包含保质期管理)
    product_batchlot=models.SmallIntegerField(_('生产批次管理'),choices=(
        (0,_('否')),
	(1, _('是')), ),default=1,blank=True)


    class Meta:
        verbose_name = _('公司基础设置')
        verbose_name_plural = _('公司基础设置')

    def __str__(self):
        return self.company.name


class WxOpenid(models.Model):    
    company=models.ForeignKey(Company, verbose_name=_('企业名称'), related_name='wxopenid_company', on_delete=models.CASCADE)
    wx_openid = models.CharField(_('微信OpenID'), max_length=50, db_index=True)
    wx_nickname = models.CharField(_('微信昵称'), max_length=100, db_index=True)
    wx_headimgurl = models.CharField(_('微信头像'), max_length=400)       
    tm = models.DateTimeField(_('时间'), auto_now_add=True)    
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True) 

    class Meta:
        verbose_name = _('公司登录帐号OPENID')
        verbose_name_plural = _('公司登录帐号OPENID')
        unique_together = ('company', 'wx_openid')

    def __str__(self):
        return self.wx_nickname


class User(AbstractUser):
    company = models.ForeignKey(Company, verbose_name=_('公司名称'), blank=True, null=True, related_name='user_company', on_delete=models.CASCADE)
    external_id = models.IntegerField(_('外部ID'), blank=True, null=True, unique=True)
    external_code = models.CharField(_('外部编码'), max_length=30, blank=True, null=True)
    ancestor_id=models.IntegerField(_('族系'),blank=True,null=True, db_index=True)
    phone = models.CharField(_('电话'), max_length=20, null=True, blank=True)   
    wx_official_id=models.IntegerField(_('微信公众号ID'),blank=True,null=True)
    wx_headimgurl=models.CharField(_('微信头像URL'),max_length=400,blank=True,null=True)

    wx_openid = models.CharField(_('微信OPENID'), max_length=50, blank=True,null=True,db_index=True)
    #2021-03-22    
    bind_wxopenid=models.CharField(_('绑定微信OPENID'), max_length=50, blank=True, null=True,db_index=True)

    wx_unionid = models.CharField(_('微信UNIONID'), max_length=50, blank=True, null=True)    
    wxopenids= ArrayField(models.IntegerField('使用过的OPENID'), blank=True, null=True) 
    legacy_id = models.IntegerField(_('SqlSrvID'), null=True, blank=True)
    is_active = models.BooleanField(_('是否已激活'), default=True)
    is_delete = models.BooleanField(_('是否已删除'), default=False)
    #2020-12-07
    agents_incharge=ArrayField(models.IntegerField(),verbose_name=_('业务员负责的终端店/经销商'), blank=True, null=True)
    pwd_changed = models.BooleanField(_('是否已修改密码'),default=False)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    brand_ids=ArrayField(models.IntegerField(),verbose_name=_('品牌ID'),blank=True,null=True)    
    #2021-09-11 用户账号所拥有的企业功能组别权限
    cgroup_ids=models.JSONField(_('企业功能组别'),default=list,blank=True,null=True)
    product_series = ArrayField(models.IntegerField('授权品牌/系列'), blank=True, null=True) 
    # 2022-06-29 启用RESTFUL API后，保存用户所属角色
    roles=models.JSONField(_('所属角色'),default=list,blank=True,null=True)

    class Meta:
        verbose_name = _('用户帐号')
        verbose_name_plural = _('用户帐号')

        permissions = (
            ('sys_admin', '系统管理员权限'),
            ('stk_inbound', '库存入库权限'),
            ('stk_delivery', '库存发货权限'),
            #('stk_qrscan', '库存扫码权限'),

            ('stk_close_order', '关闭下级订单'),

            ('mkt_inspect','市场级稽查'),
            ('lbl_query','标签查询'),
            ('lbl_package','查看未激活标签套标关系'),
            ('sal_chart','查看销售图表'),
            ('sal_divmgt','营销战区管理'),

            ('sal_inside_job', '内勤管理'),
            ('sal_salesmen', '业务员'),
           
        )
    def save(self, *args, **kwargs):    
        if self.username and not self.last_name:
            self.last_name=self.username            
        super(User, self).save(*args, **kwargs)

    '''
    def save(self, *args, **kwargs):
        # 保存到SQL SRV
        cn = pyodbc.connect(settings.WULIU_STR)
        cur = cn.cursor()
        l_id = 0
        if not self.id:
            c_id = self.company.legacy_id
            if c_id:
                # sql srv role_id:53 酒鬼酒系统管理员
                s = "insert into TJMarketingSystemYin.dbo.TJ_User(CompID,LoginName,RID,IsActived) " + \
                    "values (" + str(c_id)  + ",'" + self.username + "',53,1)"
                cur.execute(s)
                cur.execute('SELECT @@IDENTITY')
                r = cur.fetchone()
                if r:
                    l_id = r[0]
                    self.legacy_id = l_id
                cn.commit()
        else:
            cur.execute("update TJMarketingSystemYin.dbo.TJ_User set LoginName='" + self.username + "' " + \
                    " where UserID=" + str(self.legacy_id))
            cn.commit()
        super(User, self).save(*args, **kwargs)
        # 更新SQL SRV ID
        if l_id:
            # 更新SQL SRV ID
            cur.execute("update TJMarketingSystemYin.dbo.TJ_User set pg_stk_id=" + str(self.id) + \
                        " where UserID=" + str(l_id))
            cn.commit()
        cur.close()
        cn.close()
    '''

    

class BrandRecommender(models.Model):
    company=models.ForeignKey(Company, verbose_name=_('企业名称'), related_name='recommender_company', on_delete=models.CASCADE)
    agent=models.ForeignKey(Company, verbose_name=_('关联经销商'), related_name='recommender_agent', on_delete=models.CASCADE)
    user=models.ForeignKey(User,verbose_name=_('操作人'),related_name='recommender_user', on_delete=models.CASCADE)
    wxopenid=models.CharField(_('微信OpenID'),max_length=100,db_index=True,null=True,blank=True)
    name=models.CharField(_('姓名'),max_length=20,db_index=True)
    cellphone=models.CharField(_('手机'),max_length=11,blank=True,null=True)
    address=models.CharField(_('地址'),max_length=100,blank=True,null=True)    
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    is_active = models.BooleanField(_("是否通过审核"),default=False)
    is_hidden = models.BooleanField(_("是否被隐藏"),default=False)
    remark=models.CharField(_('备注'),max_length=100,blank=True,null=True)

    class Meta:
        verbose_name = _('品牌推荐官')
        verbose_name_plural = _('品牌推荐官')
        unique_together = ('company', 'name')

    def __str__(self):
        return self.name



class StaffSaldiv(models.Model):
    company = models.ForeignKey(Company,verbose_name=_('企业名称'),related_name='staffdiv_company', on_delete=models.CASCADE)
    user = models.OneToOneField(User,verbose_name=_('用户帐号'), on_delete=models.CASCADE)
    user_name=models.CharField(_('用户姓名'),max_length=20,blank=True,null=True)
    group_ids=ArrayField(models.IntegerField(),verbose_name=_('功能组'),blank=True,null=True)
    saldiv_ids=ArrayField(models.IntegerField(),verbose_name=_('战区'),blank=True,null=True)
    subsaldiv_ids=ArrayField(models.IntegerField(),verbose_name=_('分区'),blank=True,null=True)
    agent_ids=ArrayField(models.IntegerField(),verbose_name=_('经销商'),blank=True,null=True)
    tm = models.DateTimeField(_('创建时间'), auto_now_add=True)
    
    class Meta:
        verbose_name = _('营销管理人员区域划分')
        verbose_name_plural = _('营销管理人员区域划分')

    def save(self, *args, **kwargs):    
        if self.user.last_name:
            self.user_name=self.user.last_name            
        super(StaffSaldiv, self).save(*args, **kwargs)


class AuthorizedProducts(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('经销商'), related_name='authorizedproduct_company', on_delete=models.CASCADE)
    user = models.ForeignKey(User, verbose_name=_('授权操作人'), related_name='authorizedproduct_user', on_delete=models.CASCADE)    
    products=ArrayField(models.IntegerField(),verbose_name=_('授权产品'))
    dt_from = models.DateField(_('授权开始日期'), blank=True, null=True)
    dt_to = models.DateField(_('授权结束日期'), blank=True, null=True)    
    tm = models.DateField(_('授权时间'), auto_now_add=True)

    class Meta:
        verbose_name = _('产品授权')
        verbose_name_plural = _('产品授权')


#2020-07-20
class AuthorizedAreas(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司'), related_name='authorizedarea_company', on_delete=models.PROTECT)  
    user = models.ForeignKey(User, verbose_name=_('授权操作人'), related_name='authorizedarea_user', on_delete=models.CASCADE)
    adm_ids=ArrayField(models.IntegerField(),verbose_name=_('授权区域'))
    dt_from = models.DateField(_('授权开始日期'), blank=True, null=True)
    dt_to = models.DateField(_('授权结束日期'), blank=True, null=True)    
    tm = models.DateField(_('授权时间'), auto_now_add=True)
    
    class Meta:
        verbose_name = _('区域授权')
        verbose_name_plural = _('区域授权')


class SalesDivision(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司名称'), related_name='division_company',
                                on_delete=models.CASCADE)
    code = models.CharField(_('战区编码'), max_length=10, blank=True, null=True)
    name = models.CharField(_('战区名称'), max_length=50)
    manager = models.ForeignKey(User, verbose_name=_('战区经理'), blank=True, null=True, on_delete=models.CASCADE)
    #2020-11-30 内参战区分省内省外
    provincial=models.SmallIntegerField(_('是否为省内站区'),blank=True,null=True,default=0,choices=((0,'省外'),(1,'省内')))
    sn=models.SmallIntegerField(_('序号'),blank=True,null=True)
    is_delete = models.BooleanField(_('是否已删除'), default=False)
    rpt_shown=models.BooleanField(_('销售报表是否显示此战区'),default=True,blank=True,null=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)

    category=models.SmallIntegerField(_('类别'),choices=((1,'省内'),(2,'省外'),(3,'其它')),default=2,blank=True,null=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = _('营销战区')
        verbose_name_plural = _('营销战区')
        unique_together = ('company', 'name')
        ordering = ['name']

    def __str__(self):
        return self.name


class SubSalDivision(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司名称'), related_name='sub_division_company',
                                on_delete=models.CASCADE)
    division = models.ForeignKey(SalesDivision, verbose_name=_('营销战区'), on_delete=models.CASCADE)
    code = models.CharField(_('分区编码'), max_length=10, blank=True, null=True)
    name = models.CharField(_('分区名称'), max_length=50)
    manager = models.ForeignKey(User, verbose_name=_('分区经理'), blank=True, null=True, on_delete=models.CASCADE)
    is_delete = models.BooleanField(_('是否已删除'), default=False)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = _('营销分区')
        verbose_name_plural = _('营销分区')
        unique_together = ('division', 'name')
        ordering = ['name']

    def __str__(self):
        return self.name


class CategoryProp(models.Model):
    category = models.ForeignKey(Category, verbose_name=_('公司类别'), on_delete=models.CASCADE)
    name = models.CharField(_('属性名称'), max_length=50)
    desc_cn = models.CharField(_('中文属性名'), max_length=50)
    desc_en = models.CharField(_('英文属性名'), max_length=50, blank=True, null=True)
    unit = models.CharField(_('单位'), max_length=20, blank=True, null=True)
    type = models.CharField(_('值类型'), max_length=10, blank=True, null=True, choices=(
        ('c', _('字符')),
        ('n', _('数字')),
    ))
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = _('属性类别')
        verbose_name_plural = _('属性类别')
        unique_together = ('category', 'name')

    def __str__(self):
        return self.desc_cn


class PrdPlant(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司名称'), related_name='plant_company', on_delete=models.CASCADE)
    legacy_id = models.IntegerField(_('SqlSrvID'), null=True, blank=True)
    external_code = models.CharField(_('外部编码'), max_length=30, blank=True, null=True)
    name = models.CharField(_('工厂/厂区名称'), max_length=50)
    address = models.CharField(_('地址'), max_length=100, blank=True, null=True)
    remark = models.CharField(_('备注说明'), max_length=50, blank=True, null=True)
    is_delete = models.BooleanField(_('是否已删除'), default=False)

    class Meta:
        verbose_name = _('工厂/厂区')
        verbose_name_plural = _('工厂/厂区')
        unique_together = ('company', 'name')

    def __str__(self):
        return self.name


class PrdWorkshop(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司名称'), related_name='workshop_company',
                                on_delete=models.CASCADE)
    prd_plant = models.ForeignKey(PrdPlant, verbose_name=_('工厂厂区'), related_name='workshop_plant',
                              on_delete=models.CASCADE, blank=True, null=True)
    adm_id = models.IntegerField(_('GIS'), blank=True, null=True)
    province = models.CharField(_('省份'), max_length=20, blank=True, null=True)
    city = models.CharField(_('城市'), max_length=20, blank=True, null=True)
    address = models.CharField(_('地址'), max_length=100, blank=True, null=True)
    legacy_id = models.IntegerField(_('SqlSrvID'), null=True, blank=True)
    external_code = models.CharField(_('外部编码'), max_length=30, blank=True, null=True)
    name = models.CharField(_('车间名称'), max_length=50)
    remark = models.CharField(_('备注说明 '), max_length=100, blank=True, null=True)
    is_delete = models.BooleanField(_('是否已删除'), default=False)

    class Meta:
        verbose_name = _('生产车间')
        verbose_name_plural = _('生产车间')
        unique_together = ('company', 'prd_plant', 'name')

    def __str__(self):
        return self.name


class PrdLine(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司名称'), related_name='line_company',
                                on_delete=models.CASCADE)
    prd_plant = models.ForeignKey(PrdPlant, verbose_name=_('工厂/厂区'), related_name='line_plant',
                              on_delete=models.CASCADE, blank=True, null=True)
    prd_workshop = models.ForeignKey(PrdWorkshop, verbose_name=_('生产车间'), related_name='line_shop',
                                     on_delete=models.CASCADE, blank=True, null=True)
    legacy_id = models.IntegerField(_('SqlSrvID'), null=True, blank=True)
    external_code = models.CharField(_('外部编码'), max_length=30, blank=True, null=True)
    name = models.CharField(_('产线名称'), max_length=20)
    remark = models.CharField(_('备注说明'), max_length=50, blank=True, null=True)
    is_delete = models.BooleanField(_('是否已删除'), default=False)

    class Meta:
        verbose_name = _('生产线')
        verbose_name_plural = _('生产线')
        unique_together = ('prd_workshop', 'prd_plant', 'name')

    def __str__(self):
        return self.name


class PrdTeam(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司名称'), related_name='team_company',
                                on_delete=models.CASCADE)
    prd_plant = models.ForeignKey(PrdPlant, verbose_name=_('工厂/厂区'), related_name='team_plant',
                              on_delete=models.CASCADE, blank=True, null=True)
    prd_workshop = models.ForeignKey(PrdWorkshop, verbose_name=_('生产车间'), related_name='team_shop',
                                     on_delete=models.CASCADE, blank=True, null=True)
    prd_line = models.ForeignKey(PrdLine, verbose_name=_('生产线'), related_name='team_line',
                                 on_delete=models.CASCADE, blank=True, null=True)
    type = models.CharField(_('班组类别'), max_length=20,blank=True,null=True,default=_('production'), choices=(       
        (_('production'), _('生产班组')),
        (_('inspection'), _('检验班组')),
    ))
    name = models.CharField(_('班组名称'), max_length=50)
    legacy_id = models.IntegerField(_('SqlSrvID'), null=True, blank=True)
    external_code = models.CharField(_('外部编码'), max_length=30, blank=True, null=True)
    remark = models.CharField(_('备注说明 '), max_length=100, blank=True, null=True)
    is_delete = models.BooleanField(_('是否已删除'), default=False)

    class Meta:
        verbose_name = _('生产班组')
        verbose_name_plural = _('生产班组')
        unique_together = ('company', 'prd_plant', 'prd_workshop', 'prd_line', 'name')

    def __str__(self):
        return self.name


class PrdQc(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司名称'), related_name='qc_company', on_delete=models.CASCADE)
    legacy_id = models.IntegerField(_('SqlSrvID'), null=True, blank=True)
    prd_plant = models.ForeignKey(PrdPlant, verbose_name=_('工厂/厂区'), related_name='qc_plant',
                              on_delete=models.CASCADE, blank=True, null=True)
    prd_workshop = models.ForeignKey(PrdWorkshop, verbose_name=_('生产车间'), related_name='qc_shop',
                                     on_delete=models.CASCADE, blank=True, null=True)
    external_code = models.CharField(_('外部编码'), max_length=30, blank=True, null=True)
    name = models.CharField(_('质检员'), max_length=50)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = _('质检员')
        verbose_name_plural = _('质检员')
        unique_together = ('company', 'prd_plant', 'prd_workshop', 'name')

    def __str__(self):
        return self.name


class TerminalRegister(models.Model):
    ancestor=models.ForeignKey(Company, verbose_name=_('公司族系'), related_name='terminal_ancestor', on_delete=models.CASCADE)
    parent=models.ForeignKey(Company, verbose_name=_('上级公司名称'), related_name='terminal_company', on_delete=models.CASCADE)
    name=models.CharField(_('终端店名称'),max_length=100)
    contacts=models.CharField(_('联系人'),max_length=50)
    cell_phone = models.CharField(_('手机号码'), max_length=20)
    license_number=models.CharField(_('营业执照编号'),max_length=50,blank=True,null=True)
    address = models.CharField(_('详细地址'), max_length=100)     
    wx_openid = models.CharField(_('微信OpenID'), max_length=50)
    img_signboard = models.ImageField(_('店面门头照'), upload_to=company_upload_register,blank=True,null=True)
    img_license = models.ImageField(_('营业执照'), upload_to=company_upload_register,blank=True,null=True)
    tm = models.DateTimeField(_('申请时间'), auto_now_add=True)
    dt = models.DateField(_('申请日期'), auto_now_add=True)
    tm_aprv = models.DateTimeField(_('审核通过时间'), blank=True,null=True)
    user_aprv=models.ForeignKey('company.User', verbose_name=_('审核人'), related_name='who_aprv', on_delete=models.CASCADE, blank=True, null=True)
    lng_lat=ArrayField(models.DecimalField(_('经纬度'),max_digits=12,decimal_places=8),blank=True,null=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)
    product_series = ArrayField(models.IntegerField('授权品牌/系列'), blank=True, null=True) 
    salesman_id = models.IntegerField(_('业务员id'), null=True, blank=True)
    # 2022-09-14
    is_rejected=models.BooleanField(_('是否已驳回'),default=False,blank=True,null=True)
    tm_rejected=models.DateTimeField(_('驳回时间'),blank=True,null=True)

    class Meta:
        verbose_name = _('终端店注册申请记录')
        verbose_name_plural = _('终端店注册申请记录')       

    def __str__(self):
        return self.name



class AgentOrderBatch(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('下单公司'), related_name='agentorder_batch_company', on_delete=models.PROTECT)
    vendor = models.ForeignKey('company.Company', verbose_name=_('接单公司'), related_name='agentorder_batch_receiver', on_delete=models.PROTECT)
    ancestor_id=models.IntegerField(_('族系'), db_index=True)
    code=models.CharField(_('订单号'), max_length=40)    
    user = models.ForeignKey('company.User', verbose_name=_('下单人'), on_delete=models.PROTECT, related_name='agentorder_batch_user')
    tm = models.DateTimeField(_('下单时间'), auto_now_add=True)
    dt = models.DateField(_('下单日期'), auto_now_add=True)
    dt_expect = models.DateField(_('期望到货日期'),blank=True,null=True)
    tm_complete=models.DateTimeField(_('订单完成时间'), blank=True, null=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)
    review_company = models.ForeignKey('company.Company', verbose_name=_('审核公司'), on_delete=models.PROTECT, related_name='agentorder_review_company',blank=True,null=True)
    batch_code = models.CharField(_('物流订单号'), max_length=40,blank=True,null=True)
    voucher_id = models.IntegerField(_('单据类别'),blank=True,null=True, db_index=True)
    helper = models.ForeignKey('company.User', verbose_name=_('协助下单人'), on_delete=models.PROTECT, related_name='agentorder_batch_helper',blank=True,null=True)
    voucher_code = models.CharField(_('单据号'),blank=True,null=True,max_length=50)
    state = models.SmallIntegerField(_('审核状态'),blank=True,null=True,default=0)
    
    
    class Meta:
        verbose_name = _('终端店订单Batch')
        verbose_name_plural = _('终端店订单Batch')
        unique_together = ('company', 'code')



class AgentOrderDetails(models.Model):
    batch = models.ForeignKey(AgentOrderBatch, verbose_name=_('终端店订单Batch'), on_delete=models.CASCADE)
    company = models.ForeignKey('company.Company', verbose_name=_('公司'), related_name='agentlorder_detail_company', on_delete=models.PROTECT)
    vendor = models.ForeignKey('company.Company', verbose_name=_('接单公司'),  related_name='agentorder_detail_receiver', on_delete=models.PROTECT)
    ancestor_id=models.IntegerField(_('族系'),blank=True,null=True, db_index=True)   
    product = models.ForeignKey('product.Product', verbose_name=_('产品名称'), related_name='agentorder_detail_product', on_delete=models.PROTECT)
    
    #2020-11-05删除
    #qty=models.IntegerField(_('数量'),blank=True,null=True)
    #package_id=models.SmallIntegerField(_('单位'),default=3,choices=( (1, _('瓶')),(3, _('箱'))),blank=True,null=True )
    #2020-11-05删除   
    
    voucher_id = models.SmallIntegerField(_('操作类型'), default=0)
    qty_box=models.IntegerField(_('箱数'),blank=True,null=True)
    qty_bottle=models.IntegerField(_('瓶数'),blank=True,null=True)
    qty_h=models.IntegerField(_('盒数'),blank=True,null=True)
    
    class Meta:
        verbose_name = _('终端店订单detail')
        verbose_name_plural = _('终端店订单detail')

    def save(self, *args, **kwargs):
        self.ancestor_id=self.company.ancestor_id
        super(self.__class__, self).save(*args, **kwargs)


#终端店订单审核
class AgentOrderReview(models.Model):
    batch = models.ForeignKey(AgentOrderBatch, verbose_name=_('终端店订单Batch'), on_delete=models.CASCADE)
    company = models.ForeignKey('company.Company', verbose_name=_('审核公司'), on_delete=models.CASCADE)
    user = models.ForeignKey('company.User', verbose_name=_('审核人'), on_delete=models.PROTECT)
    tm = models.DateTimeField(_('审核时间'), auto_now_add=True)
    dt = models.DateField(_('审核日期'), auto_now_add=True)
    class Meta:
        verbose_name = _('终端店订单审核')
        verbose_name_plural = _('终端店订单审核')



#2020-08-15
class ChangeLog(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司'), related_name='changelog_company', on_delete=models.PROTECT) 
    ancestor_id=models.IntegerField(_('族系'), db_index=True)
    user = models.ForeignKey('company.User', verbose_name=_('操作人'), on_delete=models.PROTECT, related_name='changelog_user')     
    obj_name=models.CharField(_('对象名称'),max_length=20, db_index=True)    
    obj_id=models.IntegerField(_('对象id'),db_index=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    dt = models.DateField(_('日期'), auto_now_add=True, db_index=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)

    class Meta:
        verbose_name = _('数据修改日志')
        verbose_name_plural = _('数据修改日志')


#2020-11-20
#def BankInfo(models.Model):
#    company = models.OneToOneField('company.Company', verbose_name=_('经销商'), related_name='company_bankinfo', on_delete=models.CASCADE)
#    ancestor_id=models.IntegerField(_('族系'), db_index=True)
#    bank_name=models.CharField(_(''),max_length=50)





class White_Domain_Type(models.Model):
    name = models.CharField(_('类型'),max_length=100)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    class Meta:
        verbose_name = _('域名白名单类型')
        verbose_name_plural = _('域名白名单类型')
    def __str__(self):
        return self.name

#2020-11-28
#域名白名单
class White_Domain(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    domain = models.CharField(_('域名'),max_length=200)
    domain_type = models.ForeignKey(White_Domain_Type, verbose_name=_(
        '域名类型'), on_delete=models.DO_NOTHING)  
    is_active = models.BooleanField(
        _('是否激活'), blank=False, null=False, default=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    class Meta:
        verbose_name = _('域名白名单')
        verbose_name_plural = _('域名白名单')

#2020-11-30
class Label_Bind_Rule(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    level_1 = models.SmallIntegerField(_('一级绑定'), default=0)
    level_2 =  models.SmallIntegerField(_('二级绑定'), default=0)
    level_3 =  models.SmallIntegerField(_('三级绑定'), default=0)
    is_active = models.BooleanField(_('是否激活'), default=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)

    class Meta:
        verbose_name = _('绑定规则')
        verbose_name_plural = _('绑定规则')

class Third_Party_Company(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    name = models.CharField(_('第三方公司名称'),max_length=200)
    is_active = models.BooleanField(_('是否激活'), default=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    class Meta:
        verbose_name = _('第三方公司')
        verbose_name_plural = _('第三方公司')
    def __str__(self):
        return self.name
 
class Third_Party_Label_Bind(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    label_type =  models.CharField(_('标签类型'),max_length=50)
    label_code = models.CharField(_('标签序号'),max_length=50,db_index=True)
    label_code_out = models.CharField(_('第三方标签序号'),max_length=100,db_index=True) 
    label_code_type = models.SmallIntegerField(_('标签序号类型'), default=2)
    label_bind_rule = models.CharField(_('绑定规则'),max_length=50)
    label_bar_code = models.CharField(_('条形码'),max_length=50,db_index=True)
    third_party_company = models.ForeignKey(Third_Party_Company, verbose_name=_(
        '第三方公司'), on_delete=models.DO_NOTHING)  
    batch_id = models.CharField(_('标签序号'),max_length=50)
    user = models.ForeignKey('company.User', verbose_name=_('操作人'), on_delete=models.DO_NOTHING, blank=True, null=True)
    parent_id = models.IntegerField(_('父级ID'), blank=True, null=True)
    first_parent_id = models.IntegerField(_('顶层父级ID'), blank=True, null=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    remark = models.CharField(_('备注'),max_length=50)
    class Meta:
        verbose_name = _('第三方标签序号绑定')
        verbose_name_plural = _('第三方标签序号绑定')


#权益
class Benefit(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    name = models.CharField(_("权益名称"),max_length=50,db_index=True)
    is_face_to_agent=models.BooleanField(_('是否面向经销商'), default=True)
    is_face_to_terminal=models.BooleanField(_('是否面向终端店'), default=True)
    is_face_to_business=models.BooleanField(_('是否面向业务员'), default=True)
    is_active = models.BooleanField(_('是否激活'), default=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True,default='')
    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)
    class Meta:
        verbose_name = _('权益')
        verbose_name_plural = _('权益')
    def __str__(self):
        return self.name


#权益类型
class Benefit_Rule_Category(models.Model):
    name = models.CharField(_("权益类型名称"), max_length=50, db_index=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)
    class Meta:
        verbose_name = _('权益类型')
        verbose_name_plural = _('权益类型')

#权益规则
class Benefit_Rule(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    benefit = models.ForeignKey(Benefit, verbose_name=_('权益'), on_delete=models.CASCADE)
    name = models.CharField(_("权益名称"), max_length=50, db_index=True)
    rule_category = models.ForeignKey(Benefit_Rule_Category, verbose_name=_('权益类型'), on_delete=models.DO_NOTHING)
    discount = models.DecimalField(_('折扣'), max_digits=10, decimal_places=2, blank=True, null=True, default=100)
    is_active = models.BooleanField(_('是否激活'), default=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)
    class Meta:
        verbose_name = _('权益规则')
        verbose_name_plural = _('权益规则')

#品牌管理
class Brands(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    third_party_company =models.ForeignKey(Third_Party_Company, verbose_name=_('第三方公司'), on_delete=models.DO_NOTHING)
    name = models.CharField(_('名称'),max_length=100)
    is_active = models.BooleanField(_('是否激活'), default=True)
    level_up_method = models.SmallIntegerField(_('升级方法'), choices=((1, _('按销售数量')), (2, _('按销售金额'))), blank=True, null=True, default=1)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True,default='')
    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)
    settle_method = models.SmallIntegerField(_('重置方法'), choices=((0, _('不重置')), (1, _('年度')), (2, _('季度')), (3, _('月度'))), blank=True, null=True, default=0)
    reset_tm = models.DateTimeField(_('重置时间'), blank=True, null=True)
    class Meta:
        verbose_name = _('品牌管理')
        verbose_name_plural = _('品牌管理')

#品牌等级
class Brands_Level(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    brand = models.ForeignKey(Brands, verbose_name=_('品牌'), on_delete=models.CASCADE)
    benefit = models.ForeignKey(Benefit, verbose_name=_('权益'), on_delete=models.SET_NULL, null=True, blank=True)
    name = models.CharField(_("等级名称"),max_length=50,db_index=True)
    level = models.IntegerField(_("等级"),db_index=True,default=1)
    photo=models.ImageField(_('等级图片'), upload_to=company_upload_brand,blank=True,null=True)
    need_money = models.IntegerField(_('需要金额'),blank=True,null=True,default=0)
    need_num = models.IntegerField(_('需要数量'),blank=True,null=True,default=0)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True,default='')
    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)
    reset_tm = models.DateTimeField(_('重置时间'), blank=True, null=True)
    class Meta:
        verbose_name = _('品牌管理')
        verbose_name_plural = _('品牌管理')


#经销商品牌等级
class Brands_Agent_Level(models.Model):
    ancestor_id = models.IntegerField(_('祖籍ID'),blank=True,null=True)
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    brand = models.ForeignKey(Brands, verbose_name=_('品牌'), on_delete=models.SET_NULL,blank=True,null=True)
    brand_level = models.ForeignKey(Brands_Level, verbose_name=_('品牌等级'), on_delete=models.SET_NULL,blank=True,null=True)
    all_money = models.DecimalField(_('全部金额'),max_digits=10, decimal_places=2,blank=True,null=True,default=0)
    all_num = models.IntegerField(_('全部数量'),blank=True,null=True,default=0)

    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)
    class Meta:
        verbose_name = _('品牌管理')
        verbose_name_plural = _('品牌管理')

#经销商等级写入记录
class Brands_Agent_Records(models.Model):
    ancestor_id = models.IntegerField(_('祖籍ID'),blank=True,null=True)
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING,blank=True,null=True)
    brand = models.ForeignKey(Brands, verbose_name=_('品牌'), on_delete=models.SET_NULL,blank=True,null=True)
    product_id = models.IntegerField(_('产品ID'),blank=True,null=True)
    product_name = models.CharField(_('产品名称'),max_length=100)
    product_num = models.IntegerField(_('产品数量'),default=0)
    product_money = models.DecimalField(_('产品价格'), max_digits=10, decimal_places=2, blank=True, null=True, default=0)

    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)

    class Meta:
        verbose_name = _('经销商等级写入记录')
        verbose_name_plural = _('经销商等级写入记录')

#经销商等级记录
class Brands_Agent_Level_Records(models.Model):
    ancestor_id = models.IntegerField(_('祖籍ID'),blank=True,null=True)
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING,blank=True,null=True)
    brand_name = models.CharField(_('品牌名称'),max_length=100)
    brand_level_name = models.CharField(_('品牌等级名称'),max_length=100)

    reset_tm = models.DateTimeField(_('重置时间'), blank=True, null=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)
    
    class Meta:
        verbose_name = _('经销商等级记录')
        verbose_name_plural = _('经销商等级记录')




#销售任务考核
class Sale_Task(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    name = models.CharField(_('销售任务名称'),max_length=100)
    start_tm = models.DateField(_('开始时间'), blank=True, null=True)
    end_tm = models.DateField(_('结束时间'), blank=True, null=True)
    finish_percent = models.DecimalField(_('完成进度'), max_digits=10, decimal_places=4, blank=True, null=True, default=0)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True,default='')
    is_active = models.BooleanField(_('是否激活'), default=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)
    last_update_tm = models.DateTimeField(_('最后更新时间'), auto_now_add=True, blank=True, null=True)
    class Meta:
        verbose_name = _('销售任务考核')
        verbose_name_plural = _('销售任务考核')

#销售任务分配
class Sale_Task_Allocate(models.Model):
    sale_task = models.ForeignKey(Sale_Task, verbose_name=_('任务'), on_delete=models.CASCADE)
    company = models.ForeignKey(Company,related_name='company_company', verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    agent = models.ForeignKey(Company,related_name='company_agent', verbose_name=_('经销商'), on_delete=models.DO_NOTHING)
    sale_money = models.DecimalField(_('任务销售额度'),blank=True,null=True,max_digits=10,decimal_places=2,default=0)
    sold_money = models.DecimalField(_('已销售金额'),blank=True,null=True,max_digits=10,decimal_places=2,default=0)
    finish_percent = models.DecimalField(_('完成进度'), max_digits=10, decimal_places=4, blank=True, null=True, default=0)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True,default='')
    is_active = models.BooleanField(_('是否激活'), default=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)
    last_update_tm = models.DateTimeField(_('最后更新时间'), auto_now_add=True, blank=True, null=True)
    allocate_type=models.SmallIntegerField(_('任务类型'),choices=(
        (0,_('按销售金额')),
        (1, _('按销售数量')), ),default=0)    
    class Meta:
        verbose_name = _('销售任务分配')
        verbose_name_plural = _('销售任务分配')


#销售任务分配产品
class Sale_Task_Allocate_Products(models.Model): 
    sale_task_allocate = models.ForeignKey(Sale_Task_Allocate, verbose_name=_('任务分配'), on_delete=models.CASCADE)
    agent = models.ForeignKey(Company, verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    product = models.ForeignKey('product.Product', verbose_name=_('产品'), on_delete=models.CASCADE)
    num = models.IntegerField(_('产品数量'),blank=True,null=True)
    sale_num = models.IntegerField(_('已销售数量'),default=0)
    class Meta:
        verbose_name = _('销售任务分配产品')
        verbose_name_plural = _('销售任务分配产品')

#新闻咨询
class News(models.Model):
    company = models.ForeignKey(Company,verbose_name=_('公司'), on_delete=models.DO_NOTHING)
    news_from = models.CharField(_('来源'), max_length=300)
    subtitle = models.CharField(_('大标题'), max_length=300)
    desc = models.CharField(_('描述'), max_length=500)
    poster = models.ImageField(
        _('导图'), upload_to=company_upload_page_poster, blank=True, null=True)
    content = models.CharField(_('新闻内容'), max_length=10000)
    is_active = models.BooleanField(_('是否激活'), default=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True,default='')
    pub_date = models.DateField(_('文章时间'))
    tm = models.DateTimeField(_('添加时间'), auto_now_add=True)

    class Meta:
        verbose_name = _('新闻资讯')
        verbose_name_plural = _('新闻资讯')


# 页面轮播图管理
class Page_Banners(models.Model):
    company = models.ForeignKey(Company, verbose_name=_(
        '公司名称'), on_delete=models.DO_NOTHING)
    image = models.ImageField(
        _('轮播图'), upload_to=company_upload_page_banners, blank=True, null=True)
    sort_id = models.SmallIntegerField(_('排序'), blank=True, null=True, default=0)
    is_active = models.BooleanField(
        _('是否激活'), blank=False, null=False, default=True)
    tm = models.DateTimeField(_('添加时间'), auto_now_add=True)

    class Meta:
        verbose_name = _('轮播图管理')
        verbose_name_plural = _('轮播图管理')


class WxWalletStatus(models.Model):
    sn=models.SmallIntegerField(_('状态值'))
    name=models.CharField(_('状态名称'),max_length=30)    
    remark=models.CharField(_('备注说明'),max_length=50,blank=True,null=True)

    class Meta:
        verbose_name = _('微信钱包绑定申请状态')
        verbose_name_plural = _('微信钱包绑定申请状态')

#2021-02-05
class ApplicationStatus(models.Model):
    company_id=models.IntegerField(_('企业名称'), blank=True,null=True)
    sn=models.SmallIntegerField(_('状态值'),blank=True,null=True)
    name=models.CharField(_('状态名'),max_length=50)
    remark=models.CharField(_('备注说明'),max_length=50,blank=True,null=True)

    class Meta:
        verbose_name = _('申请状态')
        verbose_name_plural = _('申请状态')



#2021-02-18 此model将被删除
#class BankInfo(models.Model):
#    ancestor_id=models.IntegerField(_('族系'), db_index=True)
#    company = models.OneToOneField(Company,verbose_name=_('经销商'),  related_name='bankinfo_company',on_delete=models.CASCADE) 
#    bank_name=models.CharField(_('收款行名称'),max_length=50)
#    bank_account=models.CharField(_('收款行帐号'),max_length=50)    
#    payee=models.CharField(_('收款人'),max_length=50)   
#    tm = models.DateTimeField(_('添加时间'), auto_now_add=True)   
#    tm_edit=models.DateTimeField(_('修改时间'), auto_now=True)
#    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)
#    #status_id=models.IntegerField(_('当前状态'),default=1,null=True,blank=True)
#    status=models.ForeignKey(ApplicationStatus,verbose_name=_('当前状态'),default=1,on_delete=models.SET_NULL,null=True,blank=True)

#    class Meta:
#        verbose_name = _('经销商银行卡绑定')
#        verbose_name_plural = _('经销商银行卡绑定')


class DeliveryAddress(models.Model):
    ancestor_id=models.IntegerField(_('族系'), db_index=True)
    company_id = models.IntegerField(_('经销商ID') )
    cellphone=models.CharField(_('手机号码'),max_length=20,blank=True,null=True)
    receiver=models.CharField(_('收货人'),max_length=20,blank=True,null=True)
    address=models.CharField(_('收货地址'),max_length=100,blank=True,null=True)
    is_default=models.BooleanField(_('默认账号'),default=False)    
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = _('经销商货返收货地址')
        verbose_name_plural = _('经销商货返收货地址')




class WxWalletApplication(models.Model):
    ancestor_id=models.IntegerField(_('族系'), db_index=True)
    company_id = models.IntegerField(_('经销商ID'), db_index=True)
    user_id=models.IntegerField(_('申请人'),db_index=True,blank=True,null=True)    
    wxopenid_id=models.IntegerField(_('申请人微信openid_id'),blank=True,null=True)
    nickname = models.CharField(_('申请人微信昵称'), max_length=100, db_index=True,blank=True,null=True)
    headimgurl = models.CharField(_('申请人微信头像'), max_length=400,blank=True,null=True)      
    status_id=models.IntegerField(_('状态ID'),db_index=True,default=1)
    payee_company=models.ForeignKey(Company,verbose_name=_('收款人wxopenid'),related_name='wxwalletapp_company',on_delete=models.CASCADE,blank=True,null=True)
    payee_wxopenid=models.ForeignKey(WxOpenid,verbose_name=_('收款人wxopenid'),on_delete=models.CASCADE)
    realname=models.CharField(_('实名制收款人'),max_length=30,blank=True,null=True) 
    cellphone=models.CharField(_('手机号码'),max_length=20,blank=True,null=True)     
    tm = models.DateTimeField(_('时间'), auto_now_add=True)   
    dt = models.DateField(_('日期'), auto_now_add=True,db_index=True)  
    remark = models.CharField(_('备注'), max_length=100, blank=True, null=True)


    #这些字段要删除
    #wxwallet=models.ForeignKey(WxWallet,verbose_name=_('经销商微信钱包'),on_delete=models.CASCADE,blank=True,null=True)
    wxwallet_id=models.IntegerField(_('经销商微信钱包'),blank=True,null=True)
    app_company=models.ForeignKey(Company,verbose_name=_('申请经销商'),on_delete=models.CASCADE,blank=True,null=True)
    app_user=models.ForeignKey(User,verbose_name=('申请人'),on_delete=models.CASCADE,blank=True,null=True)
    app_wxopenid_id=models.IntegerField(_('申请人微信openid_id'),blank=True,null=True)
    app_nickname = models.CharField(_('申请人微信昵称'), max_length=100, db_index=True,blank=True,null=True)
    app_headimgurl = models.CharField(_('申请人微信头像'), max_length=400,blank=True,null=True) 
    priority=models.SmallIntegerField(_('优先支付方式'),choices=((1,'微信支付'),(2,'银行转帐')),default=1,blank=True,null=True)  
    bank_name=models.CharField(_('收款行名称'),max_length=50,blank=True,null=True)
    bank_account=models.CharField(_('收款行帐号'),max_length=50,blank=True,null=True)   

    class Meta:
        verbose_name = _('微信钱包申请')
        verbose_name_plural = _('微信钱包申请')


class WxWallet(models.Model):
    ancestor_id=models.IntegerField(_('族系'), db_index=True)
    company =models.ForeignKey(Company,verbose_name=_('经销商'),related_name='wxwallet_company', on_delete=models.CASCADE)
    wxopenid=models.ForeignKey(WxOpenid,verbose_name=_('收款人wxopenid'),on_delete=models.CASCADE)
    cellphone=models.CharField(_('手机号码'),max_length=20,blank=True,null=True)
    realname=models.CharField(_('微信实名制收款人'),max_length=30) 
    tm = models.DateTimeField(_('添加时间'), auto_now_add=True)
    tm_edit=models.DateTimeField(_('修改时间'), auto_now=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)    
    application=models.OneToOneField(WxWalletApplication,verbose_name=_('微信钱包申请'),on_delete=models.CASCADE)  

    class Meta:
        verbose_name = _('经销商微信钱包绑定')
        verbose_name_plural = _('经销商微信钱包绑定')
        unique_together=('ancestor_id','company')



class BankInfoApplication(models.Model):
    ancestor_id=models.IntegerField(_('族系'), db_index=True)        
    company_id=models.IntegerField(_('申请经销商'),db_index=True)
    user_id=models.IntegerField(_('申请人'),db_index=True)    
    wxopenid_id=models.IntegerField(_('申请人微信openid_id'),blank=True,null=True)
    nickname = models.CharField(_('申请人微信昵称'), max_length=100, db_index=True,blank=True,null=True)
    headimgurl = models.CharField(_('申请人微信头像'), max_length=400,blank=True,null=True)     
    tm = models.DateTimeField(_('时间'), auto_now_add=True)   
    dt = models.DateField(_('日期'), auto_now_add=True,db_index=True)  
    remark = models.CharField(_('备注'), max_length=100, blank=True, null=True)    
    status_id=models.IntegerField(_('当前状态ID'),db_index=True,default=1)    
    payee_company=models.ForeignKey(Company,verbose_name=_('收款人wxopenid'),related_name='bankinfoapp_company',on_delete=models.CASCADE,blank=True,null=True)
    bank_name=models.CharField(_('收款行名称'),max_length=50)
    bank_account=models.CharField(_('收款行帐号'),max_length=50)  
    payee=models.CharField(_('收款人'),max_length=50)
    

    class Meta:
        verbose_name = _('银行卡绑定申请')
        verbose_name_plural = _('银行卡绑定申请')
        #unique_together=('ancestor_id','company_id')


#2021-02-18
class BankInfo(models.Model):
    ancestor_id=models.IntegerField(_('族系'), db_index=True)
    company=models.ForeignKey(Company,verbose_name=_('经销商'),related_name='bankinfors_company',on_delete=models.CASCADE)
    application=models.OneToOneField(BankInfoApplication,verbose_name=_('银行卡绑定申请'),on_delete=models.CASCADE)    
    bank_name=models.CharField(_('收款行名称'),max_length=50)
    bank_account=models.CharField(_('收款行帐号'),max_length=50)  
    payee=models.CharField(_('收款人'),max_length=50)
    is_default=models.BooleanField(_('默认账号'),default=False)    
    tm = models.DateTimeField(_('时间'), auto_now=True)
    
    class Meta:
        verbose_name = _('银行卡信息')
        verbose_name_plural = _('银行卡信息')
        #unique_together=('ancestor_id','company_id')


#class WxWalletReview(models.Model):
#    ancestor_id=models.IntegerField(_('族系'), db_index=True)
#    application=models.ForeignKey(WxWalletApplication,verbose_name=_('微信钱包申请'),on_delete=models.CASCADE)
#    user=models.ForeignKey(User,verbose_name=('审核人'),on_delete=models.CASCADE,related_name='wxwalletreview_user')
#    comment=models.CharField(_('审核意见'),max_length=100,blank=True,null=True)
#    tm = models.DateTimeField(_('时间'), auto_now_add=True)    
#    remark = models.CharField(_('备注'), max_length=100, blank=True, null=True)

#    class Meta:
#        verbose_name = _('微信钱包审核')
#        verbose_name_plural = _('微信钱包审核')


class ApplicationReviewLog(models.Model):    
    company_id = models.IntegerField(_('公司ID'), db_index=True)
    content_type=models.CharField(_('django_content_type'), max_length=50, db_index=True)
    obj_id=models.IntegerField(_('审核对象ID'),db_index=True)
    status_id=models.IntegerField(_('状态ID'),db_index=True)
    user_id=models.IntegerField(_('审核人'))
    comment=models.CharField(_('审核意见'),max_length=100,blank=True,null=True)
    dt=models.DateField(_('日期'),auto_now_add=True,db_index=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)   

    class Meta:
        verbose_name = _('公司审核事项日志')
        verbose_name_plural = _('公司审核事项日志')
        index_together = ["company_id","content_type", "obj_id","status_id"]


# 客户留言
class Leave_Message(models.Model): 
    company = models.ForeignKey(Company, verbose_name=_(
        '公司名称'), on_delete=models.CASCADE)
    consumer = models.ForeignKey('sales.ConsumerAccount', verbose_name=_(
        '消费者账号'), on_delete=models.SET_NULL, null=True,blank=True)
    subject = models.CharField(_('主题'),blank=True,null=True,max_length=200)
    name = models.CharField(_('用户姓名'),blank=True,null=True,max_length=50)
    tel = models.CharField(_('用户电话'),blank=True,null=True,max_length=20)
    address = models.CharField(_('用户地址'),blank=True,null=True,max_length=300)
    message =  models.CharField(_('留言信息'),blank=True,null=True,max_length=1000)
    leave_date = models.DateField(_('留言日期'),auto_now_add=True)
    tm =  models.DateTimeField(_('提交信息'), auto_now_add=True) 
    
    class Meta:
        verbose_name = _('客户留言')
        verbose_name_plural = _('客户留言')


#2021-02-24
class BulletinBoard(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('企业名称'), on_delete=models.CASCADE)    
    user=models.ForeignKey(User,verbose_name=_('创建人'),on_delete=models.SET_NULL,null=True)
    subject = models.CharField(_('标题摘要'),max_length=200)
    content=models.TextField(_('内容'),max_length=50000,blank=True,null=True) 
    category=models.SmallIntegerField(_('类别'),choices=((0,'公共信息'),(1,'政策文件'),(2,'系统消息'),(3,'其它')),default=0)
    scope=models.SmallIntegerField(_('发布对象'),choices=((0,'所有人'),(1,'公司内部'),(2,'经销商')),default=0)
    salesdivisions =models.JSONField(_('指定战区'),default=list,blank=True,null=True)
    is_active=models.BooleanField(_('是否激活'),default=True)
    dt=models.DateField(_('创建日期'),auto_now_add=True,db_index=True)
    tm=models.DateTimeField(_('创建时间'),auto_now_add=True)  
    tm_edit=models.DateTimeField(_('修改时间'),auto_now=True) 
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)

    class Meta:
        verbose_name = _('公告信息')
        verbose_name_plural = _('公告信息')


class BulletinBoardAttach(models.Model):
    def upload_to(instance, filename):
        return '/'.join([instance.bulletinboard.company.name,'bulletinboard', filename])
    bulletinboard=models.ForeignKey(BulletinBoard,verbose_name=_('公告信息'),on_delete=models.CASCADE)
    attachment=models.FileField(upload_to=upload_to,verbose_name=_('附件'))
    
    class Meta:
        verbose_name=_('公告信息通知附件')
        verbose_name_plural=_('公告信息通知附件')    

    def get_name(self):
        return self.attachment.name.split("/")[-1]


class BBSreader(models.Model):
    bulletinboard=models.ForeignKey(BulletinBoard,verbose_name=_('公告信息'),on_delete=models.CASCADE)
    user_id=models.IntegerField(_('帐号ID'))
    dt=models.DateField(_('创建日期'),auto_now_add=True,db_index=True)
    tm=models.DateTimeField(_('创建时间'),auto_now_add=True)  
    
    class Meta:
        unique_together = ('bulletinboard', 'user_id')
        verbose_name=_('公告信息读取记录')
        verbose_name_plural=_('公告信息读取记录')


class BBSdelete(models.Model):
    bulletinboard=models.ForeignKey(BulletinBoard,verbose_name=_('公告信息'),on_delete=models.CASCADE)
    user_id=models.IntegerField(_('帐号ID'))
    dt=models.DateField(_('创建日期'),auto_now_add=True,db_index=True)
    tm=models.DateTimeField(_('创建时间'),auto_now_add=True)  
    
    class Meta:
        unique_together = ('bulletinboard', 'user_id')
        verbose_name=_('公告信息删除记录')
        verbose_name_plural=_('公告信息删除记录')


class BBSfeedback(models.Model):
    bulletinboard=models.ForeignKey(BulletinBoard,verbose_name=_('公告信息'),on_delete=models.CASCADE)
    user_id=models.IntegerField(_('帐号ID'))
    comment=models.TextField(max_length=10000)
    is_active=models.BooleanField(_('是否激活'),default=True)
    dt=models.DateField(_('创建日期'),auto_now_add=True,db_index=True)
    tm=models.DateTimeField(_('创建时间'),auto_now_add=True)  
    
    class Meta:
        verbose_name=_('公告信息意见反馈')
        verbose_name_plural=_('公告信息意见反馈')


class BBSfeedbackAttach(models.Model):
    def upload_to(instance, filename):
        return '/'.join([instance.bulletinboard.company.name,'bulletinboard','feedback', filename])
    bsfeedback=models.ForeignKey(BBSfeedback,verbose_name=_('公告信息意见反馈'),on_delete=models.CASCADE)
    attachment=models.FileField(upload_to=upload_to,verbose_name=_('附件'))
    
    class Meta:
        verbose_name=_('公告意见反馈附件')
        verbose_name_plural=_('公告意见反馈附件')    



#2021-07-08
class Salesman(models.Model):
    company=models.ForeignKey(Company,verbose_name=_('所属企业'),related_name="salesman_company",on_delete=models.CASCADE)   
    agent=models.ManyToManyField(Company,verbose_name=_('经销商'))
    staff=models.ManyToManyField(Staff,verbose_name=_('业务员'))
    tm = models.DateTimeField(_('时间'), auto_now_add=True)  

    class Meta:
        verbose_name=_('业务员经销商')
        verbose_name_plural=_('业务员经销商') 


#2021-07-15
class CompanyDiv(models.Model):
    company=models.ForeignKey(Company,verbose_name=_('所属企业'),related_name="companydiv_company",on_delete=models.CASCADE)   
    div_name=models.CharField(_('一级区域名'),max_length=50)
    subdiv_name=models.CharField(_('二级区域名'),max_length=50,blank=True,null=True)

    class Meta:
        verbose_name=_('营销区域/客户分类名称')
        verbose_name_plural=_('营销区域/客户分类名称') 


#class Franchise(models.Model):
#    ancestor_id=models.IntegerField(_('所属企业'))
#    company=models.ForeignKey('company.Company',verbose_name=_('所属加盟商'),related_name="franchise_company",on_delete=models.CASCADE)
#    series=models.ForeignKey('product.Series',verbose_name=_('授权品牌'),related_name='franchise_series',blank=True,null=True,on_delete=models.CASCADE)
#    prdduct=models.ForeignKey('product.Product',verbose_name=_('授权产品'),blank=True,null=True,on_delete=models.CASCADE)
#    level = models.ForeignKey(Level, verbose_name=_('营销层级'), related_name='franchise_level',on_delete=models.CASCADE, blank=True, null=True)
#    name=models.CharField(_('分店名称'),max_length=100)  
#    province_gis_id = models.IntegerField(_('GIS省份ID'), blank=True, null=True)   
#    city_gis_id = models.IntegerField(_('GIS城市ID'), blank=True, null=True)   
#    county_gis_id = models.IntegerField(_('GIS县区ID'), blank=True, null=True)
#    lng_lat=ArrayField(models.DecimalField(_('经纬度'),max_digits=12,decimal_places=8),blank=True,null=True)
#    address=models.CharField(_('详细地址'),max_length=100,blank=True,null=True)
#    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)


#    class Meta:
#        verbose_name=_('加盟商分店信息')
#        verbose_name_plural=_('加盟商分店信息') 


class Outlet(models.Model):
    ancestor_id=models.IntegerField(_('所属企业'),blank=True,null=True)
    company=models.ForeignKey('company.Company',verbose_name=_('所属加盟商'),related_name="outlet_company",on_delete=models.CASCADE)
    series=models.ForeignKey('product.Series',verbose_name=_('授权品牌'),related_name='outlet_series',blank=True,null=True,on_delete=models.CASCADE)
    prdduct=models.ForeignKey('product.Product',verbose_name=_('授权产品'),blank=True,null=True,on_delete=models.CASCADE)
    level = models.ForeignKey(Level, verbose_name=_('营销层级'),related_name='outlet_level',on_delete=models.CASCADE, blank=True, null=True)
    status=models.ForeignKey(OutletStatus,verbose_name=_('门店状'),on_delete=models.CASCADE,blank=True,null=True)
    name=models.CharField(_('分店名称'),max_length=100)  
    province_gis = models.JSONField(_('GIS省份'), blank=True,null=True,default=dict)   
    city_gis = models.JSONField(_('GIS城市'), blank=True,null=True,default=dict)   
    county_gis = models.JSONField(_('GIS县区'), blank=True,null=True,default=dict)
    lng_lat=ArrayField(models.DecimalField(_('经纬度'),max_digits=12,decimal_places=8),blank=True,null=True)
    address=models.CharField(_('详细地址'),max_length=100,blank=True,null=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)
    create_by=models.ForeignKey(User,verbose_name=_('创建人'),related_name='outlet_create',on_delete=models.CASCADE,blank=True,null=True)
    create_tm=models.DateTimeField(_('创建时间'),blank=True,null=True,auto_now_add=True)
    edit_by=models.ForeignKey(User,verbose_name=_('修改人'),related_name='outlet_edit',on_delete=models.CASCADE,blank=True,null=True)
    edit_tm=models.DateTimeField(_('修改时间'),blank=True,null=True)
    approve_by=models.ForeignKey(User,verbose_name=_('审核人'),related_name='outlet_approve',on_delete=models.CASCADE,blank=True,null=True)
    approve_tm=models.DateTimeField(_('审核时间'),blank=True,null=True)
    qry_teacher=models.CharField(_('查询老师'),max_length=20,blank=True,null=True)
    qry_time=models.DateTimeField(_('首查时间'),blank=True,null=True)
    contacts=models.CharField(_('联系人'),max_length=20,blank=True,null=True)
    position=models.CharField(_('职位'),max_length=50,blank=True,null=True)

    is_active = models.BooleanField(_('是否已激活'), default=True)
    is_delete = models.BooleanField(_('是否已删除'), default=False)


    #franchise_query=models.JSONField(_('首查信息'),blank=True,null=True,default=dict)
    #title=models.CharField(_('职位'),max_length=50,blank=True,null=True)
     
    class Meta:
        verbose_name=_('加盟商分店信息')
        verbose_name_plural=_('加盟商分店信息') 
        ordering=['name'] 


    def save(self, *args, **kwargs):
        pk=self.pk
        if self.company:            
            self.ancestor_id=self.company.ancestor_id
            # 保存销售层级
            if self.company.level and not self.level:
                ls = Level.objects.filter(sn=(self.company.level.sn+1))
                if ls:
                    self.level = ls[0]
        super(Outlet, self).save(*args, **kwargs)      

        #2021-09-03 易臻新建门店时，要求其加盟商编码前加000
        #if not pk and self.ancestor_id==19267:
        #    c=self.company
        #    code=c.external_code
        #    if len(code.split('_'))==1:                
        #        c.external_code='000_'+code
        #        c.save()

# 
class UserSharethings(models.Model):
    name=models.CharField(_('名称'),max_length=100)  
    sharethings = models.CharField(_('共享内容'),max_length=100,blank=True,null=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)
    tm = models.DateTimeField(_('创建时间'), auto_now_add=True)
    
    class Meta:
        verbose_name = _('共享内容')
        verbose_name_plural = _('共享内容')


class UserShareGroup(models.Model):
    company = models.ForeignKey(Company,verbose_name=_('企业名称'), on_delete=models.CASCADE)
    name=models.CharField(_('共享小组名称'),max_length=100)  
    user_ids = ArrayField(models.IntegerField(),verbose_name=_('用户帐号'), blank=True,null=True)
    sharethings = ArrayField(models.IntegerField(),verbose_name=_('分享内容'), blank=True,null=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)
    tm = models.DateTimeField(_('创建时间'), auto_now_add=True)
    
    class Meta:
        verbose_name = _('共享人员')
        verbose_name_plural = _('共享人员')

class UserLoginHistory(models.Model):
    company=models.ForeignKey(Company, verbose_name=_('企业名称'), on_delete=models.CASCADE)
    user=models.ForeignKey(User,verbose_name=_('操作人'),on_delete=models.CASCADE)
    openid=models.CharField(_('openid'),max_length=50,blank=True,null=True)
    ip=models.CharField(_('ip'),max_length=20,blank=True,null=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)

    class Meta:
        verbose_name = _('登录历史')
        verbose_name_plural = _('登录历史')




#2022-05-06 今后企业设置，使用以下关系表
class Configure(models.Model):
    module=models.CharField(_('所属模块'),max_length=50)
    module_name=models.CharField(_('模块名称'),max_length=50,blank=True,null=True)
    code=models.CharField(_('代码'),max_length=40,unique=True)
    name=models.CharField(_('名称'),max_length=50)
    options=models.JSONField(default=dict,blank=True,null=True)

    class Meta:
        verbose_name=_('企业配置项')
        verbose_name_plural=_('企业配置项')


class ConfigureOption(models.Model):
    configure=models.ForeignKey(Configure,verbose_name=_('企业配置项'),related_name='configureoption_configure',on_delete=models.CASCADE)
    option=models.CharField(_('选项'),max_length=50)

    class Meta:
        verbose_name=_('配置选项')
        verbose_name_plural=_('配置选项')


class CompanyCfgOpt(models.Model):
    company=models.ForeignKey(Company,verbose_name=_('企业'),related_name='companycfgopt_company',on_delete=models.CASCADE)
    configure=models.ForeignKey(Configure,verbose_name=_('配置项'),related_name='companycfgopt_configure',on_delete=models.CASCADE)
    option=models.ForeignKey(ConfigureOption,verbose_name=_('选项'),related_name='companycfgopt_option',on_delete=models.CASCADE)    

    class Meta:
        unique_together = ('company', 'configure')
        verbose_name=_('企业设置')
        verbose_name_plural=_('企业设置')


class CGroupCfgOpt(models.Model):
    company=models.ForeignKey(Company,verbose_name=_('所属企业'),related_name='cgroupcfgopt_company',on_delete=models.CASCADE)
    cgroup=models.ForeignKey(CGroup,verbose_name=_('企业功能组'),related_name='cgroupcfgopt_cgroup',on_delete=models.CASCADE)
    configure=models.ForeignKey(Configure,verbose_name=_('配置项'),related_name='cgroupcfgopt_configure',on_delete=models.CASCADE)
    values=models.JSONField(_('选项值集合'),default=list,blank=True,null=True)    

    class Meta:
        unique_together = ('cgroup', 'configure')
        verbose_name=_('企业功能组设置')
        verbose_name_plural=_('企业功能组设置')


class UserCfgOpt(models.Model):
    company=models.ForeignKey(Company,verbose_name=_('所属企业'),related_name='usercfgopt_company',on_delete=models.CASCADE)
    user=models.ForeignKey(User,verbose_name=_('用户帐号'),related_name='usercfgopt_user',on_delete=models.CASCADE)
    configure=models.ForeignKey(Configure,verbose_name=_('配置项'),related_name='usercfgopt_configure',on_delete=models.CASCADE)
    value=models.JSONField(_('选项'),default=dict,blank=True,null=True)    

    class Meta:
        unique_together = ('user', 'configure')
        verbose_name=_('用户设置')
        verbose_name_plural=_('用户设置')
        
class FileCategory(models.Model):
    name=models.CharField(_('名称'),max_length=50)

    class Meta:
        verbose_name=_('文件类型')
        verbose_name_plural=_('文件类型')
    def __str__(self):
        return self.name


class UploadFiles(models.Model):
    company=models.ForeignKey(Company,verbose_name=_('所属企业'),on_delete=models.CASCADE)
    media_type=models.SmallIntegerField(_('文件类型'),choices=((1,'图片'),(2,'文件')),default=1)
    category=models.ForeignKey(FileCategory,verbose_name=_('所属分类'),on_delete=models.CASCADE)
    url=models.CharField(_('文件地址'),max_length=400)
    remark=models.CharField(_('备注'),max_length=50,blank=True,null=True)
    class Meta:
        verbose_name=_('上传文件')
        verbose_name_plural=_('上传文件')
    
class UserWechatOpenids(models.Model):
    company=models.ForeignKey(Company,verbose_name=_('所属企业'),on_delete=models.CASCADE)
    user=models.ForeignKey(User,verbose_name=_('用户帐号'),on_delete=models.CASCADE)
    wx_account_id=models.IntegerField(_('所属微信公众号'),blank=True,null=True)
    openid=models.CharField(_('openid'),max_length=50,blank=True,null=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    
    class Meta:
        verbose_name=_('用户微信绑定表')
        verbose_name_plural=_('用户微信绑定表')



# 2022-11-16
class OperationLog(models.Model):
    '''
    model或自建表(非model创建) 修改/删除操作日志
    云平台先放company下，restful-api要放在system下
    '''    
    company=models.ForeignKey(Company,verbose_name=_('所属企业'),on_delete=models.CASCADE,related_name='operationlog_company')
    contenttype=models.ForeignKey(ContentType,verbose_name=_('对像/表名'),blank=True,null=True,on_delete=models.CASCADE,related_name='operationlog_contenttype')
    object_id = models.IntegerField(verbose_name='实例ID',blank=True,null=True)  
    # 快速实现content_type操作 ,快速插入数据 不生成数据库中的字段 
    content_object = GenericForeignKey('contenttype','object_id')
    # 自建表
    tb_name=models.CharField(_('自建表名称'),max_length=50,blank=True,null=True)
    action=models.SmallIntegerField(_('操作类型'),choices=( (1,_('修改')),  (2,_('删除')) ))
    user=models.ForeignKey(User,verbose_name=_('操作人'),on_delete=models.CASCADE,related_name='operationlog_user')  
    #修改 字段(名):{'old':旧值,'new':新值}   
    #删除：{"data":{当前数据记录格式如{字段1:v1,字段2:v2,字段3:v3...},"details":[与当前记录关联的子记录明细{字段1:v1,字段2:v2,字段3:v3...},{...}]}  一般只打删除标记，不做物理删除  
    changes=models.JSONField(_('修改内容'),default=list)    
    dt=models.DateField(_('日期'),auto_now_add=True,db_index=True)
    tm=models.DateTimeField(_('时间'),auto_now_add=True)

    class Meta:
        verbose_name=_('修改删除操作日志')
        verbose_name_plural=_('修改删除操作日志')



# 2022-11-23 
class BonusPoints(models.Model):
    '''
    云平台渠道促销经销商积分表，适用于非期结性、可随时兑换、实时反映经销商当前积分的情况
    '''    
    ancestor_id=models.IntegerField(_('所属族系'),blank=True,null=True)
    company=models.OneToOneField(Company,verbose_name=_('所属公司'),related_name='bonuspoints_company',on_delete=models.CASCADE)    
    points=models.DecimalField(_('当前积分值'), max_digits=12, decimal_places=2,blank=True,null=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)
    tm=models.DateTimeField(_('更新时间'),auto_now =True)
    
    channelpromotions = models.ForeignKey('sales.ChannelPromotions', verbose_name=_('所属渠道返利'),
                                          on_delete=models.CASCADE,related_name='bonuspointslog_ChannelPromotions',
                                          blank=True, null=True)
    
                                          
    class Meta:
        verbose_name=_('渠道促销经销商积分')
        verbose_name_plural=_('渠道促销经销商积分')


class BonusPointsLog(models.Model):
    '''
    云平台用户积分变化记录表，记录用户每一次积分变化及获取积分的明细
    '''
    # 冗余，为提高查询速度
    ancestor_id=models.IntegerField(_('所属族系'),blank=True,null=True)
    company=models.ForeignKey(Company,verbose_name=_('所属公司'),related_name='bonuspointslog_company',on_delete=models.CASCADE)
    user=models.ForeignKey(User,verbose_name=_('用户帐号'),on_delete=models.CASCADE,related_name='bonuspointslog_user')
    channelpromotions=models.ForeignKey('sales.ChannelPromotions',verbose_name=_('所属渠道返利'),on_delete=models.CASCADE,related_name='bonuspointslog_activity',blank=True,null=True)
    # 触发积分变化的对像源，如收货确认由终端入库inventory.Batch，宴会申请banquet.Apply 触发
    contenttype = models.ForeignKey(ContentType, verbose_name='实例对像',on_delete=models.CASCADE,blank=True,null=True) 
    # 触发积分变化的对像实例，如batch.id, apply.id
    object_id = models.IntegerField(verbose_name='实例ID',blank=True,null=True) 
    # 快速实现content_type操作,快速插入数据 不会生成数据库表中的字段
    content_object = GenericForeignKey('contenttype', 'object_id')      
    
    # 启用事务，将当前变化值实时反映到BonusPoints用户积分
    self_points = models.DecimalField(_('确认收货方积分值'), max_digits=12, decimal_places=2, blank=True, null=True)
    parent_points = models.JSONField(_('经济发货方积分值'), default=list, blank=True, null=True)

    dt=models.DateField(_('日期'),auto_now_add=True,db_index=True)
    tm=models.DateTimeField(_('时间'),auto_now_add=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)

    class Meta:
        verbose_name=_('用户积分日志')
        verbose_name_plural=_('用户积分日志')


class PointsLogDetails(models.Model):
    '''
    云平台积分变化物流标签明细表
    '''
    # 冗余，为提高查询速度
    ancestor_id=models.IntegerField(_('所属族系'),blank=True,null=True)
    # 冗余，为提高查询速度
    company=models.ForeignKey(Company,verbose_name=_('所属公司'),on_delete=models.CASCADE,related_name='pointslogdetails_company')
    # 冗余，为提高查询速度
    user=models.ForeignKey(User,verbose_name=_('用户帐号'),on_delete=models.CASCADE,related_name='pointslogdetails_user')
    # 冗余，为提高查询速度
    channelpromotions=models.ForeignKey('sales.ChannelPromotions',verbose_name=_('所属渠道返利'),on_delete=models.CASCADE,related_name='pointslogdetails_activity',blank=True,null=True)
    log=models.ForeignKey(BonusPointsLog,verbose_name=_('所属积分日志'),on_delete=models.CASCADE)
    label_code = models.CharField(_('标签号码'), max_length=20, db_index=True)
    label_id = models.BigIntegerField(_('标签ID'),  db_index=True)
    label_pk_id = models.BigIntegerField(_('标签PKID'), db_index=True)
    label_pkg = models.SmallIntegerField(_('标签类型'), db_index=True)
    self_points = models.DecimalField(_('自身积分值'), max_digits=12, decimal_places=2,default=0)
    parent_points = models.DecimalField(_('顶级发货商积分值'),max_digits=12, decimal_places=2,default=0) 
    dt=models.DateField(_('日期'),auto_now_add=True,db_index=True)
    tm=models.DateTimeField(_('时间'),auto_now_add=True)
    company_fr_id = models.IntegerField(_("顶级发货经销商"),blank=True,null=True)

    err = models.CharField(_('错误信息'), max_length=100, blank=True, null=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)


    class Meta:
        verbose_name=_('积分物流标签明细')
        verbose_name_plural=_('积分物流标签明细')



class PointsRedeemed(models.Model):    
    ancestor_id=models.IntegerField(_('所属族系'),blank=True,null=True)
    company=models.ForeignKey(Company,verbose_name=_('所属公司'),on_delete=models.CASCADE,related_name='pointsredeem_company')    
    user=models.ForeignKey(User,verbose_name=_('用户帐号'),on_delete=models.CASCADE,related_name='pointsredeem_user')
    
    # 启用事务，将当前兑换值 实时反映到BonusPoints用户积分
    points=models.DecimalField(_('兑换积分值'), max_digits=12, decimal_places=2)     
    # 可能兑换成现金/微信零钱
    amount=models.DecimalField(_('金额'), max_digits=12, decimal_places=2,blank=True,null=True)   
    payment_method=models.SmallIntegerField(_('付款方式'), default=1, choices=((1,'微信钱包'),(2,'银行卡'),(3,'货返')))
    invoice_needed=models.SmallIntegerField(_('是否开票'), default=0, choices=((1,'开票提现'),(0,'不开票提现')))    
    bank_receipt=models.CharField(_('银行/微信回单编号'),max_length=50,blank=True,null=True)
    # 也可能兑换礼品、卡券等奖项
    award=models.ForeignKey('sales.Award',verbose_name=_('兑换奖项'),on_delete=models.CASCADE,blank=True,null=True)
    qty=models.IntegerField(_('兑换奖项个数'), blank=True,null=True)

    dt=models.DateField(_('日期'),auto_now_add=True,db_index=True)
    tm=models.DateTimeField(_('时间'),auto_now_add=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)

    class Meta:
        verbose_name=_('积分兑换')
        verbose_name_plural=_('积分兑换')