from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.postgres.fields import ArrayField
#from django.contrib.postgres.fields.jsonb import JSONField as JSONBField

# Create your models here.
import random
import bisect
from django.db import connection
from django.conf import settings
import os
import hashlib

#2020-08-14
import datetime
from django.utils.timezone import now

#会员等级图像上传路径
def memberlever_img_upload(instance,filename):
    return os.path.join(instance.company.name,'memberlevel', filename)


#1:权重随机数抽奖
class WeightRandom(object):
    def __init__(self,items):
        weights = [w for _,w in items]
        self.awards=[x for x,_  in items]
        self.total=sum(weights)
        self.acc=list(self.accumulate(weights))

    def accumulate(self, weights):
        cur = 0
        for w in weights:
            cur = cur+w
            yield cur

    def draw(self):
        return self.awards[bisect.bisect_right(self.acc,random.uniform(0,self.total))]


class BugChanel(models.Model):
    company = models.ForeignKey('company.Company',verbose_name=_('公司名称'),on_delete=models.CASCADE,related_name='bugchanel_company')    
    hierarchy=models.ForeignKey('company.Company',verbose_name=_('体系'),on_delete=models.CASCADE,related_name='bugchanel_hierarchy')
    version=models.SmallIntegerField(_('版本'))
    ancestor =models.ForeignKey('company.Company',verbose_name=_('族系'),on_delete=models.CASCADE,related_name='bugchanel_ancestor')
    user = models.ForeignKey('company.User', verbose_name=_('操作员'),on_delete=models.CASCADE,blank=True,null=True)
    label_code=models.CharField(_('标签号码'),max_length=20)
    package_id=models.SmallIntegerField(_('包装'),blank=True,null=True)
    company_fr=models.ForeignKey('company.Company',verbose_name=_('发货公司'),on_delete=models.CASCADE,related_name='bugchanel_company_fr')
    company_to=models.ForeignKey('company.Company',verbose_name=_('目的公司'),on_delete=models.CASCADE,related_name='bugchanel_company_to')
    batch=models.ForeignKey('inventory.Batch',verbose_name=_('Batch'),on_delete=models.CASCADE,related_name='bugchanel_company_to')
    tm_delivery=models.DateTimeField(_('发货时间'))
    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 = _('渠道窜货记录')

    def __str__(self):
        return self.label_code


#奖品图像上传路径
def award_img_upload(instance,filename):    
    return os.path.join(instance.company.name,'award', filename)  

#活动页面背景图像上传路径
def activity_img_upload(instance,filename):
    return os.path.join(str(instance.company.name), "activity", filename)  

#发票图像上传路径
def invoice_img_upload(instance,filename):
    dt=datetime.datetime.now()
    y=str(dt.year)
    m=str(dt.month)
    return os.path.join(str(instance.invoice.company.name), "invoice", y, m, filename)  


