# -*- 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
# from django.db.models.signals import post_save, post_delete
# from django.dispatch import receiver
# from django.contrib.auth.validators import UnicodeUsernameValidator

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])


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




#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


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)
    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)
    ctyid = models.IntegerField(_('CTID'), blank=True, null=True)
    external_code = models.CharField(_('外部编码'), max_length=30, blank=True, null=True, help_text=_('企业自有编码，如SAP编码'))
    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_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)
    gis_adm_id = models.IntegerField(_('GIS'), 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)
    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
            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]
            # 是否微商
            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
    

class CompanyCfg(models.Model):
    #company=models.ForeignKey(Company, verbose_name=_('公司名称'), unique=True, blank=True, null=True, related_name='cfg_company', on_delete=models.CASCADE)
    company=models.OneToOneField(Company, verbose_name=_('公司名称'), related_name='cfg_company', on_delete=models.CASCADE)
    tjfwbase_oauth=models.BooleanField(_('允许天鉴防伪微信静默授权'), default=True)
    tjfw_oauth=models.BooleanField(_('使用天鉴防伪微信公众号授权'), default=False)
    wx_account=models.ForeignKey('sales.WxOfficialAccounts',on_delete=models.CASCADE, verbose_name=_('微信公众号'),db_index=True,blank=True,null=True)
    product_photo=models.BooleanField(_('要求录入产品图片'), default=False, blank=True, null=True)
    product_price=models.BooleanField(_('要求录入产品价格'), default=False, blank=True, null=True)
    inv_mgt = models.BooleanField(_('库存管理'), default=True, blank=True, null=True)

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

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




'''
class CompanyCfg(models.Model):
    #company=models.ForeignKey(Company, verbose_name=_('公司名称'), unique=True, blank=True, null=True, related_name='cfg_company', on_delete=models.CASCADE)
    company=models.OneToOneField(Company, verbose_name=_('公司名称'), related_name='cfg_company', on_delete=models.CASCADE)
    tjfwbase_oauth=models.BooleanField(_('允许天鉴防伪微信静默授权'), default=True)
    tjfw_oauth=models.BooleanField(_('使用天鉴防伪微信公众号授权'), default=False)
    wx_account=models.ForeignKey('sales.WxOfficialAccounts',on_delete=models.CASCADE, verbose_name=_('微信公众号'),db_index=True,blank=True,null=True)
    
    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)
    inbound_lv1=models.SmallIntegerField(_('一级经销商自动入库'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=1)
   
    inbound_lv2=models.SmallIntegerField(_('允许一级经销商入库'),choices=(
        (0,_('否')),
        (1, _('是')), ),default=0)
    
    class Meta:
        verbose_name = _('公司基础设置')
        verbose_name_plural = _('公司基础设置')

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

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_account = models.CharField(_('微信号'), max_length=30, blank=True, null=True)
    wx_pub_account = models.CharField(_('微信公众号'), max_length=30, blank=True, null=True)
    wx_openid = models.CharField(_('微信OPENID'), max_length=50, blank=True, null=True)
    wx_unionid = models.CharField(_('微信UNIONID'), max_length=50, 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)
    pwd_changed = models.BooleanField(_('是否已修改密码'),default=False)
    tm = models.DateTimeField(_('时间'), auto_now_add=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.company:
            self.ancestor_id=self.company.ancestor_id

        #2020-04-05
        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 AuthorizedProducts(models.Model):
    company = models.ForeignKey(Company, verbose_name=_('经销商'), related_name='a_company', on_delete=models.CASCADE)
    product = models.ForeignKey('product.Product', verbose_name=_('产品'), related_name='a_product', on_delete=models.CASCADE)
    dt_from = models.DateField(_('授权开始日期'), blank=True, null=True)
    dt_to = models.DateField(_('授权结束日期'), blank=True, null=True)
    user = models.ForeignKey(User, verbose_name=_('授权操作人'), related_name='a_user', on_delete=models.CASCADE)
    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)
    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 = ('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)

    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)

    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)

    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, default=_('生产班组'), 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)

    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)
    remark=models.CharField(_('备注说明'),max_length=100,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=20)    
    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)

    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)
    qty=models.IntegerField(_('数量'))
    
    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 CfgOptions(models.Model):
    name=models.CharField(_('项目名称'),max_length=100,unique=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)      

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



class Configs(models.Model):
    company=models.ForeignKey(Company,verbose_name=_('公司名称'),related_name='cfg_company',on_delete=models.PROTECT)
    cfgoption=models.ForeignKey(CfgOptions,verbose_name=_('选项名称'),on_delete=models.PROTECT)
    active=models.BooleanField(_('是否启用'),default=True) 

    class Meta:
        verbose_name=_('公司选项设置')
        verbose_name_plural=_('公司选项设置')
'''
