from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.postgres.fields import ArrayField
# Create your models here.
import random
import bisect
from django.db import connection
from django.conf import settings
import os

#2020-08-14
import datetime


#权重随机数抽奖
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)  


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)    

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

    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 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 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=6, decimal_places=2, 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 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')
    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.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)
    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)
    province = models.CharField(_('省份'), max_length=100, blank=True, null=True)
    city = models.CharField(_('城市'), max_length=50, blank=True, null=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) 

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

    def __str__(self):
        return self.label_code


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(Award, 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.CASCADE, 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.CASCADE)  
    label_code = models.CharField(_('标签号码'), max_length=20, db_index=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)
    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) 
    
    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)
    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 BugSales(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')
    label_code=models.CharField(_('标签号码'),max_length=20)
    package_id=models.SmallIntegerField(_('标签类别'),blank=True,null=True)
    province=models.CharField(_('省份'),max_length=50)  
    city=models.CharField(_('城市'),max_length=50)
    address=models.CharField(_('详细地址'),max_length=150)
    distance=models.IntegerField(_('距离'))
    lng_lat=models.CharField('经纬度',max_length=50)
    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)
    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(_('结束时间'))
    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=(
        (0, _('不限定')),
        (1, _('扫码入库')),
        (2, _('扫码出库'))), default=2)
    package_scan=models.SmallIntegerField('扫码标签类型',choices=(
        (0, _('不限定 ）')),
        (1,_('瓶/支(最内层包装)')),
        (2,_('盒')),
        (3,_('箱(最外层包装'))), default=3)    
    rebate_unit=models.SmallIntegerField('奖励单位',choices=(
        (1,_('按瓶/支(最内层包装)奖励')),        
        (3,_('按箱(最外层包装)奖励'))), default=1)
    level=models.ForeignKey('company.Level', verbose_name=_('扫码层级'), on_delete=models.CASCADE, related_name='channelrebate_level')
    val =models.DecimalField(_('返利金额（点值）'), max_digits=12, decimal_places=2) 
    

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

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



#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):
    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)
    checked=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=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)
    val=models.DecimalField(_('返利总金额（点值）'), max_digits=12, decimal_places=2)
    tm=models.DateTimeField(_('创建时间'), auto_now_add=True)
    dt=models.DateTimeField(_('创建日期'), 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-09-08 新建
class ChannelRebateRedeemed(models.Model):
    company = models.ForeignKey('company.Company', verbose_name=_('公司名称'), on_delete=models.CASCADE, related_name='channelrebateredeemed_company')
    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)
    tm=models.DateTimeField(_('兑付时间'), auto_now_add=True)
    dt=models.DateTimeField(_('兑付日期'), 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

    