class WxOfficialAccounts(models.Model):    
    company_id=models.IntegerField(_('公司名称'), blank=True, null=True)   
    name=models.CharField(_('公众号名称'), max_length=100, unique=True)
    wx_appid = models.CharField(_('APPID'), max_length=100, unique=True)
    wx_appsecret=models.CharField(_('APPSECRET'), max_length=100, unique=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 = _('微信公众号')
        unique_together = ("company_id", "wx_appid")

    def __str__(self):
        return self.name


class AwardCategory(models.Model):
    name=models.CharField(_('名称'), max_length=20, unique=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 Award(models.Model):   
    company=models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE, related_name='award_company')
    awardcat=models.ForeignKey(AwardCategory, verbose_name=_('奖品类型'), on_delete=models.CASCADE,related_name='award_cat')
    user = models.ForeignKey('company.User', verbose_name=_('操作员'), on_delete=models.CASCADE, related_name='award_user')
    name=models.CharField(_('奖品名称'), max_length=50)
    photo=models.ImageField(_('奖品图片'), upload_to=award_img_upload)
    introduction=models.CharField(_('奖品介绍'), max_length=100, blank=True, null=True)
    points=models.IntegerField(_('折合积分'), blank=True, null=True)
    amount=models.DecimalField(_('折合现金'), max_digits=12, decimal_places=2, blank=True, null=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)    
    is_need_hexiao = models.BooleanField(_('是否需要核销'),default=False)

    class Meta:
        verbose_name = _('奖项列表')
        verbose_name_plural = _('奖项列表')
        unique_together = ('company', 'name')

    def __str__(self):
        return self.name


class ExpressAgency(models.Model):
    name = models.CharField(_('公司名称'), max_length=100, unique=True)
    code = models.CharField(_('代码'), max_length=20, unique=True, 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.label_code


class Activities(models.Model):    
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE, related_name='activity_company')
    wx_account=models.ForeignKey(WxOfficialAccounts, verbose_name=_('微信授权'),on_delete=models.CASCADE, related_name='activity_wxaccout', blank=True, null=True)
    user = models.ForeignKey('company.User', verbose_name=_('创建人'), on_delete=models.CASCADE,related_name='activity_user')
    #target = models.SmallIntegerField(_('活动对象'), choices=(
    #    (1,_('消费者扫码')),
    #    (2,_('经销商层级'))), default=1)  
    target = models.SmallIntegerField(_('活动对象'), choices=(
        (1,_('消费者扫码')),
       ), default=1)
    scheme = models.SmallIntegerField(verbose_name=_('中奖方案'), choices=(
            (1,_('奖品概率抽奖')),
            (2,_('奖池标签概率抽奖')), 
            (3,_('奖池指定标签及奖品')),            
        ), default=1)
    distribution = models.SmallIntegerField(verbose_name=_('实物配送'), blank=True, null=True, choices=(
        (1,_('邮寄')),
        (2,_('门店兑换'))), default=1)    
    template = models.SmallIntegerField(_('中奖页面'), choices=(
        (1, _('通用')),
        (2, _('自定义'))), default=1) 
    lblpkg_id = models.SmallIntegerField(_('标签类别'), choices=(
        (1, _('瓶/支标')),
        (3, _('箱标'))),default=1)
    status = models.SmallIntegerField(_('活动状态'),choices=(
        (0,_('未激活')),
        (1,_('进行中')),
        (2,_('暂停')),
        (3,_('已结束'))), default=0)
    background = models.ImageField(_('背景图片'), upload_to=activity_img_upload, blank=True, null=True)
    tm = models.DateTimeField(_('创建时间'), auto_now_add=True)
    name = models.CharField(_('活动名称'), max_length=100)
    digest = models.CharField(_('活动摘要'), max_length=300, blank=True, null=True)
    priority = models.SmallIntegerField(_('优 先 级'), default=0)
    batch_ids=ArrayField(models.IntegerField(), verbose_name=_('指定发货批次'),blank=True,null=True)

    tm_start = models.DateTimeField(_('开始时间'))
    tm_end = models.DateTimeField(_('结束时间'))
    agent_lvs = ArrayField(models.IntegerField(),verbose_name=_('指定层级'), blank=True, null=True)        
    adm_ids = ArrayField(models.IntegerField(),verbose_name=_('指定区域'), blank=True, null=True)    
    agents = ArrayField(models.IntegerField(),verbose_name=_('指定商家'), blank=True, null=True)
    products = ArrayField(models.IntegerField(),verbose_name=_('指定产品'), blank=True, null=True)        
    user_closed = models.ForeignKey('company.User',verbose_name=_('关闭人'), blank=True, null=True,related_name='activity_user_close',on_delete=models.CASCADE)
    tm_closed = models.DateTimeField(_('关闭时间'), 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 = _('营销活动')

    def __str__(self):
        return self.name
    
    
    #当前活动抽奖，返回奖品 或 None
    def draw(self):   
        #rt={'
        awards=self.activityawards_activity.all()
        if not awards:
            return None
        total=0.0     #所有奖项中奖概率百分比之和
        weights=[]  #各奖项权重
        for o in awards:
            total = total+float(o.rate)
            weights.append((o, float(o.rate)))
        if total<100.0:
            weights.append((None,100.0-total))
        m=WeightRandom(weights)
        o=m.draw()
        if o:
            a_id=str(o.award_id)
            id=str(self.id)
            cur=connection.cursor()
            s="select count(*) cnt from sales_consumerwinner where award_id="+a_id+" and activity_id="+id
            cur.execute(s)
            r=cur.fetchone()
            useup=False
            #中奖上限数量检查
            if o.qty_upper:
                if r[0]>=o.qty_upper:
                    useup=True               
            #每日上限检查
            elif o.qty_daily:
                s="select count(*) cnt from sales_consumerwinner where award_id="+a_id+" and activity_id="+id+\
                    " and dt='"+datetime.datetime.now().strftime('%Y-%m-%d')+"'"
                cur.execute(s)
                r=cur.fetchone()
                if r[0]>=o.qty_upper:
                    useup=True
            if  useup:
                o=o.alternative

            cur.close()
        return o
        
class Activities_Code_Range(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE)
    activity = models.ForeignKey(Activities,verbose_name=_('活动名称'), on_delete=models.CASCADE, blank=True, null=True)
    code_start = models.CharField(_('开始号码'), max_length=20, blank=True, null=True)
    code_end = models.CharField(_('结束号码'), max_length=20, 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 ActivityAwards(models.Model):
    name = models.CharField(_('奖项名称'), max_length=100)    
    activity = models.ForeignKey(Activities, verbose_name=_('营销活动'), on_delete=models.CASCADE, related_name='activityawards_activity')
    award = models.ForeignKey(Award, verbose_name=_('奖品名称'), on_delete=models.CASCADE, related_name='activityawards_award')
    alternative = models.ForeignKey(Award, verbose_name=_('超限后替代品'), on_delete=models.CASCADE, related_name='activityawards_alternative', blank=True, null=True)    
    needcheck=models.BooleanField(_('中奖审核'),choices=(
        (False,_('不需审核')),
        (True,_('需要审核'))), default=False)
    rate = models.DecimalField(_('中奖概率'), max_digits=12, decimal_places=8, blank=True, null=True)
    qty_upper = models.IntegerField(_('上限数量'),blank=True,null=True)
    qty_input = models.IntegerField(_('投放数量'),blank=True,null=True)
    qty_daily = models.IntegerField(_('每日上限'),blank=True,null=True)
    qty_alarm = models.IntegerField(_('预警数量'),blank=True,null=True, default=0)

    class Meta:
        verbose_name = _('营销活动奖品')
        verbose_name_plural = _('营销活动奖品')

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


class AwardAddition(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE, related_name='awardsaddition_company')
    activity = models.ForeignKey(Activities, verbose_name=_('营销活动'), on_delete=models.CASCADE, related_name='awardaddition_activity')
    award = models.ForeignKey(Award, verbose_name=_('奖品名称'), on_delete=models.CASCADE, related_name='awardaddition_award')
    user = models.ForeignKey('company.User', verbose_name=_('操作人'), on_delete=models.CASCADE, related_name='awardaddition_user')
    qty = models.IntegerField(_('追加数量'))
    tm = models.DateTimeField(_('时间'),  auto_now_add=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = _('营销活动奖品追加')
        verbose_name_plural = _('营销活动奖品追加')

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


class ActivityRebatConfig(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE, related_name='activityrebat_company')
    activity = models.ForeignKey(Activities, verbose_name=_('营销活动'), on_delete=models.CASCADE, related_name='activityrebatcfg_activity')
    level = models.ForeignKey('company.Level', verbose_name=_('经销商层级'), on_delete=models.CASCADE, related_name='activityrebatcfg_lavel')
    amount = models.DecimalField(_('返利金额'), max_digits=12, decimal_places=2)

    class Meta:
        verbose_name = _('经销商返利设置')
        verbose_name_plural = _('经销商返利设置')

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


class TjfwAccount(models.Model):
    wx_openid = models.CharField(_('微信OpenID'), max_length=50, db_index=True, unique=True)
    dt = models.DateField(_('日期'), auto_now_add=True, db_index=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)

    class Meta:
        verbose_name = _('天鉴防伪OPENID')
        verbose_name_plural = _('天鉴防伪OPENID')

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


class ConsumerAccount(models.Model):    
    wx_account=models.ForeignKey(WxOfficialAccounts, on_delete=models.CASCADE, verbose_name=_('微信公众号'), db_index=True)
    tjfwacct=models.ForeignKey(TjfwAccount, on_delete=models.CASCADE, verbose_name=_('天鉴防伪帐号'),blank=True,null=True, db_index=True)
    wx_openid = models.CharField(_('微信OpenID'), max_length=50, blank=True, null=True, db_index=True)
    wx_nickname = models.CharField(_('微信昵称'), max_length=100, blank=True, null=True, db_index=True)
    wx_headimgurl = models.CharField(_('微信头像'), max_length=400, blank=True, null=True)
    wx_province = models.CharField(_('微信省份'), max_length=50, blank=True, null=True)
    wx_city = models.CharField(_('微信城市'), max_length=50, blank=True, null=True)
    wx_unionid = models.CharField(_('微信UNIONID'), max_length=50, blank=True, null=True)
    wx_language = models.CharField(_('语言'), max_length=50, blank=True, null=True)
    name = models.CharField(_('姓名'), max_length=20, blank=True, null=True)
    gender = models.SmallIntegerField(_('性别'), choices=((1, _('男')),(2, _('女')),(0,_('未知'))), blank=True,null=True)
    birthday = models.DateField(_('生日'), blank=True, null=True)
    age = models.SmallIntegerField(_('年龄'),blank=True,null=True)
    province = models.CharField(_('省份'), max_length=50, blank=True, null=True)
    city = models.CharField(_('城市'), max_length=50, blank=True, null=True)
    phone = models.CharField(_('电话号码'), max_length=20, blank=True, null=True, db_index=True)
    address = 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)    
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True) 

    class Meta:
        verbose_name = _('消费者帐号信息')
        verbose_name_plural = _('消费者帐号信息')

    def __str__(self):
        return self.wx_nickname


class MemberLevel(models.Model):
    company = models.ForeignKey('company.Company',verbose_name=_('公司'),related_name='MemberCompany',
                                on_delete=models.PROTECT)
    name = models.CharField(_("等级名称"),max_length=20,db_index=True)
    level = models.IntegerField(_("等级"),db_index=True)
    photo=models.ImageField(_('会员图片'), upload_to=memberlever_img_upload,null=True)
    integral = models.IntegerField(_('积分'),blank=True,null=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)
    class Meta:
        verbose_name=_("会员等级")
        verbose_name_plural=_("会员等级")
        unique_together =( ('company', 'level'),('company', 'name'))

    def __str__(self):
        return  self.name

    def save(self, *args, **kwargs):
        if not self.pk:
            # 存在就更新，不存在就创建
            m = hashlib.md5()
            m.update(self.name.encode(encoding="utf-8"))
            self.uid = m.hexdigest()
        super(MemberLevel, self).save(*args, **kwargs)




class Member(models.Model):
    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('消费者帐号'),
                                 on_delete=models.CASCADE, related_name='member_consumer', blank=True, null=True)
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE,
                                related_name='member_company')
    agent = models.ForeignKey('company.Company', verbose_name=_('终端名称'), on_delete=models.CASCADE,
                                related_name='member_agent_company',blank=True,null=True)
    sales_man = models.ForeignKey('company.User', verbose_name=_('业务员'), on_delete=models.CASCADE,
                                related_name='member_sales_man_company',blank=True,null=True)
    member_level = models.ForeignKey(MemberLevel,verbose_name=_('会员等级'),blank=True,null=True,
                              on_delete=models.CASCADE,related_name='member_level')
    name = models.CharField(_('姓名'), max_length=20, blank=True, null=True)
    gender = models.SmallIntegerField(_('性别'), choices=((1, _('男')), (2, _('女')), (0, _('未知'))), blank=True, null=True)
    birthday = models.DateField(_('生日'), blank=True, null=True)
    province = models.CharField(_('省份'), max_length=50, blank=True, null=True)
    city = models.CharField(_('城市'), max_length=50, blank=True, null=True)
    phone = models.CharField(_('电话号码'), max_length=20, blank=True, null=True, db_index=True)
    exps = models.IntegerField(_('经验'),db_index=True,default=0, blank=True, null=True)
    address = models.CharField(_('详细地址'), max_length=100, blank=True, null=True)
    dt = models.DateField(_('日期'), auto_now_add=True, db_index=True,blank=True, null=True,)
    dt = models.DateField(_('日期'), auto_now_add=True, db_index=True,blank=True, null=True,)
    tm = models.DateTimeField(_('时间'), auto_now_add=True,blank=True, null=True,)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)
    grade_id = models.SmallIntegerField(_('用户类型'), choices=((1, _('消费者')), (2, _('经销商')), (3, _('业务员'))), blank=True, null=True)
    headImg = models.CharField(_('头像'), max_length=400, blank=True, null=True)

    class Meta:
        verbose_name = _('会员信息')
        verbose_name_plural = _('会员信息') 

    def __str__(self):
        return self.name




class LabelScan(models.Model):  
    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('消费者帐号'), on_delete=models.CASCADE, related_name='labelscan_consumer')    
    company = models.ForeignKey('company.Company',verbose_name=_('公司名称'),on_delete=models.CASCADE, related_name='labelscan_company')
    activity = models.ForeignKey(Activities, verbose_name=_('活动名称'), on_delete=models.CASCADE, related_name='labelscan_activity', blank=True, null=True)
    scan_type=models.SmallIntegerField(_('扫码类型'),default=1,db_index=True)
    from_wx_official_account=models.BooleanField(_('请求是否自微信公众号'),default=False,db_index=True)
    label_code = models.CharField(_('标签号码'), max_length=20, db_index=True)
    label_pkg = models.SmallIntegerField(_('标签类型'), blank=True, null=True, db_index=True)
    label_id = models.BigIntegerField(_('标签ID'), blank=True, null=True, db_index=True)
    label_pk_id = models.BigIntegerField(_('主箱标ID'), db_index=True, blank=True, null=True)
    product = models.ForeignKey('product.Product',verbose_name=_('产品名称'), related_name='customerscan_product', on_delete=models.PROTECT, blank=True, null=True)
    ip=models.GenericIPAddressField(_('IP地址'),blank=True,null=True)
    province = models.CharField(_('省份'), max_length=100, blank=True, null=True,db_index=True)
    city = models.CharField(_('城市'), max_length=50, blank=True, null=True,db_index=True)
    address = models.CharField(_('详细地址'), max_length=200, blank=True, null=True)
    pos_permission = models.BooleanField(_('是否允许获取地理位置'))
    lng_lat = ArrayField(models.DecimalField(blank = True,max_digits=12, decimal_places=8), blank=True, null=True)
    amd_id1 = models.IntegerField(_('GIS adm_id1'), blank=True, null=True)
    amd_id2 = models.IntegerField(_('GIS adm_id2'), blank=True, null=True)
    amd_id3 = models.IntegerField(_('GIS adm_id3'), 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) 
    is_first = models.BooleanField(_('是否第一次扫码'),default=False, blank=True, null=True)
    agent_name = models.CharField(_('经销商名称'),max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = _('消费者扫码记录')
        verbose_name_plural = _('消费者扫码记录')        

    def __str__(self):
        return self.label_code



#2020-11-12 这个表将来删除，LabelScan 用 scan_type区分
class LabelImageQuery(models.Model):  
    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('消费者帐号'), on_delete=models.CASCADE, related_name='lblimage_consumer',blank=True,null=True)
    company = models.ForeignKey('company.Company',verbose_name=_('公司名称'),on_delete=models.CASCADE, related_name='lblimage_company',blank=True,null=True)  
    label_code = models.CharField(_('标签号码'), max_length=20, db_index=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 = _('标签图像查询记录')        

    def __str__(self):
        return self.label_code



class LotterySeeds(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE, related_name='lotteryseeds_company')
    activity = models.ForeignKey(Activities,verbose_name=_('活动名称'), on_delete=models.CASCADE, related_name='lotteryseeds_activity', blank=True, null=True)
    award = models.ForeignKey(ActivityAwards, verbose_name=_('奖品名称'), on_delete=models.CASCADE, related_name='lotterySeeds_award', blank=True, null=True)
    product = models.ForeignKey('product.Product', verbose_name=_('产品名称'), related_name='lotteryseeds_product', on_delete=models.PROTECT, blank=True, null=True)
    label_code = models.CharField(_('标签号码'), max_length=20, db_index=True)
    label_pkg = models.SmallIntegerField(_('标签类型'), blank=True, null=True, db_index=True)
    label_id = models.BigIntegerField(_('标签ID'), blank=True, null=True, db_index=True)
    label_pk_id = models.BigIntegerField(_('标签PKID'), db_index=True,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 = _('标签布奖记录')        

    def __str__(self):
        return self.label_code


class ConsumerWinner(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE, related_name='cunsumerwinner_company')
    activity = models.ForeignKey(Activities, verbose_name=_('活动名称'), on_delete=models.SET_NULL, related_name='cunsumerwinner_activity', blank=True,null=True)
    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('消费者帐号'), on_delete=models.CASCADE, related_name='cunsumerwinner_consumer', blank=True,null=True)
    award = models.ForeignKey(ActivityAwards, verbose_name=_('奖项'), on_delete=models.SET_NULL,blank=True,null=True)  
    label_code = models.CharField(_('标签号码'), max_length=20,    db_index=True,blank=True,null=True)
    seeds_id = models.IntegerField(_('布奖记录'), blank=True, null=True)
    labelscan_id = models.IntegerField(_('消费者扫码ID'), blank=True, null=True)
    phone = models.CharField(_('联系电话'), max_length=20, blank=True, null=True)    
    address = models.CharField(_('详细地址'), max_length=200, blank=True,null=True)
    qty=models.IntegerField(_('数量'),blank=True,null=True)
    name = models.CharField(_('姓名'), max_length=20,blank=True,null=True)    
    dt = models.DateField(_('日期'), auto_now_add=True, db_index=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True)
    tm_redeemed = models.DateTimeField(_('领奖时间'), blank=True, null=True)

    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True) 
    is_need_hexiao = models.BooleanField(_('是否需要核销'),default=False)
    is_hexiao = models.BooleanField(_('是否已经核销'),default=False)

    
    activity_name  = models.CharField(_('活动名称'), max_length=200,blank=True,null=True)
    original_award = models.ForeignKey(Award, verbose_name=_('原始奖项'), on_delete=models.SET_NULL,blank=True,null=True)
    award_name = models.CharField(_('奖品名称'), max_length=200,blank=True,null=True)
    award_points = models.IntegerField(_('奖品积分'),blank=True,null=True)
    award_amount = models.DecimalField(_('折合现金'), max_digits=12, decimal_places=2, blank=True, null=True)
    award_img =models.CharField(_('奖品图片'), max_length=500,blank=True,null=True)
    award_cat =models.CharField(_('奖品类型'), max_length=100,blank=True,null=True)
    tm_used = models.DateTimeField(_('使用时间'), blank=True, null=True)
    
    can_active_award = models.ForeignKey(ActivityAwards, verbose_name=_('可激活奖项'), on_delete=models.SET_NULL,blank=True,null=True,related_name='can_active_award_consumerwinner')  
    tm_expire = models.DateTimeField(_('过期时间'), blank=True, null=True)
    is_sharing = models.BooleanField(_('是否在分享中'),default=False)
    product = models.ForeignKey('product.Product', verbose_name=_('产品名称'), on_delete=models.SET_NULL,blank=True,null=True)

    
    wxpay_code = models.CharField(_('外部单号'), max_length=100, blank=True, null=True)
    
    agent_id = models.IntegerField(_('经销商ID'),blank=True,null=True)
    
    class Meta:
        verbose_name = _('消费者中奖记录')
        verbose_name_plural = _('消费者中奖记录')

    def __str__(self):
        return self.label_code


class ConsumerRedeem(models.Model):  
    winner = models.OneToOneField(ConsumerWinner,verbose_name=_('中奖记录'), on_delete=models.CASCADE, related_name='consumerredeem_awardwinner', unique=True)  
    checked_by = models.ForeignKey('company.User',verbose_name=_('审核人'), on_delete=models.CASCADE, related_name='consumerredeem_user', blank=True, null=True)
    checked_tm = models.DateTimeField(_('审核时间'), blank=True, null=True)
    expressagency = models.ForeignKey(ExpressAgency, verbose_name=_('快递代理公司'), on_delete=models.CASCADE, related_name='consumerredeem_expressagency', blank=True, null=True)    
    waybill_number = models.CharField(_('快递单号'), max_length=30, blank=True, null=True)
    ref_code = models.CharField(_('外部关联单号'), max_length=30, blank=True, null=True)
    tm_send = models.DateTimeField(_('发货时间'), blank=True, null=True)
    dt = models.DateField(_('兑奖日期'), auto_now_add=True, db_index=True)
    tm = models.DateTimeField(_('兑奖时间'), auto_now_add=True)
    tm_received = models.DateTimeField(_('收货时间'), blank=True, null=True)
    is_closed = models.BooleanField(_('是否已完结'), default=False)
    phone = models.CharField(_('联系电话'), max_length=20, blank=True, null=True) 
    province=models.CharField(_('省'),max_length=20,blank=True,null=True)
    city=models.CharField(_('市'),max_length=50,blank=True,null=True)
    county=models.CharField(_('县'),max_length=50,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 IntegralCollection(models.Model):
    ancestor_id = models.IntegerField(_('族系'), db_index=True)
    agent = models.ForeignKey('company.Company', verbose_name=_('经销商名称'), on_delete=models.CASCADE, related_name='pointcollection_agent')
    activity = models.ForeignKey(Activities, verbose_name=_('营销活动'), on_delete=models.CASCADE, related_name='pointcollection_activity')
    labelscan_id = models.IntegerField(_('消费者扫码ID'), blank=True, null=True)
    stk_batch_id = models.IntegerField(_('层级扫码Batch_id'), blank=True, null=True)
    points = models.IntegerField(_('获得积分'))
    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 = _('经销商积分获取')

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


class IntegralRedeemed(models.Model):
    agent = models.ForeignKey('company.Company', verbose_name=_('经销商名称'), on_delete=models.CASCADE, related_name='agtpointsredeem_agent')
    activity = models.ForeignKey(Activities, verbose_name=_('营销活动'), on_delete=models.CASCADE, related_name='agtpointsredeem_activity', blank=True, null=True)
    award = models.ForeignKey(Award, verbose_name=_('奖项'),  on_delete=models.CASCADE, related_name='integralredeemed_award', blank=True, null=True)
    user = models.ForeignKey('company.User',verbose_name=_('操作人'), related_name='integralredeemed_user', on_delete=models.CASCADE)
    points = models.IntegerField(_('消耗积分'))
    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 = _('经销商积分兑换')

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


class LoyaltyCollection(models.Model):
    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('消费者帐号'), on_delete=models.CASCADE, related_name='loyaltycollection_consumer', blank=True, null=True)
    activity = models.ForeignKey(Activities, verbose_name=_('营销活动'), on_delete=models.CASCADE, related_name='loyaltyCollection_activity', blank=True, null=True)
    labelscan_id = models.IntegerField(_('消费者扫码ID'), blank=True, null=True)
    points = models.IntegerField(_('获得积分'))
    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 = _('消费者积分获取')

    def __str__(self):
        return self.consumer.wx_nickname


class LoyaltyRedeemed(models.Model):
    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('消费者帐号'), on_delete=models.CASCADE, related_name='loyaltyredeem_consumer')
    activity = models.ForeignKey(Activities, verbose_name=_('营销活动'), on_delete=models.CASCADE, related_name='loyaltyredeem_activity', blank=True, null=True)
    award = models.ForeignKey(Award, verbose_name=_('奖项'),  on_delete=models.CASCADE, related_name='loyaltyredeem_award', blank=True, null=True)
    points = models.IntegerField(_('消耗积分'))
    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 = _('消费者积分兑换')

    def __str__(self):
        return self.agent.wx_nickname


class AgentCashCollection(models.Model):
    ancestor_id = models.IntegerField(_('族系'), db_index=True)
    agent = models.ForeignKey('company.Company', verbose_name=_('经销商名称'), on_delete=models.CASCADE, related_name='cashcollection_agent')
    activity = models.ForeignKey(Activities, verbose_name=_('营销活动'), on_delete=models.CASCADE, related_name='cashcollection_activity')
    labelscan_id = models.IntegerField(_('消费者扫码ID'), blank=True, null=True)
    stk_batch_id = models.IntegerField(_('层级扫码Batch_id'), blank=True, null=True)
    amount = models.DecimalField(_('记帐金额'), max_digits=12, decimal_places=2)
    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 = _('经销商记帐现金获取')

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


class AgentCashWithdraw(models.Model):
    agent = models.ForeignKey('company.Company', verbose_name=_('经销商名称'), on_delete=models.CASCADE, related_name='agtcashwithdraw_agent')
    activity = models.ForeignKey(Activities, verbose_name=_('营销活动'), on_delete=models.CASCADE, related_name='agtcashwithdraw_activity', blank=True, null=True)
    user = models.ForeignKey('company.User', verbose_name=_('操作人'), related_name='agtcashwithdraw_user', on_delete=models.CASCADE)
    tm_checked=models.DateTimeField(_('审核时间'), blank=True, null=True)
    amount = models.DecimalField(_('提现金额'), max_digits=12, decimal_places=2)
    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 = _('经销商记帐现金提取')

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


class BugSell(models.Model):
    ancestor=models.ForeignKey('company.Company',verbose_name=_('族系'),on_delete=models.CASCADE,related_name='bugsales_ancestor')
    company=models.ForeignKey('company.Company',verbose_name=_('公司名称'),on_delete=models.CASCADE,related_name='bugsales_company')  
    agent=models.ForeignKey('company.Company',verbose_name=_('经销商名称'),on_delete=models.CASCADE,related_name='bugsales_agent')   
    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('消费者帐号'), on_delete=models.CASCADE, related_name='bugsales_consumer')  
    product=models.ForeignKey('product.Product',verbose_name=_('产品名称'),on_delete=models.CASCADE,related_name='bugsales_product',blank=True,null=True)
    stkdetails_id=models.IntegerField(_('销售出库明细ID'),blank=True,null=True)
    tm_delivery=models.DateTimeField(_('销售出库时间'), blank=True,null=True)
    label_code=models.CharField(_('标签号码'),max_length=20)
    label_pkg=models.SmallIntegerField(_('标签类别'))   
    province=models.CharField(_('省份'),max_length=50)  
    city=models.CharField(_('城市'),max_length=50)
    address=models.CharField(_('详细地址'),max_length=150)
    distance=models.IntegerField(_('距离')) 
    lng_lat=ArrayField(models.DecimalField(_('经纬度'),max_digits=12,decimal_places=8))    
    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 = _('窜货预警')

    def __str__(self):
        return self.label_code







#2020-08-24
class ChannelPromotions(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE, related_name='channelpromotion_company')
    awardcategory = models.ForeignKey(AwardCategory,verbose_name=_('奖励方式'), on_delete=models.CASCADE, default=5)
    package_unit = models.SmallIntegerField('奖励核算基本单位', choices=(
        (1, _('按瓶/支(最小包装)奖励')),
        (3, _('按箱(最大包装)奖励'))), default=1)
    status = models.SmallIntegerField(_('活动状态'),choices=(
        (0,_('未激活')),
        (1,_('进行中')),
        (2,_('暂停')),
        (3,_('已结束'))), default=0)
    name = models.CharField(_('活动名称'), max_length=100)
    priority = models.SmallIntegerField(_('优 先 级'), default=0)
    digest = models.CharField(_('活动摘要'), max_length=300, blank=True, null=True)   
    div_ids = ArrayField(models.IntegerField(),verbose_name=_('指定战区'), blank=True, null=True)
    subdiv_ids = ArrayField(models.IntegerField(), verbose_name=_('指定分区'), blank=True, null=True)
    agents = ArrayField(models.IntegerField(),verbose_name=_('指定商家'), blank=True, null=True)
    products = ArrayField(models.IntegerField(),verbose_name=_('指定产品'), blank=True, null=True)
    tm_start = models.DateTimeField(_('开始时间(经销商扫码时间)'))
    tm_end = models.DateTimeField(_('结束时间(经销商扫码时间)'))
    dt_delivery=models.DateField(_('产品从公司的最早发货日期'),blank=True,null=True)
    user_closed = models.ForeignKey('company.User',verbose_name=_('关闭人'), blank=True, null=True,related_name='channelpromotion_user_close',on_delete=models.CASCADE)
    tm_closed = models.DateTimeField(_('关闭时间'), blank=True, null=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)
    user = models.ForeignKey('company.User', verbose_name=_('创建人'), on_delete=models.CASCADE,related_name='channelpromotion_user')
    tm = models.DateTimeField(_('创建时间'), auto_now_add=True)

    class Meta:
        verbose_name = _('渠道促销活动')
        verbose_name_plural = _('渠道促销活动')

    def __str__(self):
        return self.name



#2020-09-08 修改
class ChannelPromtionsRebate(models.Model):
    promotion = models.ForeignKey(ChannelPromotions, verbose_name=_('渠道促销活动'), on_delete=models.CASCADE, related_name='channelrebate_promotion')    
    vtype_id = models.SmallIntegerField(_('扫码类别'), choices=(       
        (1, _('扫码入库')),
        (2, _('扫码出库'))), default=2)
    level=models.ForeignKey('company.Level', verbose_name=_('扫码层级'), on_delete=models.CASCADE, related_name='channelrebate_level')
    val =models.DecimalField(_('返利金额（点值）'), max_digits=12, decimal_places=2)
    pvals=models.CharField(_('父级返利'), max_length=100, blank=True, null=True)
    distance=models.IntegerField(_('扫码有效距离'),blank=True,null=True)

    class Meta:
        verbose_name = _('渠道促销返利策略')
        verbose_name_plural = _('渠道促销返利策略')       

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

    #2020-09-11
    def save(self, *args, **kwargs):
        if self.id:
            for o in self.parentrebate_set.all():
                o.delete()
        super(ChannelPromtionsRebate, self).save(*args, **kwargs)
        if self.pvals:
            for s in self.pvals.split('&'):
                a=s.split('|')
                o=ParentRebate(rebate_id=self.id,level_id=int(a[0]),recursion=int(a[1]),val=float(a[2]))
                o.save()


#2020-09-08 新建
class ParentRebate(models.Model):
    rebate=models.ForeignKey(ChannelPromtionsRebate, verbose_name=_('渠道返利策略'),on_delete=models.CASCADE) 
    recursion=models.SmallIntegerField(_('递推次数'))
    level = models.ForeignKey('company.Level', verbose_name=_('营销层级'), on_delete=models.CASCADE, related_name='rebatedetails_level')
    val =models.DecimalField(_('返利金额（点值）'), max_digits=12, decimal_places=2) 
    
    class Meta:
        verbose_name = _('层级返利明细')
        verbose_name_plural = _('层级返利明细')

    def __str__(self):
        return self.rebate.promotion.name





#2020-09-08 新建
class ChannelRebateBatch(models.Model):
    ancestor=models.ForeignKey('company.Company',verbose_name=_('族系'),on_delete=models.CASCADE,related_name='channelrebatebath_ancestor',blank=True,null=True)
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE, related_name='channelrebatebath_company')
    company_src=models.ForeignKey('company.Company', verbose_name=_('返利贡献公司'), on_delete=models.CASCADE, related_name='channelrebatebath_company_src',blank=True,null=True)
    promotion = models.ForeignKey(ChannelPromotions, verbose_name=_('渠道促销活动'), on_delete=models.CASCADE, related_name='channelrebatebatch_promotion')
    batch=models.ForeignKey('inventory.Batch', verbose_name=_('batch'), on_delete=models.CASCADE)
    vtype_id=models.SmallIntegerField(_('扫码类型'),blank=True,null=True,db_index=True)
    level_id=models.SmallIntegerField(_('营销层级ID'),blank=True,null=True,db_index=True)
    saldivision_id=models.IntegerField(_('战区ID'),blank=True,null=True)
    storegeo_id=models.IntegerField(_('仓库ID'),blank=True,null=True)
    distance=models.DecimalField(_('距离'), max_digits=12, decimal_places=2,blank=True,null=True)
    checked_by=models.ForeignKey('company.User', verbose_name=_('检查人'),on_delete=models.CASCADE, related_name='channelrebatebatch_checked',blank=True,null=True)
    tm_checked=models.DateTimeField(_('检查时间'),blank=True,null=True)
    approved_by=models.ForeignKey('company.User', verbose_name=_('批准人'), on_delete=models.CASCADE, related_name='channelrebatebatch_approved',blank=True,null=True)
    tm_approved=models.DateTimeField(_('批准时间'),blank=True,null=True)
    confirmed=models.BooleanField(_('已确认'),default=False)
    val=models.DecimalField(_('返利总金额（点值）'), max_digits=12, decimal_places=2)
    boxes=models.IntegerField(_('箱数'),blank=True,null=True)
    bottles=models.IntegerField(_('瓶数'),blank=True,null=True)
    tm=models.DateTimeField(_('创建时间'), auto_now_add=True)
    dt=models.DateField(_('创建日期'), auto_now_add=True, db_index=True)
    tm_redeemed=models.DateTimeField(_('兑付时间'),blank=True,null=True)
    remark=models.CharField(_('备注说明'),max_length=50,blank=True,null=True)

    class Meta:
        verbose_name = _('渠道返利批次')
        verbose_name_plural = _('渠道返利批次')

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


#2020-10-29 
class ChannelRebateDetails(models.Model):
    rebate_batch=models.ForeignKey(ChannelRebateBatch,verbose_name=_('渠道返利批次'),on_delete=models.CASCADE)
    stk_batch = models.ForeignKey('inventory.Batch',verbose_name=_('StkBatch'),blank=True,null=True,on_delete=models.CASCADE)    
    dt_delivery=models.DateField(_('公司发货日期'),blank=True,null=True)
    label_id = models.BigIntegerField(_('标签ID'), db_index=True)
    label_pk_id = models.BigIntegerField(_('标签PKID'), db_index=True,blank=True,null=True)
    label_code = models.CharField(_('标签号码'), max_length=20, db_index=True)
    label_pkg = models.SmallIntegerField(_('标签类型'), db_index=True) 
    #2021-01-03
    is_deducted=models.BooleanField(_('是否为核减数据'),default=False,db_index=True)
    deduction_batch_id=models.IntegerField(_('核减项batch_id'),default=0,db_index=True)
    
    product_id=models.IntegerField(_('产品ID'))    
    #2020-11-09
    company_id=models.IntegerField(_('公司ID'),blank=True,null=True,db_index=True)
    vtype_id=models.SmallIntegerField(_('扫码类型'),blank=True,null=True,db_index=True)
    
    val =models.DecimalField(_('返利金额（点值）'), max_digits=12, decimal_places=2) 
    bottles=models.IntegerField(_('瓶数（最小包装）'),blank=True,null=True)
    dt = models.DateField(_('日期'), default=now, db_index=True)
    tm = models.DateTimeField(_('时间'), default=now)

    class Meta:
        verbose_name = _('渠道返利明细')
        verbose_name_plural = _('渠道返利明细')




#2020-09-08 新建
class ChannelRebateRedeemed(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE, related_name='channelrebateredeemed_company')
    ancestor_id=models.IntegerField(_('族系'))
    rebatebatch= models.ForeignKey(ChannelRebateBatch, verbose_name=_('营销渠道返利批次'), on_delete=models.CASCADE)
    val=models.DecimalField(_('返利总金额（点值）'), max_digits=12, decimal_places=2)
    user = models.ForeignKey('company.User', verbose_name=_('操作人'), on_delete=models.CASCADE,related_name='channelrebateredeemed_user', blank=True, null=True)    
    bank_receipt=models.CharField(_('银行回单'),max_length=30,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=50,blank=True,null=True)

    class Meta:
        verbose_name = _('营销渠道返利兑付')
        verbose_name_plural = _('营销渠道返利兑付')

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

 
#2020-11-12
#class ChannelSettlement(models.Model):
#    company = models.ForeignKey('company.Company',verbose_name=_('公司名称'),on_delete=models.CASCADE, related_name='channelsettlement_company')
#    ancestor=models.IntegerField(_('族系'))





#2020-11-04 内参扫码返利 如箱码、瓶码扫重复，箱码覆盖瓶码，补齐未扫的瓶码
#2020-11-16 ：此表将被删除，箱瓶替换记录写入INVENTORY 内参模式下，无返利也会有箱瓶码替换，影响库存
class RebateSubstitute(models.Model):
    stk_batch =models.ForeignKey('inventory.Batch',verbose_name=_('扫码枪Batch'),blank=True,null=True,
        on_delete=models.CASCADE,related_name='pkgsubstitute_inv_batch') 
    rebate_batch =models.ForeignKey(ChannelRebateBatch,verbose_name=_('层级返利Batch'),blank=True,null=True,
        on_delete=models.CASCADE,related_name='pkgsubstitute_rbt_batch')
    stk_batch_old=models.ForeignKey('inventory.Batch',verbose_name=_('原扫码枪Batch'),blank=True,null=True,
        on_delete=models.CASCADE,related_name='pkgsubstitute_inv_batcho') 
    rebate_batch_old=models.ForeignKey(ChannelRebateBatch,verbose_name=_('原层级返利Batch'),blank=True,null=True,
        on_delete=models.CASCADE,related_name='pkgsubstitute_rbt_batcho')
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), related_name='pkgsubstitute_company', on_delete=models.CASCADE)     
    ancestor_id=models.IntegerField(_('族系'),blank=True,null=True, db_index=True)    
    product = models.ForeignKey('product.Product', verbose_name=_('产品名称'), related_name='pkgsubstitute_product', on_delete=models.PROTECT)
    vtype_id=models.SmallIntegerField(_('单据类别ID'),db_index=True)    
    label_id = models.BigIntegerField(_('标签ID'), db_index=True)
    label_pk_id = models.BigIntegerField(_('标签PKID'), db_index=True,blank=True,null=True)
    label_bottle = models.CharField(_('瓶标号码'), max_length=20, db_index=True)    
    label_box=models.CharField(_('箱标号码'), max_length=20, db_index=True)
    val =models.DecimalField(_('返利金额（点值）'), max_digits=12, decimal_places=2,blank=True,null=True) 
    dt = models.DateField(_('日期'), default=now, db_index=True)
    tm = models.DateTimeField(_('时间'), default=now)    

    class Meta:
        verbose_name = _('被箱标置换的瓶标明细')
        verbose_name_plural = _('被箱标置换的瓶标明细')



#2020-11-22
class RebateClosing(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'),related_name='rebateclosing_company', on_delete=models.CASCADE) 
    name=models.CharField(_('会计期名称'),max_length=50)
    user = models.ForeignKey('company.User', verbose_name=_('期结操作人'), on_delete=models.CASCADE,related_name='rebateclosing_user')    
    period=models.SmallIntegerField(_('期结类型'),choices=((1,_('月结')),(2,_('季结')),(3,_('年结'))),default=2)
    dt_fr=models.DateField(_('开始日期'))
    dt_to=models.DateField(_('结束日期'))  
    lv1_dt_fr=models.DateField(_('平台商开始日期'),blank=True,null=True)
    lv1_dt_to=models.DateField(_('平台商结束日期'),blank=True,null=True)
    payable_counting=models.IntegerField(_('应付帐单笔数'),blank=True,null=True)
    balance_amount=models.DecimalField(_('上期余额'),max_digits=12,decimal_places=2,blank=True,null=True)
    payable_amount=models.DecimalField(_('应付款金额'), max_digits=12,decimal_places=2,blank=True,null=True)
    payable_checked_user=models.ForeignKey('company.User',verbose_name=_('应付款审核人'),on_delete=models.CASCADE,related_name='rebateclosing_checkerpayable',blank=True,null=True)
    payable_checked_tm=models.DateTimeField(_('应付款审核时间'),blank=True,null=True)

    application_counting=models.IntegerField(_('提现申请笔数'),blank=True,null=True)
    application_amount=models.DecimalField(_('提现申请金额'), max_digits=12,decimal_places=2,blank=True,null=True)
    application_checked_user=models.ForeignKey('company.User',verbose_name=_('提现申请审核人'),on_delete=models.CASCADE,related_name='rebateclosing_checkerapplication',blank=True,null=True)  
    application_checked_tm=models.DateTimeField(_('提现申请审核时间'),blank=True,null=True)    
       
    paid_amount=models.DecimalField(_('实际付款金额'), max_digits=12, decimal_places=2,blank=True,null=True)
    paid_counting=models.IntegerField(_('实际付款笔数'),blank=True,null=True)

    closed_tm=models.DateTimeField(_('关闭时间'),blank=True,null=True)
    closed_user=models.IntegerField(_('关闭操作人'),blank=True,null=True)
    calculated_tm=models.DateTimeField(_('应付返利计算时间'),blank=True,null=True)

    dt = models.DateField(_('创建日期'), default=now, db_index=True,blank=True,null=True)
    tm = models.DateTimeField(_('创建时间'), default=now, 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")


class RebatePayable(models.Model):
    rebateclosing=models.ForeignKey(RebateClosing,verbose_name=_('会计期'),related_name='rebatepayable_closing',on_delete=models.CASCADE)
    company_id=models.IntegerField(_('企业ID'),db_index=True)    
    agent=models.OneToOneField('company.Company',verbose_name=_('收款经销商'),related_name='rebatepayable_agent',on_delete=models.CASCADE)
    agent_name=models.CharField(_('经销商名称'),max_length=100)
    parent_id=models.IntegerField(_('上级经销商'))
    parent_name=models.CharField(_('上级经销商名称'),max_length=100)
    level_id=models.SmallIntegerField(_('经销商层级'))

    #log_edit=ArrayField(models.CharField(max_length=200),verbose_name=_('修改日志'),default=list, null=True)
    #image_invoice=ArrayField(models.CharField(max_length=200),verbose_name=_('发票上传记录'),default=list, null=True)

    log_edit=models.JSONField(default=list)  
    image_invoice=models.JSONField(null=True,blank=True)
    amount=models.DecimalField(_('本期扫码返利'),     max_digits=12, decimal_places=2,blank=True,null=True)
    amount_balance=models.DecimalField(_('上期余额'), max_digits=12, decimal_places=2,blank=True,null=True)
    amount_topay=models.DecimalField(_('应付款总计'), max_digits=12, decimal_places=2,blank=True,null=True)  
    boxes=models.IntegerField(_('扫码箱数'),blank=True,null=True)
    bottles=models.IntegerField(_('扫码瓶数'),blank=True,null=True)
    dt = models.DateField(_('日期'), default=now, db_index=True)
    tm = models.DateTimeField(_('时间'), default=now)  
    tm_chceked=models.DateTimeField(_('审核时间'),blank=True,null=True)
    is_closed=models.BooleanField(_('是否已关闭'),default=False,blank=True,null=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)

    class Meta:
        verbose_name = _('会计期返利应付款明细')
        verbose_name_plural = _('会计期返利应付款明细')
        unique_together = ("rebateclosing", "agent")

        


class RebateApplicationStatus(models.Model):
    company_id=models.IntegerField(_('企业ID'),default=1644)
    sn=models.SmallIntegerField(_('状态值'))
    name=models.CharField(_('状态名称'),max_length=30)    
    act_name=models.CharField(_('操作名称'),max_length=20,blank=True,null=True)
    act_sn=models.IntegerField(_('操作序号'),blank=True,null=True)
    status=models.CharField(_('当前状态名'),max_length=50,blank=True,null=True)
    remark=models.CharField(_('备注说明'),max_length=50,blank=True,null=True)

    class Meta:
        verbose_name = _('返利提现申请状态')
        verbose_name_plural = _('返利提现申请状态')


#2020-12-31
class RebateApplication(models.Model):
    rebateclosing=models.ForeignKey(RebateClosing,verbose_name=_('会计期'),related_name='rebateapplication_closing',on_delete=models.CASCADE)
    company_id=models.IntegerField(_('企业ID'),db_index=True)
    user_id=models.IntegerField(_('申请人ID'),blank=True,null=True)
    agent_name=models.CharField(_('经销商名称'),max_length=100)
    code=models.CharField(_('申请单号'),max_length=20,blank=True,null=True)
    parent_name=models.CharField(_('父级名称'),max_length=100,blank=True,null=True)
    level_id=models.SmallIntegerField(_('经销商层级'),blank=True,null=True)
    agent=models.ForeignKey('company.Company',verbose_name=_('经销商ID'),related_name='rebateapplication_agent',on_delete=models.CASCADE)  
    amount=models.DecimalField(_('申请提现金额'), max_digits=12, decimal_places=2)
    rate_vat=models.SmallIntegerField(_('税率'),blank=True,null=True)
    amount_vat=models.DecimalField(_('税费'),max_digits=11,decimal_places=2,blank=True,null=True)
    amount_total=models.DecimalField(_('金额合计'),max_digits=12,decimal_places=2,blank=True,null=True)
    wx_openid = models.CharField(_('申请人微信OPENID'), max_length=50)
    wx_nickname = models.CharField(_('申请人微信昵称'), max_length=100, db_index=True)
    wx_headimgurl = models.CharField(_('申请人微信头像'), max_length=400)         
    

    #2021-02-21
    payment_method=models.SmallIntegerField(_('付款方式'),default=1,choices=((1,'微信钱包'),(2,'银行卡')))
    invoice_needed=models.SmallIntegerField(_('提现方式'),default=1,choices=((1,'开票提现'),(0,'不开票提现')))
    wxwallet=models.ForeignKey('company.WxWallet',verbose_name=_('微信钱包'),blank=True,null=True,on_delete=models.SET_NULL)
    bankinfo=models.ForeignKey('company.BankInfo',verbose_name=_('银行卡'),blank=True,null=True,on_delete=models.SET_NULL)    

    status=models.ForeignKey(RebateApplicationStatus,verbose_name=_('当前状态'),default=1,db_index=True,on_delete=models.PROTECT)    
    img_invoices=models.JSONField(_('上传发票'),default=list)
    wx_receipt=models.CharField(_('微信转帐回单'),max_length=50,blank=True,null=True)
    dt = models.DateField(_('申请日期'), default=now, db_index=True)
    tm = models.DateTimeField(_('申请时间'), default=now)  
    tm_chceked=models.DateTimeField(_('审核时间'),blank=True,null=True)
    tm_paid=models.DateTimeField(_('付款时间'),blank=True,null=True,db_index=True)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)
    #2021-03-02
    wx_transmit=models.BooleanField(_('勾选微信钱包转帐'),default=False)

    class Meta:
        verbose_name = _('会计期返利提现申请')
        verbose_name_plural = _('会计期返利提现申请')


class RebatePaylog(models.Model):
    company_id=models.IntegerField(_('企业ID'),db_index=True)    
    application_id=models.IntegerField(_('经销商提现申请'),db_index=True)
    operator_id = models.IntegerField(_('操作人')) 
    is_success=models.BooleanField(_('支付是否成功'),default=False,blank=True,null=True)
    dt = models.DateField(_('日期'), default=now, db_index=True)
    tm = models.DateTimeField(_('时间'), default=now)
    msg=models.JSONField(_('平台返回信息'))
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)


    class Meta:
        verbose_name = _('会计期返利支付日志')
        verbose_name_plural = _('会计期返利支付日志')

    

class RebatePaid(models.Model):
    company_id=models.IntegerField(_('企业ID'),db_index=True)
    rebateclosing=models.ForeignKey(RebateClosing,verbose_name=_('会计期'),related_name='rebatepaid_closing',on_delete=models.CASCADE)    
    rebatepayable_id=models.IntegerField(_('返利应付款ID'),blank=True,null=True)
    application=models.OneToOneField(RebateApplication,verbose_name=_('经销商提现申请'),blank=True,null=True,on_delete=models.CASCADE)
    rebatepaylog_id=models.IntegerField(_('平台支付日在志'),blank=True,null=True)
    operator = models.ForeignKey('company.User',verbose_name=_('操作人'), related_name='rebatepaid_user',on_delete=models.CASCADE) 
    payment_method=models.SmallIntegerField(_('付款方式'),default=1,choices=((1,'微信钱包'),(2,'银行卡'),(3,'货返')))
    invoice_needed=models.SmallIntegerField(_('提现方式'),default=1,choices=((1,'开票提现'),(0,'不开票提现')))
    level_id=models.SmallIntegerField(_('经销商层级'),blank=True,null=True)   
    parent_name=models.CharField(_('父级名称'),max_length=100,blank=True,null=True)
    agent_id=models.IntegerField(_('经销商ID'),db_index=True)
    agent_name=models.CharField(_('经销商名称'),max_length=100,blank=True,null=True)
    amount=models.DecimalField(_('付款金额'), max_digits=12, decimal_places=2)   
    rate_vat=models.SmallIntegerField(_('税率'),blank=True,null=True)
    amount_vat=models.DecimalField(_('税费'),max_digits=11,decimal_places=2,blank=True,null=True)
    amount_total=models.DecimalField(_('金额合计'),max_digits=12,decimal_places=2,blank=True,null=True)    
    payment_no=models.CharField(_('微信付款单号'),max_length=40,blank=True,null=True)
    bank_statement=models.CharField(_('银行转帐流水单号'),max_length=50,blank=True,null=True)
    user_id=models.IntegerField(_('付款操作人ID'),blank=True,null=True)
    dt = models.DateField(_('日期'), default=now, db_index=True)
    tm = models.DateTimeField(_('时间'), default=now)      
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)


    class Meta:
        verbose_name = _('会计期返利付款明细')
        verbose_name_plural = _('会计期返利付款明细')



#2020-12-21 经销商返利，(微信)收款人
class RebatePayee(models.Model):
    company_id=models.IntegerField(_('公司ID'),db_index=True)
    #company=models.ForeignKey('company.Company',verbose_name=_('所属公司'),related_name='rebateueraccount_company',on_delete=models.CASCADE) 
    agent=models.OneToOneField('company.Company',verbose_name=_('收款经销商'),related_name='rebateuseraccount_agent',on_delete=models.CASCADE,unique=True)
    payee = models.ForeignKey('company.User', verbose_name=_('收款人'), on_delete=models.CASCADE,related_name='rebateueraccount_user',blank=True,null=True)  
    payee_name=models.CharField(_('收款人实名'),max_length=15,blank=True,null=True)
    tm = models.DateTimeField(_('生成时间'), default=now)    
    agent_confirmed_user_id=models.IntegerField(_('经销商确认人'),blank=True,null=True)
    agent_confirmed_time=models.DateTimeField(_('经销商确认时间'),blank=True,null=True)
    company_confirmed_user_id=models.IntegerField(_('公司确认人'),blank=True,null=True)
    company_confirmed_time=models.DateTimeField(_('公司确认时间'),blank=True,null=True)
    log_edit=models.JSONField(default=list)
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)


    class Meta:
        verbose_name = _('经销商返利微信收款人')
        verbose_name_plural = _('经销商返利微信收人')


#2021-03-01
class RebateInvoice(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('企业名称'),on_delete=models.CASCADE,related_name='rebateinvoice_company') 
    agent = models.ForeignKey('company.Company', verbose_name=_('开票经销商'), on_delete=models.CASCADE,related_name='rebateinvoice_agent',blank=True,null=True) 
    user=models.ForeignKey('company.User',verbose_name=_('登记人'),on_delete=models.CASCADE)
    code=models.CharField(_('发票代码'),max_length=20,blank=True,null=True)
    numbers=models.CharField(_('发票号码'),max_length=30)    
    amount=models.DecimalField(_('发票金额'), max_digits=12, decimal_places=2)
    salesdivision=models.ForeignKey('company.SubSalDivision',verbose_name=_('战区'),on_delete=models.CASCADE,blank=True,null=True)    
    claimant=models.CharField(_('报销人'),max_length=20,blank=True,null=True)
    uploaded=models.BooleanField(_('已上传'),blank=True,null=True,default=False)
    dt_billing = models.DateField(_('开票日期日期'), )    
    dt = models.DateField(_('日期'), default=now, db_index=True)
    tm = models.DateTimeField(_('时间'), default=now)  
    remark=models.CharField(_('备注说明'),max_length=100,blank=True,null=True)

    class Meta:
        verbose_name = _('发票记录')
        verbose_name_plural = _('发票记录')
        unique_together = ("company","code", "numbers")
        

class RebateInvoiceAttach(models.Model):
    invoice=models.ForeignKey(RebateInvoice,verbose_name=_('发票记录'),on_delete=models.CASCADE)
    title=models.CharField(_('标题'),max_length=50,blank=True,null=True,default='发票图片')    
    img=models.ImageField(_('发票图像文件'),upload_to=invoice_img_upload)



#2020-11-23 酒鬼酒鼠年生肖纪念酒集卡活动
class PromotionCode(models.Model):
    """
    @param {printed}
        0: 未印刷
        1: 已印刷
    @param {status}
        0: 初始状态, 未被领取
        1: 已领取
        2: 转赠中，未被领取
        3: 已被消耗
    """
    code = models.CharField(_('验证码'), max_length=12, unique=True)
    item = models.IntegerField(_('对应物品名称'))
    items=ArrayField(models.IntegerField(),verbose_name=_('对应物品名称'), blank=True, null=True) 
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), related_name='PromotionCode_company',    on_delete=models.CASCADE)
    activity = models.ForeignKey(Activities, verbose_name=_('活动名称'), related_name='PromotionCode_activity',     on_delete=models.CASCADE)
    printed = models.BooleanField(_('是否已印刷'),default=False)
    status = models.IntegerField(_('状态'), blank=False, default=0)
    uid = models.ForeignKey(ConsumerAccount, verbose_name=_('状态持有人'),on_delete=models.CASCADE, related_name='PromotionCode_user', 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.code


class PromotionCodeStatusRecord(models.Model):
    """
    @param {operation}
        1: 领取操作
        2: 转赠操作, code转为未被领取状态
        3: 兑换操作, code转为被消耗状态
    """
    code = models.ForeignKey(PromotionCode, verbose_name=_('验证码'), related_name='PromotionCodeStatusRecord_code', on_delete=models.CASCADE)
    operation = models.IntegerField(_('操作'), blank=False, default=0)
    uid = models.ForeignKey(ConsumerAccount, verbose_name=_('操作人'), on_delete=models.CASCADE, related_name='PromotionCodeStatusRecord_user')
    tm = models.DateTimeField(_('时间'), default=now)

    class Meta:
        verbose_name = _('验证码操作记录')
        verbose_name_plural = _('验证码操作记录')






# Jonathan
# 2020-12-14
class BuJiang_Labels(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE)
    label_code = models.CharField(_('标签序号'),max_length=50,blank=True,null=True)
    award = models.ForeignKey(Award,verbose_name=_('奖品'), on_delete=models.CASCADE) 
    is_active = models.BooleanField(_('是否激活'), blank=False, null=False, default=True)
    is_get = models.BooleanField(_('是否领取'), blank=False, null=False, default=False)
    remark=models.CharField(_('备注说明'),max_length=50,blank=True,null=True)
    tm=models.DateTimeField(_('步奖时间'), auto_now_add=True)
    class Meta:
        verbose_name = _('手动步奖')
        verbose_name_plural = _('手动步奖')





class Sms(models.Model): 
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE,related_name='sms_company')
    messages = models.CharField(_('短信内容'), max_length=100, blank=True, null=True)
    phone = models.CharField(_('电话号码'), max_length=20, blank=True, null=True, db_index=True)
    dt = models.DateField(_('日期'), auto_now_add=True, db_index=True, blank=True, null=True)
    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)
    code = models.CharField(_('验证码'), max_length=20, blank=True, null=True)

    class Meta:
        verbose_name = _('短信记录')
        verbose_name_plural = _('短信记录')

    def __str__(self):
        return self.name

#核销记录
class HeXiao_Record(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.DO_NOTHING)
    award = models.ForeignKey(Award, verbose_name=_('奖品'), on_delete=models.DO_NOTHING)
    award_name = models.CharField(_('奖品名称'), max_length=200, blank=True, null=True, db_index=True)
    activity = models.ForeignKey(Activities, verbose_name=_('活动名称'), on_delete=models.DO_NOTHING, blank=True, null=True)
    activity_name = models.CharField(_('活动名称'), max_length=200, blank=True, null=True)

    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('用户'), on_delete=models.DO_NOTHING)
    consumer_name = models.CharField(_('消费者姓名'), max_length=50, blank=True, null=True)
    consumer_phone = models.CharField(_('消费者电话'), max_length=50, blank=True, null=True)

    agent = models.ForeignKey('company.Company',related_name='hexiao_record_agent', verbose_name=_('公司名称'), on_delete=models.DO_NOTHING)
    agent_name =  models.CharField(_('终端店名称'), max_length=200, blank=True, null=True)
    is_agent_accepted = models.BooleanField(_('是否已经收货'), blank=False,
            null=False, default=False)
    agent_accepted_tm = models.DateTimeField(_('收货时间'), blank=True, null=True)

    user = models.ForeignKey('company.User', verbose_name=_('业务员'), on_delete=models.DO_NOTHING,blank=True, null=True)
    user_name = models.CharField(_('业务员名称'), max_length=200, blank=True, null=True)
    user_phone = models.CharField(_('业务员电话'), max_length=200, blank=True, null=True)
    money = models.DecimalField(_('返利金额'), max_digits=8, decimal_places=2)

    is_need_dispatch = models.BooleanField(_('是否需要配送'), blank=False, null=False, default=True)
    is_dispatched = models.BooleanField(_('是否已经配送'), blank=False,
            null=False, default=False)
    dispatched_tm = models.DateTimeField(_('配送时间'), blank=True, null=True)


    is_need_money_return = models.BooleanField(_('是否需要返现'), blank=False, null=False, default=False)
    is_money_returned = models.BooleanField(_('是否已经返现'), blank=False,
            null=False, default=False)
    money_returned_tm = models.DateTimeField(_('返现时间'), blank=True, null=True)

    is_permit = models.BooleanField(_('是否允许'), blank=False, null=False, default=False)
    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)
    remark = models.CharField(_('备注说明'), max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = _('核销记录')
        verbose_name_plural = _('核销记录')


# 节假期
class Holiday(models.Model):
    name = models.CharField(_('名称'),max_length=20)
    dt = models.DateField(_('日期'),db_index=True,)
    customize = models.BooleanField(default=False)
    remark = models.CharField(_('备注'),max_length=100,blank=True,null=True)
    company = models.ForeignKey('company.Company',verbose_name=_('公司名称'), on_delete=models.CASCADE,
                                related_name='holiday_company',blank=True,null=True)

    class Meta:
        verbose_name = _('节假日')
        verbose_name_plural = _('节假日')

    def __str(self):
        return self.name




#20445 "求真酱酒"用 ( 2020-01 )
class ActivityRebate_Relations(models.Model):
    activity = models.ForeignKey(Activities, verbose_name=_('返利活动'), on_delete=models.DO_NOTHING,
                                 related_name='ActivityRebateRelations_activity', blank=True)
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE,
                                related_name='ActivityRebateRelations_company', blank=True, null=True)
    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('用户'), blank=True,
            related_name='ActivityRebate_Relations_consumer',on_delete=models.DO_NOTHING)
    parent = models.ForeignKey(ConsumerAccount, verbose_name=_('父级用户'),
            related_name='ActivityRebate_Relations_parent',null=True,blank=True, on_delete=models.DO_NOTHING)
    tm = models.DateTimeField(_('关系创建时间'), auto_now_add=True, blank=True, null=True)

    class Meta:
        verbose_name = _('活动返利用户关系')
        verbose_name_plural = _('返利活动用户关系')

#20445 "求真酱酒"用 ( 2020-01 )
'''
    {operation}
    1: 获得返利 (直接扫码, 100%)
    2: 获得返利 (间接获得, 一等: 50%)
    3: 获得返利 (间接获得, 二等: 40%)
    4: 获得返利 (间接获得, 三等: 30%)
    5: 获得返利 (间接获得, 四等: 20%)
    6: 获得返利 (间接获得, 五等: 10%)
    100: 返利被提现单包含
    200: 返利对应的提现单被取消
'''
class ActivityRebate_BonusRecord(models.Model):
    activity = models.ForeignKey(Activities, verbose_name=_('返利活动'), on_delete=models.CASCADE,
                                 related_name='ActivityRebate_BonusRecord_activity', blank=True)
    company_id = models.ForeignKey('company.Company', verbose_name=_('公司'), on_delete=models.CASCADE,
                                related_name='AActivityRebate_BonusRecord_company', blank=True, null=True)
    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('用户'),
            related_name='ActivityRebate_BonusRecord_consumer',on_delete=models.CASCADE)
    labelcode = models.CharField(_('标签号码'), max_length=20,null=False,blank=False)
    operation = models.IntegerField(_('操作类型'), blank=False)
    amount = models.DecimalField(_('金额'), max_digits=8, decimal_places=2)
    tm = models.DateTimeField(_('时间'), auto_now_add=True, blank=True, null=True)
    remark = models.CharField(_('备注'), max_length=50, null=True, blank=True)
    class Meta:
        verbose_name = _('活动返利记录')
        verbose_name_plural = _('活动返利记录')

class ActivityRebate_RedPackSendRecord(models.Model):
    activity = models.ForeignKey(Activities, verbose_name=_('返利活动'), on_delete=models.CASCADE,
                                 related_name='RedPackSendRecord_activity', blank=True)
    company_id = models.ForeignKey('company.Company', verbose_name=_('公司'), on_delete=models.CASCADE,
                                related_name='RedPackSendRecord_company', blank=True, null=True)
    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('用户'),
            related_name='RedPackSendRecord_consumer',on_delete=models.CASCADE)
    bonus_record=models.ForeignKey(ActivityRebate_BonusRecord,verbose_name=('返利记录'),on_delete=models.CASCADE,
            related_name='redpacksendrecord_bonus_record',blank=False,null=False)
    openid= models.CharField(_('openid'),max_length=100,null=False,blank=False)
    remark=models.CharField(_('remark'),max_length=100,null=True,blank=True)
    return_code=models.CharField(_('return_code'),max_length=100,null=True,blank=True)
    result_code=models.CharField(_('result_code'),max_length=100,null=True,blank=True)
    class Meta:
        verbose_name=_('红包发放记录')
        verbose_name_plural = _('红包发放记录')

class Consumer_Appeal(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司'), on_delete=models.CASCADE)
    consumer = models.ForeignKey(ConsumerAccount, verbose_name=_('用户'),on_delete=models.CASCADE)
    label_code=models.CharField(_('标签序号'),max_length=30,null=True,blank=True)
    photo = models.CharField(_('图片'),max_length=200,null=True,blank=True)
    phone = models.CharField(_('手机号码'),max_length=20,null=True,blank=True)
    name = models.CharField(_('消费者姓名'),max_length=30,null=True,blank=True)
    message = models.CharField(_('消费者留言'),max_length=500,null=True,blank=True)
    tm = models.DateTimeField(_('提交时间'), auto_now_add=True)


    status = models.SmallIntegerField(_('状态'),default=0, choices=(
        ('0', _('审核中')),
        ('1', _('通过')),
        ('2', _('驳回')),
    )) 
    stop_tm = models.DateTimeField(_('结束日期'), null=True,blank=True)
    reason = models.CharField(_('原因'),max_length=500,null=True,blank=True)


    class Meta:
        verbose_name=_('消费者申诉记录')
        verbose_name_plural = _('消费者申诉记录')
