# coding=utf-8
from __future__ import unicode_literals
import datetime
import math
import json

from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
from gm_types.gaia import CHANNEL_CALLBACK_TYPE, CLIENT_TYPE, PLATFORM_CHANNEL, CHANNEL_STATUS
from gm_types.gaia import USER_CLASSIFY

from api.models import Province, Tag, Doctor
from api.models import Service, PLATFORM_CHOICES, Doctor
from hippo.models import MerchantRelevance
from rpc.context import get_rpc_remote_invoker
from rpc.tool.log_tool import logging_exception

__author__ = 'leaf'
rpc_invoker = get_rpc_remote_invoker()


class TopicDaily(models.Model):
    """
    每日话题统计
    """

    class Meta:
        verbose_name = u'每日话题统计'
        verbose_name_plural = u'每日话题统计'

    stat_date = models.DateField(verbose_name=u'日期', null=False, default=datetime.date.today)
    new_topic = models.IntegerField(verbose_name=u'新增话题', default=0)
    new_ask_topic = models.IntegerField(verbose_name=u'新增咨询帖', default=0)
    new_share_topic = models.IntegerField(verbose_name=u'新增经验帖', default=0)
    new_link_share_topic = models.IntegerField(verbose_name=u'新增关联医生的经验帖', default=0)
    new_link_share_diary = models.IntegerField(verbose_name=u'新增关联医生的日记本', default=0)
    new_topic_replies = models.IntegerField(verbose_name=u'新增帖子的回复数', default=0)
    new_replies = models.IntegerField(verbose_name=u'新增回复总数', default=0)

    replied_topic = models.IntegerField(verbose_name=u'被回复话题', default=0)

    new_pm = models.IntegerField(verbose_name=u'用户新建私信对话数', default=0)
    new_pm_replies = models.IntegerField(verbose_name=u'用户新建私信对话所含对话条数', default=0)


class DoctorDaily(models.Model):
    """
    每日专家统计
    """

    class Meta:
        verbose_name = u'每日专家统计'
        verbose_name_plural = u'每日专家统计'

    stat_date = models.DateField(verbose_name=u'日期', null=False, default=datetime.date.today)

    doctor_reply_new_topics = models.IntegerField(verbose_name=u'有医生回复的话题', default=0)
    doctor_reply_pm = models.IntegerField(verbose_name=u'有医生回复的私信数', default=0)
    pm_reply_percent = models.FloatField(verbose_name=u'3天前私信被医生回复率', default=0.0)

    new_doctor = models.IntegerField(verbose_name=u'新增医生数', default=0)
    reply_doctor = models.IntegerField(verbose_name=u'回复话题的医生数', default=0)

    active_doctor = models.IntegerField(verbose_name=u'活跃医生数', default=0)


class UserDaily(models.Model):
    """
    每日用户统计
    """

    class Meta:
        verbose_name = u'每日用户统计'
        verbose_name_plural = u'每日用户统计'

    stat_date = models.DateField(verbose_name=u'日期', null=False, default=datetime.date.today)
    new_ios_device = models.IntegerField(verbose_name=u'新增iOS设备', default=0)
    new_android_device = models.IntegerField(verbose_name=u'新增Android设备', default=0)
    active_ios_device = models.IntegerField(verbose_name=u'活跃iOS设备', default=0)
    active_android_device = models.IntegerField(verbose_name=u'活跃Android设备', default=0)

    active_ios_user = models.IntegerField(verbose_name=u'活跃iOS用户', default=0)
    active_android_user = models.IntegerField(verbose_name=u'活跃Android', default=0)

    register_ios_user = models.IntegerField(verbose_name=u'新增iOS注册用户', default=0)
    register_android_user = models.IntegerField(verbose_name=u'新增Android注册用户', default=0)

    create_topic_user = models.IntegerField(verbose_name=u'发帖用户', default=0)
    reply_topic_user = models.IntegerField(verbose_name=u'回帖用户', default=0)

    pm_user = models.IntegerField(verbose_name=u'私信参与用户数', default=0)

    invited_user = models.IntegerField(verbose_name=u'受邀注册用户', default=0)


class TopicView(models.Model):
    """
    每日各话题的查看数量
    """

    class Meta:
        verbose_name = u'话题查看数量'
        verbose_name_plural = u'话题查看数量'
        unique_together = ('stat_date', 'topic_id')

    stat_date = models.DateField(verbose_name=u'日期', null=False, default=datetime.date.today)
    topic_id = models.IntegerField()  # TODO related_name='topic_views'
    view_num = models.IntegerField(default=0, verbose_name="浏览量")


class DiaryView(models.Model):
    """
    每日各日记本的查看数量
    """

    class Meta:
        verbose_name = u'日记本查看数量'
        verbose_name_plural = u'日记本查看数量'
        unique_together = ('stat_date', 'diary_id')

    stat_date = models.DateField(verbose_name=u'日期', null=False, default=datetime.date.today)
    diary_id = models.IntegerField()  # TODO related_name='diary_views'
    view_num = models.IntegerField(default=0, verbose_name="浏览量")


class ServiceView(models.Model):
    """
    用于福利页面统计
    """

    class Meta:
        verbose_name = '福利统计'
        verbose_name_plural = '福利统计'
        unique_together = ('stat_date', 'service',)

    stat_date = models.DateField(verbose_name=u'日期', null=False, default=datetime.date.today)
    service = models.ForeignKey(Service, related_name='service_page')
    view_num = models.IntegerField(default=0, verbose_name="每个福利详情页面的被查看次数")
    click_buy = models.IntegerField(default=0, verbose_name="每个福利详情页面被点击购买次数")


class DoctorView(models.Model):
    """
    用于专家浏览统计
    """

    class Meta:
        verbose_name = '专家浏览统计'
        verbose_name_plural = '专家浏览统计'
        unique_together = ('stat_date', 'doctor',)

    stat_date = models.DateField(verbose_name=u'日期', null=False, default=datetime.date.today)
    doctor = models.ForeignKey(Doctor, related_name='doctor_page')
    view_num = models.IntegerField(default=0, verbose_name="专家详情浏览量")
    reply_num = models.IntegerField(verbose_name=u'回复话题数量', default=0)
    new_pm_num = models.IntegerField(verbose_name=u'新增私信', default=0)
    new_pm_user_num = models.IntegerField(verbose_name=u'新用户私信数', default=0)
    noreply_pm_user_num = models.IntegerField(verbose_name=u'未回复新用户私信数', default=0)
    reply_pm_num = models.IntegerField(verbose_name=u'回复私信数量', default=0)
    no_reply_pm_num = models.IntegerField(verbose_name=u'没回复的私信数量', default=0)
    three_days_reply_pm_num = models.IntegerField(verbose_name=u'三天前私信回复数量', default=0)
    share_topic_num = models.IntegerField(verbose_name=u'案例数量', default=0)
    is_active = models.BooleanField(help_text="是否活跃医生", verbose_name="活跃", default=False)


class Device(models.Model):
    class Meta:
        verbose_name = '设备记录'
        verbose_name_plural = '设备记录'
        unique_together = ("device_id", "platform", "idfv")

    device_id = models.CharField(max_length=100, verbose_name=u'设备ID')
    platform = models.CharField(choices=PLATFORM_CHOICES, default=PLATFORM_CHOICES.ANDROID, max_length=20,
                                verbose_name=u'设备类型')
    version = models.CharField(verbose_name=u'APP版本', null=True, max_length=10)
    os_version = models.CharField(verbose_name=u'系统版本', null=True, max_length=20)
    model = models.CharField(verbose_name=u'Model', null=True, max_length=40)
    # Android Only
    screen = models.CharField(verbose_name=u'屏幕分辨率', null=True, max_length=40)
    channel = models.CharField(verbose_name=u'渠道', null=True, max_length=40)

    # User Info
    user = models.ManyToManyField(User, related_name="devices")

    # time
    created_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    last_activity = models.DateTimeField(auto_now=True, verbose_name=u'最后活跃时间')

    # add by chengliang @2016-09-23, for iOS IDFV
    idfv = models.CharField(max_length=100, verbose_name=u'iOS设备的idfv或Android设备的mac', null=False, default="")

    def __unicode__(self):
        return self.device_id

    @classmethod
    def exists_device_id(cls, device_id):
        '''
        判断对应device_id是否存在
        '''
        return cls.objects.filter(device_id=device_id).exists()

    @classmethod
    def get_interest(cls, user):
        """
        获取用户兴趣标签
        :return:
        """
        service = cls.objects.filter(user=user).order_by('-last_activity').first()
        interest_tag = []
        if service:
            interest_tag = rpc_invoker['doris/recommend/interest_tag'](device_id=service.device_id
                                                                       ).unwrap()['interest_tags']
        interest = u'暂无'
        try:
            interest = ','.join([Tag.objects.get(id=item).name for item in interest_tag])
        except:
            logging_exception()
        return interest

    @classmethod
    def get_user_ids_by_device(cls, device_id):
        """
            通过设备id获取用户id
        """
        obj = cls.objects.filter(device_id=device_id).first()
        if not obj:
            return []
        return obj.user.all().values_list('id', flat=True)


class DeviceIDFA(models.Model):

    class Meta:
        verbose_name = '设备记录'
        verbose_name_plural = '设备记录'
        unique_together = ("device_id", "platform", "idfa")

    device_id = models.CharField(max_length=100, verbose_name=u'设备ID')
    platform = models.CharField(choices=PLATFORM_CHOICES, default=PLATFORM_CHOICES.ANDROID, max_length=20,
                                verbose_name=u'设备类型')
    idfv = models.CharField(max_length=100, verbose_name=u'iOS设备的idfv或Android设备的mac', null=False, default="")
    idfa = models.CharField(max_length=100, verbose_name=u'iOS设备的idfa或Android设备的mac', null=False, default="")

    #
    created_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    last_activity = models.DateTimeField(auto_now=True, verbose_name=u'最后活跃时间')

    #同盾
    risk_result = models.CharField(verbose_name=u'风险评估结果', default='未校验', max_length=2)
    risk_score = models.IntegerField(verbose_name=u'风险评估系数', default=10)
    risk_check = models.BooleanField(verbose_name=u'是否风险检测', default=False)


class SheQuDevice(models.Model):
    class Meta:
        verbose_name = '设备记录'
        verbose_name_plural = '设备记录'
        unique_together = ("device_id", "platform", "idfv")

    device_id = models.CharField(max_length=100, verbose_name=u'设备ID')
    platform = models.CharField(
        choices=PLATFORM_CHOICES, default=PLATFORM_CHOICES.ANDROID, max_length=20,
        verbose_name=u'设备类型'
    )
    version = models.CharField(verbose_name=u'APP版本', null=True, max_length=10)
    os_version = models.CharField(verbose_name=u'系统版本', null=True, max_length=20)
    model = models.CharField(verbose_name=u'Model', null=True, max_length=40)
    # Android Only
    screen = models.CharField(verbose_name=u'屏幕分辨率', null=True, max_length=40)
    channel = models.CharField(verbose_name=u'渠道', null=True, max_length=40)

    # User Info
    user = models.ManyToManyField(User, related_name="shequ_devices")

    # time
    created_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    last_activity = models.DateTimeField(auto_now=True, verbose_name=u'最后活跃时间')

    # add by chengliang @2016-09-23, for iOS IDFV
    idfv = models.CharField(max_length=100, verbose_name=u'iOS设备的idfv或Android设备的mac', null=False, default="")

    def __unicode__(self):
        return self.device_id


class DoctorDevice(models.Model):
    class Meta:
        verbose_name = '医生版设备记录'
        verbose_name_plural = '医生版设备记录'
        unique_together = ("device_id", "platform", "idfv")
        db_table = 'statistic_device_doctor'

    device_id = models.CharField(max_length=100, verbose_name=u'设备ID')
    platform = models.CharField(choices=PLATFORM_CHOICES, default=PLATFORM_CHOICES.ANDROID, max_length=20,
                                verbose_name=u'设备类型')
    version = models.CharField(verbose_name=u'APP版本', null=True, max_length=10)
    os_version = models.CharField(verbose_name=u'系统版本', null=True, max_length=20)
    model = models.CharField(verbose_name=u'Model', null=True, max_length=40)
    # Android Only
    screen = models.CharField(verbose_name=u'屏幕分辨率', null=True, max_length=40)
    channel = models.CharField(verbose_name=u'渠道', null=True, max_length=40)

    # User Info
    # user = models.ManyToManyField(User, related_name="devices")

    # time
    created_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    last_activity = models.DateTimeField(auto_now=True, verbose_name=u'最后活跃时间')

    # add by chengliang @2016-09-23, for iOS IDFV
    idfv = models.CharField(max_length=100, verbose_name=u'iOS设备的idfv或Android设备的mac', null=False, default="")

    def __unicode__(self):
        return self.device_id


class StatisticServiceSmartRank(models.Model):
    class Meta:
        verbose_name = u'美购相关指数'
        db_table = 'statistic_service_smart_rank'
        app_label = 'statistic'

    service = models.ForeignKey(Service, related_name='service_index', db_index=True)
    stat_date = models.DateField(verbose_name=u'日期', null=False, default=datetime.date.today)
    consult_value = models.FloatField(verbose_name=u'咨询指数', null=False)
    doctor_rate = models.FloatField(verbose_name=u'医生因子', null=False)
    service_rate = models.FloatField(verbose_name=u'美购因子', null=False)
    diary_rate = models.FloatField(verbose_name=u'案例因子', null=False)
    order_value = models.FloatField(verbose_name=u'订单指数', null=False)
    discount_value = models.FloatField(verbose_name=u'抽成指数', null=False)
    refund_value = models.FloatField(verbose_name=u'退款指数', null=False)
    ad_money = models.FloatField(verbose_name=u'广告订单指数', null=False)
    high_quality_diary_count = models.IntegerField(verbose_name=u'案例数', null=False)
    income_value = models.FloatField(verbose_name=u'收入指数', null=False)


class StatisticServiceSmartRankV2(models.Model):
    class Meta:
        verbose_name = u'美购相关指数v2'
        db_table = 'statistic_service_smart_rank_v2'
        app_label = 'statistic'

    service = models.ForeignKey(Service, related_name='service_index_v2', db_index=True)
    stat_date = models.DateField(verbose_name=u'日期', null=False, default=datetime.date.today)
    ctr_value = models.FloatField(verbose_name=u'CTR', null=False)
    org_income_value = models.FloatField(verbose_name=u'机构收入转化率', null=False)
    org_deal_value = models.FloatField(verbose_name=u'机构交易转化率', null=False)
    service_detail_view_count_30 = models.IntegerField(verbose_name=u'30天美购详情曝光', null=False)
    org_income_value_60 = models.FloatField(verbose_name=u'60天机构收入转化率', null=False)
    org_income_value_90 = models.FloatField(verbose_name=u'90天机构收入转化率', null=False)
    org_income_value_180 = models.FloatField(verbose_name=u'180天机构收入转化率', null=False)
    org_deal_value_60 = models.FloatField(verbose_name=u'60天机构交易转化率', null=False)
    org_deal_value_90 = models.FloatField(verbose_name=u'90天机构交易转化率', null=False)
    org_deal_value_180 = models.FloatField(verbose_name=u'180天机构交易转化率', null=False)
    consult_pv_30 =  models.IntegerField(verbose_name=u'30天咨询pv', null=False, default=0)
    consult_pv_60 = models.IntegerField(verbose_name=u'60天咨询pv', null=False,  default=0)
    consult_pv_90 = models.IntegerField(verbose_name=u'90天咨询pv', null=False,  default=0)
    consult_pv_180 = models.IntegerField(verbose_name=u'180天咨询pv', null=False,  default=0)
    service_detail_pv_30 = models.IntegerField(verbose_name=u'30天美购详情页PV', null=False,  default=0)
    service_detail_pv_60 = models.IntegerField(verbose_name=u'60天美购详情页PV', null=False,  default=0)
    service_detail_pv_90 = models.IntegerField(verbose_name=u'90天美购详情页PV', null=False,  default=0)
    service_detail_pv_180 = models.IntegerField(verbose_name=u'180天美购详情页PV', null=False,  default=0)

class StatisticServiceSmartRankV3(models.Model):
    class Meta:
        verbose_name = u"美购相关指数v3"
        db_table = "statistic_service_smart_rank_v3"
        app_label = "statistic"

    service = models.ForeignKey(Service, related_name='service_index_v3', db_index=True)
    stat_date = models.DateField(verbose_name=u'日期', null=False, default=datetime.date.today)
    service_detail_click_count_30 = models.IntegerField(verbose_name=u'30天美购详情页点击', null=False)
    service_detail_view_count_30 = models.IntegerField(verbose_name=u"30天购详情页曝光次数", null=False)
    merchant_income_30 = models.FloatField(verbose_name=u"30天商家收入", null=False)
    merchant_income_60 = models.FloatField(verbose_name=u"30-60天商家收入", null=False)
    merchant_income_90 = models.FloatField(verbose_name=u"60-90天商家收入", null=False)
    merchant_income_180 = models.FloatField(verbose_name=u"90-180天商家收入", null=False)
    merchant_discount_30 = models.FloatField(verbose_name=u"30天商家已验证订单佣金",null=False)
    merchant_discount_60 = models.FloatField(verbose_name=u"30-60天商家已验证订单佣金", null=False)
    merchant_discount_90 = models.FloatField(verbose_name=u"60-90天商家已验证订单佣金", null=False)
    merchant_discount_180 = models.FloatField(verbose_name=u"90-180天商家已验证订单佣金",null=False)
    merchant_ad_money_30 = models.FloatField(verbose_name=u"30天商家广告消耗", null=False)
    merchant_ad_money_60 = models.FloatField(verbose_name=u"30-60天商家广告消耗", null=False)
    merchant_ad_money_90 = models.FloatField(verbose_name=u"60-90天商家广告消耗", null=False)
    merchant_ad_money_180 = models.FloatField(verbose_name=u"90-180天商家广告消耗", null=False)
    merchant_ka_income_30 = models.FloatField(verbose_name=u"30天商家KA收入",null=False)
    merchant_ka_income_60 = models.FloatField(verbose_name=u"30-60天商家KA收入", null=False)
    merchant_ka_income_90 = models.FloatField(verbose_name=u"60-90天商家KA收入",null=False)
    merchant_ka_income_180 = models.FloatField(verbose_name=u"90-180天商家KA收入",null= False)
    merchant_validate_price_30 = models.FloatField(verbose_name=u"30天商家已验证订单额",null=False)
    merchant_validate_price_60 = models.FloatField(verbose_name=u"30-60天商家已验证订单额",null=False)
    merchant_validate_price_90 = models.FloatField(verbose_name=u"60-90天商家已验证订单额", null=False)
    merchant_validate_price_180 = models.FloatField(verbose_name=u"90-180天商家已验证订单额", null=False)
    merchant_service_detail_pv_30 = models.IntegerField(verbose_name=u"商家30天美购详情页PV",null=False)
    merchant_service_detail_pv_60 = models.IntegerField(verbose_name=u"商家30-60天美购详情页PV",null=False)
    merchant_service_detail_pv_90 = models.IntegerField(verbose_name=u"商家60-90天美购详情页PV", null=False)
    merchant_service_detail_pv_180 = models.IntegerField(verbose_name=u"商家90-180天美购详情页PV", null=False)
    consult_pv_30 = models.IntegerField(verbose_name=u"30天咨询pv",null=False)
    consult_pv_60 = models.IntegerField(verbose_name=u"30-60天咨询pv", null=False)
    consult_pv_90 = models.IntegerField(verbose_name=u"60-90天咨询pv", null=False)
    consult_pv_180 = models.IntegerField(verbose_name=u"90-180天咨询pv", null=False)
    service_detail_pv_30 = models.IntegerField(verbose_name=u"30天美购详情页PV", null=False)
    service_detail_pv_60 = models.IntegerField(verbose_name=u"30-60天美购详情页PV", null=False)
    service_detail_pv_90 = models.IntegerField(verbose_name=u"60-90天美购详情页PV", null=False)
    service_detail_pv_180 = models.IntegerField(verbose_name=u"90-180天美购详情页PV", null=False)

    def get_value(self,molecular, denominator):
        return float(molecular)/float(denominator) if denominator >0 else 0

    def get_consult_value(self):
        consult_value =  self.get_value(self.consult_pv_30,self.service_detail_pv_30)
        if consult_value < 0.001:
            consult_value = 0.001
        elif consult_value >0.09:
            consult_value = 0.09
        return math.sqrt(1000*consult_value)


    def get_ctr_value(self):
        ctr_value =  self.get_value(self.service_detail_click_count_30,self.service_detail_view_count_30)
        if ctr_value < 0.001:
            ctr_value = 0.001
        elif ctr_value >= 0.09:
            ctr_value =  0.09
        ctr_value = 1000 * ctr_value
        from api.tool.smart_rank import calc_city_pv_ctr
        city_pv_map = calc_city_pv_ctr()
        city = self.service.city
        if city is not None:
            city_id = city.id
            if city_id is not None:
                min_pv = city_pv_map.get(city_id)
                if self.service_detail_view_count_30 < min_pv:
                    ctr_value = 0.01
        return math.sqrt(ctr_value)


    def get_discount_value(self):
        val =  self.get_value(self.merchant_discount_30,self.merchant_service_detail_pv_30)
        if val < 0.001:
            return 0.001
        else:
            return val

    def get_cpt_value(self):
        val = self.get_value(self.merchant_ad_money_30, self.merchant_service_detail_pv_30)
        if val < 0.001:
            return 0.001
        else:
            return val

    def get_cpc_price(self):
        cpc_map = rpc_invoker['artemis/cpc/promote/status_batch'](
            service_ids=[self.service.id]
        ).unwrap()

        click_data = cpc_map.get(str(self.service.id), None)
        click_price = 0
        if click_data is not None:
            is_promote = click_data.get("is_promote", False)
            if is_promote:
                click_price = click_data.get("click_price")
        return click_price


class StatisticServiceSmartRankV4(models.Model):
    class Meta:
        verbose_name = u"美购相关指数v4"
        db_table = "statistic_service_smart_rank_v4"
        app_label = "statistic"

    service = models.ForeignKey(Service, related_name='service_index_v4', db_index=True)
    stat_date = models.DateField(verbose_name=u'日期', null=False, default=datetime.date.today)
    service_detail_click_count_30 = models.IntegerField(verbose_name=u'30天美购详情页点击', null=False)
    service_detail_view_count_30 = models.IntegerField(verbose_name=u"30天购详情页曝光次数", null=False)
    merchant_income_30 = models.FloatField(verbose_name=u"30天商家收入", null=False)
    merchant_income_60 = models.FloatField(verbose_name=u"30-60天商家收入", null=False)
    merchant_income_90 = models.FloatField(verbose_name=u"60-90天商家收入", null=False)
    merchant_income_180 = models.FloatField(verbose_name=u"90-180天商家收入", null=False)
    merchant_discount_30 = models.FloatField(verbose_name=u"30天商家已验证订单佣金",null=False)
    merchant_discount_60 = models.FloatField(verbose_name=u"30-60天商家已验证订单佣金", null=False)
    merchant_discount_90 = models.FloatField(verbose_name=u"60-90天商家已验证订单佣金", null=False)
    merchant_discount_180 = models.FloatField(verbose_name=u"90-180天商家已验证订单佣金",null=False)
    merchant_ad_money_30 = models.FloatField(verbose_name=u"30天商家广告消耗", null=False)
    merchant_ad_money_60 = models.FloatField(verbose_name=u"30-60天商家广告消耗", null=False)
    merchant_ad_money_90 = models.FloatField(verbose_name=u"60-90天商家广告消耗", null=False)
    merchant_ad_money_180 = models.FloatField(verbose_name=u"90-180天商家广告消耗", null=False)
    merchant_ka_income_30 = models.FloatField(verbose_name=u"30天商家KA收入",null=False)
    merchant_ka_income_60 = models.FloatField(verbose_name=u"30-60天商家KA收入", null=False)
    merchant_ka_income_90 = models.FloatField(verbose_name=u"60-90天商家KA收入",null=False)
    merchant_ka_income_180 = models.FloatField(verbose_name=u"90-180天商家KA收入",null= False)
    merchant_validate_price_30 = models.FloatField(verbose_name=u"30天商家已验证订单额",null=False)
    merchant_validate_price_60 = models.FloatField(verbose_name=u"30-60天商家已验证订单额",null=False)
    merchant_validate_price_90 = models.FloatField(verbose_name=u"60-90天商家已验证订单额", null=False)
    merchant_validate_price_180 = models.FloatField(verbose_name=u"90-180天商家已验证订单额", null=False)
    merchant_service_detail_pv_30 = models.IntegerField(verbose_name=u"商家30天美购详情页PV",null=False)
    merchant_service_detail_pv_60 = models.IntegerField(verbose_name=u"商家30-60天美购详情页PV",null=False)
    merchant_service_detail_pv_90 = models.IntegerField(verbose_name=u"商家60-90天美购详情页PV", null=False)
    merchant_service_detail_pv_180 = models.IntegerField(verbose_name=u"商家90-180天美购详情页PV", null=False)
    consult_pv_30 = models.IntegerField(verbose_name=u"30天咨询pv",null=False)
    consult_pv_60 = models.IntegerField(verbose_name=u"30-60天咨询pv", null=False)
    consult_pv_90 = models.IntegerField(verbose_name=u"60-90天咨询pv", null=False)
    consult_pv_180 = models.IntegerField(verbose_name=u"90-180天咨询pv", null=False)
    service_detail_pv_30 = models.IntegerField(verbose_name=u"30天美购详情页PV", null=False)
    service_detail_pv_60 = models.IntegerField(verbose_name=u"30-60天美购详情页PV", null=False)
    service_detail_pv_90 = models.IntegerField(verbose_name=u"60-90天美购详情页PV", null=False)
    service_detail_pv_180 = models.IntegerField(verbose_name=u"90-180天美购详情页PV", null=False)

    def get_value(self,molecular, denominator):
        return float(molecular)/float(denominator) if denominator >0 else 0

    def get_consult_value(self):
        consult_value =  self.get_value(self.consult_pv_30,self.service_detail_pv_30)
        if consult_value < 0.001:
            consult_value = 0.001
        elif consult_value >0.09:
            consult_value = 0.09
        return math.sqrt(1000*consult_value)


    def get_ctr_value(self):
        ctr_value =  self.get_value(self.service_detail_click_count_30,self.service_detail_view_count_30)
        if ctr_value < 0.001:
            ctr_value = 0.001
        elif ctr_value >= 0.09:
            ctr_value =  0.09
        ctr_value = 1000 * ctr_value
        from api.tool.smart_rank import calc_city_pv_ctr
        city_pv_map = calc_city_pv_ctr()
        city = self.service.city
        if city is not None:
            city_id = city.id
            if city_id is not None:
                min_pv = city_pv_map.get(city_id)
                if self.service_detail_view_count_30 < min_pv:
                    ctr_value = 0.01
        return math.sqrt(ctr_value)


    def get_discount_value(self):
        val =  self.get_value(self.merchant_discount_30,self.merchant_service_detail_pv_30)
        if val < 0.001:
            return 0.001
        else:
            return val

    def get_cpt_value(self):
        val = self.get_value(self.merchant_ad_money_30, self.merchant_service_detail_pv_30)
        if val < 0.001:
            return 0.001
        else:
            return val

    def get_cpc_price(self):
        cpc_map = rpc_invoker['artemis/cpc/promote/status_batch'](
            service_ids=[self.service.id]
        ).unwrap()

        click_data = cpc_map.get(str(self.service.id), None)
        click_price = 0
        if click_data is not None:
            is_promote = click_data.get("is_promote", False)
            if is_promote:
                click_price = click_data.get("click_price")
        return click_price


class PromotionChannel(models.Model):
    class Meta:
        unique_together = ('idfa', 'appid')
        verbose_name = '渠道推广记录'
        db_table = 'statistic_promotion_channel'
        app_label = 'statistic'

    appid = models.CharField(max_length=64, verbose_name=u'渠道id')
    idfa = models.CharField(max_length=64, verbose_name=u'设备id')
    client_type = models.IntegerField(choices=CLIENT_TYPE, verbose_name=u'客户端类型', default=CLIENT_TYPE.USER)
    create_time = models.DateTimeField(default=timezone.now, verbose_name=u'创建时间')
    update_time = models.DateTimeField(verbose_name=u'更新时间')
    active_time = models.DateTimeField(null=True, blank=True, verbose_name=u'激活时间')
    callback_type = models.CharField(max_length=2, choices=CHANNEL_CALLBACK_TYPE,
                                     default=CHANNEL_CALLBACK_TYPE.NO_CALLBACK)
    callback = models.CharField(max_length=1024, verbose_name=u'渠道回调', blank=True, default='')
    click_request = models.TextField(blank=True, verbose_name=u'点击上报请求的json', default='')
    callback_response = models.TextField(blank=True, verbose_name=u'回调响应的json', default='')
    active_key = models.CharField(max_length=1024, verbose_name=u'激活回调需要的额外签名', default='')
    record_from = models.CharField(max_length=128, verbose_name=u'数据的来源', blank=True, default='')
    platform_type = models.IntegerField(choices=PLATFORM_CHANNEL, verbose_name=u'IOS或安卓类型',
                                        default=PLATFORM_CHANNEL.IOS)


class HospitalRankFactor(models.Model):
    class Meta:
        unique_together = (
            "hospital_id", "date"
        )
        db_table = "statistic_hospital_rank_factor"
        app_label = "statistic"

    hospital_id = models.CharField(max_length=100, verbose_name="医院id")

    hospital_pv_30 = models.IntegerField(verbose_name="医院主页pv-30天")
    hospital_exposure_pv_30 = models.IntegerField(verbose_name="该医院卡片的曝光-30天")
    hospital_ctr_30 = models.FloatField(verbose_name="医院卡片ctr-30天")

    expert_pv_30 = models.IntegerField(verbose_name="机构名下所有医生卡片pv-30天")
    expert_exposure_pv_30 = models.IntegerField(verbose_name="机构名下所有医生卡片曝光-30天")
    expert_ctr_30 = models.FloatField(verbose_name="机构名下所有医生ctr-30天")

    service_pv_30 = models.IntegerField(verbose_name="该医院名下所有美购的PV-30天")
    service_exposure_pv_30 = models.IntegerField(verbose_name="该医院名下所有美购的曝光-30天")
    service_ctr_30 = models.FloatField(verbose_name="机构名下所有美购ctr-30天")

    date = models.CharField(max_length=8, verbose_name=u'日期')

    @classmethod
    def get_hospital_score(cls, hospital_id, doctor_id):
        date_str = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d")
        # 医院整体得分= ctr开根号*（单pv佣金贡献+单pv广告消耗）
        try:
            h = cls.objects.get(hospital_id=hospital_id, date=date_str)
            merchant_id = MerchantRelevance.objects.get(doctor_id=doctor_id).merchant_id
            m = MerchantRankFactor.objects.get(merchant_id=merchant_id, partition_date=date_str)
        except:
            logging_exception()
            return 0.0

        try:
            total_exposures = float(h.hospital_exposure_pv_30 + h.service_exposure_pv_30 + h.expert_exposure_pv_30)
            if total_exposures < 3000:
                ctr = 0.01
            else:
                ctr = h.service_exposure_pv_30 / total_exposures * h.service_ctr_30 + \
                      h.hospital_exposure_pv_30 / total_exposures * h.hospital_ctr_30 + \
                      h.expert_exposure_pv_30 / total_exposures * h.expert_ctr_30
                if ctr < 0.01:
                    ctr = 0.01
                elif ctr > 0.2:
                    ctr = 0.2
        except:
            logging_exception()
            ctr = 0.01

        try:
            total_pv = m.service_pv_30 + m.expert_pv_30 + m.organization_pv_30
            if total_pv < 3000:
                total_pv = 3000
            commission = m.doctor_discount_30_days / float(total_pv)
            if commission < 0.01:
                commission = 0.01
            elif commission > 3:
                commission = 3
        except:
            logging_exception()
            commission = 0.01

        try:
            tmp = m.service_pv_30 + m.expert_pv_30 + m.organization_pv_30
            if tmp < 3000:
                tmp = 3000
            cpt = 1.0 * m.expand_rechange_amount_30 / float(tmp)
            if cpt < 0.01:
                cpt = 0.01
            elif cpt > 3:
                cpt = 3
        except:
            logging_exception()
            cpt = 0.01
        return math.sqrt(ctr) * (commission + cpt)


class BuDanFund(models.Model):
    class Meta:
        db_table = "al_meigou_service_smart_rank_budan_payment"
        app_label = "statistic"

    stat_date = models.DateField(verbose_name=u'日期')
    doctor_id = models.CharField(max_length=100, verbose_name="医生id")
    merchant_id = models.CharField(max_length=100, verbose_name="商户id")
    budan_payment_30_days = models.FloatField(verbose_name="30天已补订单佣金")


class DoctorRankFactor(models.Model):

    class Meta:
        unique_together = (
            "doctor_id", "partition_date"
        )
        db_table = "statistic_doctor_rank_factor"
        app_label = "statistic"

    doctor_id = models.CharField(max_length=100, verbose_name="医生id")
    expert_pv_30 = models.IntegerField(verbose_name="主页PV-30天")
    expert_exposure_pv_30 = models.IntegerField(verbose_name="医生曝光次数-30天")
    expert_message_num_30 = models.FloatField(verbose_name="咨询因子-30天")

    partition_date = models.CharField(max_length=8, verbose_name=u'日期')

    service_pv_30 = models.IntegerField(verbose_name="30天内美购pv")
    service_exposure_pv_30 = models.IntegerField(verbose_name="30天内美购曝光pv")
    service_ctr_30 = models.FloatField(verbose_name="30天内美购ctr")

    @classmethod
    def get_doctor_score(cls,doctor_id):
        # 医生整体得分= ctr开根号*（单pv佣金贡献+单pv广告消耗）
        date_str = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d")
        try:
            d = cls.objects.get(doctor_id=doctor_id, partition_date=date_str)
            merchant_id = MerchantRelevance.objects.get(doctor_id=doctor_id).merchant_id
            m = MerchantRankFactor.objects.get(merchant_id=merchant_id, partition_date=date_str)
        except:
            logging_exception()
            return 0.0
        try:
            # 该医生名下所有美购的曝光/(该医生名下所有美购的曝光+该医生卡片的曝光)*美购ctr+该医生卡片的曝光/(该医生名下所有美购的曝光+该医生卡片的曝光)*医生卡片ctr
            all_exposure = float(d.service_exposure_pv_30 + d.expert_exposure_pv_30)
            if all_exposure < 3000:
                ctr = 0.01
            else:
                ctr = d.service_exposure_pv_30 / all_exposure * d.service_ctr_30 + \
                      d.expert_exposure_pv_30/all_exposure * float(d.expert_pv_30/d.expert_exposure_pv_30)
                if ctr > 0.2:
                    ctr = 0.2
                elif ctr < 0.01:
                    ctr = 0.01
        except:
            logging_exception()
            ctr = 0.01

        # 统计期内商户名下医生账号的验证订单抽成之和/ （该商户名下所有美购的美购详情页PV+所有医生、机构主页PV）
        try:
            total_pv = m.service_pv_30 + m.expert_pv_30 + m.organization_pv_30
            if total_pv < 3000:
                total_pv = 3000
            commission = m.doctor_discount_30_days/ float(total_pv)
            if commission < 0.01:
                commission = 0.01
            elif commission > 3:
                commission = 3
        except:
            logging_exception()
            commission = 0.01

        # 统计期内该商户的广告消耗（CPC+CPT+其他） / （该商户名下所有美购的美购详情页PV+医生、机构主页PV）
        try:
            tmp = m.service_pv_30 + m.expert_pv_30 + m.organization_pv_30
            if tmp < 3000:
                tmp = 3000
            pv_ad = m.expand_rechange_amount_30 / float(tmp)
            if pv_ad < 0.01:
                pv_ad = 0.01
            elif pv_ad > 3:
                pv_ad = 3
        except:
            logging_exception()
            pv_ad = 0.01
        return math.sqrt(ctr) * (commission + pv_ad)

    @classmethod
    def get_rank_score(cls, doctor_id):
        date_str = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d")
        try:
            d = cls.objects.get(doctor_id=doctor_id, partition_date=date_str)
            merchant_id = MerchantRelevance.objects.get(doctor_id=doctor_id).merchant_id
            m = MerchantRankFactor.objects.get(merchant_id=merchant_id, partition_date=date_str)
        except (cls.DoesNotExist, MerchantRelevance.DoesNotExist, MerchantRankFactor.DoesNotExist):
            return 0.0

        try:
            consult = 1.0 * d.expert_message_num_30 / (m.service_pv_30 + m.expert_pv_30 + m.organization_pv_30)
        except ZeroDivisionError:
            consult = 0.001

        try:
            ctr = 1.0 * d.expert_pv_30 / d.expert_exposure_pv_30
        except ZeroDivisionError:
            ctr = 0.001

        try:
            commission = 1.0 * m.doctor_ad_money_30_days / (m.service_pv_30 + m.expert_pv_30 + m.organization_pv_30)
        except ZeroDivisionError:
            commission = 0.001

        try:
            cpt = 1.0 * m.doctor_discount_30_days / (m.service_pv_30 + m.expert_pv_30 + m.organization_pv_30)
        except ZeroDivisionError:
            cpt = 0.001
        return math.sqrt(consult) * math.sqrt(ctr) * (commission + 0.7*cpt)


class MerchantRankFactor(models.Model):
    class Meta:
        unique_together = (
            "merchant_id", "partition_date"
        )
        db_table = "statistic_merchant_rank_factor"
        app_label = "statistic"

    merchant_id = models.CharField(max_length=100, verbose_name="商户ID")
    partition_date = models.CharField(max_length=8, verbose_name=u'日期')

    doctor_ad_money_30_days = models.FloatField(verbose_name="商户名下非医生、机构账号的验证订单抽成之和")
    doctor_discount_30_days = models.FloatField(verbose_name="该商户的CPT纯消耗金额")
    service_pv_30 = models.IntegerField(verbose_name="该商户名下所有美购的美购详情页PV")
    expert_pv_30 = models.IntegerField(verbose_name="该商户名下所有医生主页PV")
    organization_pv_30 = models.IntegerField(verbose_name="该商户名下机构主页PV")
    expand_rechange_amount_30 = models.FloatField(verbose_name="统计期内该商户的广告消耗（CPC+CPT+其他）")


class MerchantDevice(models.Model):
    class Meta:
        app_label = 'api'
        verbose_name = "商家设备池"

    device = models.OneToOneField(Device, verbose_name=u'设备', related_name='merchant')
    create_time = models.DateTimeField(u'创建时间', auto_now_add=True)
    update_time = models.DateTimeField(u'更新时间', auto_now=True)


class ClassifyUser(models.Model):
    class Meta:
        unique_together = (
            "user", "classify"
        )
        app_label = 'api'
        verbose_name = "用户分类"

    user = models.ForeignKey(User, verbose_name=u'用户', related_name='user_classify')
    classify = models.CharField(verbose_name=u'用户类型', max_length=2, choices=USER_CLASSIFY, default=USER_CLASSIFY.MODEL)
    create_time = models.DateTimeField(u'创建时间', auto_now_add=True)
    update_time = models.DateTimeField(u'更新时间', auto_now=True)


class LikePromotionInfo(models.Model):
    """
    Like 渠道商信息表(由于 Like 停服，从 channels 项目迁移过来的，兼容 hermes 原有调用)
    """
    class Meta:
        verbose_name = 'Like渠道商信息表'
        db_table = 'like_promotioninfo'
        app_label = 'statistic'

    name = models.CharField(max_length=128, verbose_name='渠道名')
    code = models.CharField(max_length=64,verbose_name='渠道编码')
    sub_code = models.CharField(max_length=128, verbose_name='子渠道编码')
    platform = models.CharField(max_length=8,verbose_name='推广平台,IOS or Android')
    app = models.CharField(max_length=8,verbose_name="app名称",default="gengmei")
    appendtime = models.DateField(auto_now_add=True,verbose_name="创建时间")


class LikePromotionChannel(models.Model):
    """ Like channels 相关渠道统计模型，目前只用来存储迁移后的数据
    由于 hermes 依旧有调用，暂时迁移到gaia 观察一段时间
    """

    class Meta:
        unique_together = ('device_id', 'appid','idfa','idfv','imei')
        verbose_name = 'Like渠道推广记录'
        db_table = 'like_promotion_channel'
        app_label = 'statistic'

    # class APP_TYPE(Enum):
    #     GENGMEI=('0','gengmei')
    #     LIKE=('1','like')
    #这里改一下吧
    app_name = models.CharField(max_length=64, verbose_name=u'app名字',default="0")
    appid = models.CharField(max_length=64, verbose_name=u'渠道id')
    device_id = models.CharField(max_length=64, verbose_name=u'设备id')
    idfa = models.CharField(max_length=64,verbose_name=u'idfa')
    idfv = models.CharField(max_length=64, verbose_name=u'idfv')
    udid=models.CharField(max_length=64, verbose_name=u'udid')
    uuid=models.CharField(max_length=64, verbose_name=u'uuid')
    imei = models.CharField(max_length=64,verbose_name=u'imei')

    #设备物理地址
    mac = models.CharField(max_length=100, verbose_name=u'Android设备的mac', null=True, default="")
    platform = models.CharField(max_length=100,verbose_name=u'IOS或安卓类型',default=PLATFORM_CHANNEL.UNKNOWN)

    model = models.CharField(verbose_name=u'Model', null=True, max_length=40)#这是什么
    client_type = models.IntegerField(verbose_name=u'客户端类型', default=CLIENT_TYPE.USER)

    callback_type = models.CharField(max_length=2,default=CHANNEL_CALLBACK_TYPE.NO_CALLBACK)
    callback = models.CharField(max_length=1024, verbose_name=u'渠道回调', blank=True, default='')
    request = models.TextField(blank=True, verbose_name=u'点击上报请求的json', default='')
    response = models.TextField(blank=True, verbose_name=u'回调响应的json', default='')
    active_key = models.CharField(max_length=1024, verbose_name=u'激活回调需要的额外签名', default='')
    record_from = models.CharField(max_length=128, verbose_name=u'数据的来源', blank=True, default='')

    version = models.CharField(verbose_name=u'APP版本', null=True, max_length=10)
    os_version = models.CharField(verbose_name=u'系统版本', null=True, max_length=20)

    # Android Only
    screen = models.CharField(verbose_name=u'屏幕分辨率', null=True, max_length=40)

    # time
    create_time = models.DateTimeField(default=timezone.now, verbose_name=u'创建时间')
    active_time = models.DateTimeField(null=True, blank=True, verbose_name=u'激活时间')
    last_activity = models.DateTimeField(auto_now=True, verbose_name=u'最后活跃时间')

    def save(self, data=None, *args, **kwargs):

        if data:
            self.__dict__.update(data)

        super().save(*args, **kwargs)

    @staticmethod
    def filter_exists_propertys(**kwargs):
        '''
            查找出可操作字段
        '''
        #获取类的全部字段
        propertys = LikePromotionChannel.__dict__.keys()
        keys = kwargs.keys()
        #查找存在表中的字段
        params = {key.lower().strip():value for key,value in kwargs.items() if key.lower().strip() in propertys}

        return params

    @staticmethod
    def activate(record, kwargs):
        '''
            激活设备
        '''
        params = LikePromotionChannel.filter_exists_propertys(**kwargs)

        record.active_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        record.save(data=kwargs)

    @staticmethod
    def record(request, sub_name=None, **kwargs):
        """
        新增加渠道设备数据
        """
        params = LikePromotionChannel.filter_exists_propertys(**kwargs)

        #获得request的数据
        if request:
            params.update({"request": json.dumps(request.GET.dict())})

        #appid加前缀和子渠道
        appid = params.get("appid")
        appid = '{0}{1}'.format(appid, "_{0}".format(sub_name) if sub_name else "")
        params.update({"appid": appid})

        #如果callback_type不存在的话,默认为GET
        params.update({'callback_type': CHANNEL_CALLBACK_TYPE.GET_CALLBACK})

        #保存并记录
        try:
            promotion = LikePromotionChannel.objects.create(**params)
        except Exception as e:
            return False, CHANNEL_STATUS.ADD_FAIL_GENERAL.value

        return True, ''


class MerchantUpgradeIndic(models.Model):
    class Meta:
        verbose_name = u'验证升单质量指标基本信息'
        app_label = 'statistic'

    merchant_doctor_id = models.CharField(max_length=50, db_index=True, null=True, verbose_name="商户ID")
    merchant_name = models.CharField(max_length=50, null=True, verbose_name="商户名称")
    pay_order_num = models.IntegerField(null=True, verbose_name="支付订单数")
    validate_order_num = models.IntegerField(null=True, verbose_name="验证订单数")
    upgrade_order_num = models.IntegerField(null=True, verbose_name="升级订单数")
    upgrade_order_amount = models.FloatField(null=True, verbose_name="升级订单金额")
    validate_order_rate = models.FloatField(null=True, verbose_name="验证订单率")
    upgrade_order_rate = models.FloatField(null=True, verbose_name="升级订单率")
    single_upgrade_order_amount = models.FloatField(verbose_name="单笔升级订单金额")
    create_date = models.CharField(max_length=255, db_index=True, verbose_name="创建时间")


class MerchantUpgradeIndicAvg(models.Model):
    class Meta:
        verbose_name = u'验证升单质量指标平均值'
        app_label = 'statistic'

    validate_order_rate_avg = models.FloatField(null=True, verbose_name="平均验证订单率")
    upgrade_order_rate_avg = models.FloatField(null=True, verbose_name="平均升级订单率")
    single_upgrade_order_amount_avg = models.FloatField(verbose_name="平均单笔升级订单金额")
    create_date = models.CharField(max_length=255, db_index=True, verbose_name="创建时间")


class ClueDoctorSmartRank(models.Model):

    class Meta:
        db_table = "clue_doctor_smart_rank"

    doctor_id = models.CharField(max_length=255, verbose_name=u'医生id')
    smart_rank = models.FloatField(verbose_name="smart_rank")
    partion_date = models.CharField(max_length=8, verbose_name=u'日期')
    update_date = models.DateField(u'更新时间', auto_now=True)


class StatisticSkuItemSales(models.Model):

    class Meta:
        db_table = "statistic_sku_item_sales"

    sales = models.IntegerField(verbose_name="销量")

class TranslateTreatmentScore(models.Model):
    """
    id
    day_id
    merchant_id
    merchant_name
    merchant_level
    is_assure_clue
    is_overdue
    assure_clue_num_m
    already_clue_num_m
    surplus_days_m
    overdue_days
    dispatch_order_user_num_m
    dispatch_order_user_num_90d
    transfer_order_user_num_90d
    transfer_order_record_amount_90d
    transfer_order_pay_amount_90d
    dispatch_transfer_order_transform_rate_90d
    avg_transfer_order_pay_amount_90d
    avgall_dispatch_order_record_transform_rate_90d
    avgall_avg_transfer_order_pay_amount_90d
    """
    class Meta:
        db_table = "sl_strategy_ct_mc_merchantdispatchtransform_d"
    day_id = models.DateField(u'账期日', auto_now=True)
    merchant_id = models.CharField(max_length=50, verbose_name=u'商户ID')
    merchant_name = models.CharField(max_length=100, verbose_name=u'商户名称')
    merchant_level = models.CharField(max_length=10, verbose_name=u'商户等级')
    is_assure_clue = models.IntegerField(verbose_name=u'是否保线索')
    is_overdue = models.IntegerField(verbose_name=u'是否逾期')
    assure_clue_num_m = models.IntegerField(verbose_name=u'每月保线索数量')
    already_clue_num_m = models.IntegerField(verbose_name=u'本月已完成线索数量')
    surplus_days_m = models.IntegerField(verbose_name=u'本月剩余天数')
    overdue_days = models.IntegerField(verbose_name=u'逾期天数')
    dispatch_order_user_num_m = models.IntegerField( verbose_name=u'当月派单用户数量')
    dispatch_order_user_num_90d = models.IntegerField(verbose_name=u'过去90天派单用户数量')
    transfer_order_user_num_90d = models.IntegerField(verbose_name=u'过去90天成交用户数量')
    transfer_order_record_amount_90d = models.FloatField(verbose_name=u'过去90天成交金额')
    transfer_order_pay_amount_90d = models.FloatField(verbose_name=u'过去90天回款金额')
    dispatch_transfer_order_transform_rate_90d = models.FloatField(verbose_name=u'过去90天派单成交转化率(派单转化)')
    avg_transfer_order_pay_amount_90d = models.FloatField(verbose_name=u'过去90天转诊回款金额均值(派单价值)')
    avgall_dispatch_order_record_transform_rate_90d = models.FloatField(verbose_name=u'所有商户过去90天派单转化率均值(派单转化平均值)')
    avgall_avg_transfer_order_pay_amount_90d = models.FloatField(verbose_name=u'所有商户过去90天转诊回款金额均值平均值(派单价值平均值)')

    def calc_score(self):
        """
        在这里计算总分
        document_url:http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=45354640
        """
        score = 0.0
        score = (self.calc_bussiness_score()*0.5+(self.calc_send_orders_conversion_score()*0.2+self.calc_send_orders_value_score()*0.8))*self.calc_clue_gold_score()*self.calc_returned_money_coefficient_score()

        return score

    def calc_bussiness_score(self):
        """
        商家等级得分
        """
        merchant_level = int(self.merchant_level)
        merchant_score_table = {
            0: -10,
            1: 10,
            2: 25,
            3: 35,
            4: 40,
            5: 50,
            6: 80,
            7: 100
        }
        score = 0.0
        # if merchant_level<=3:
        #     score = 10+(merchant_level-0)*10
        # elif merchant_level<=7:
        #     score = 70+(merchant_level-4)*10
        if merchant_level in merchant_score_table:
            score = merchant_score_table[merchant_level]
        return float(score)

    def calc_clue_gold_score(self):
        """
        保线索加权
        """
        coefficient = 1.0
        if self.is_assure_clue:
            coefficient = ((self.assure_clue_num_m - self.already_clue_num_m-self.dispatch_order_user_num_m) / float(self.surplus_days_m)) / (self.assure_clue_num_m / 30.0)
        if coefficient<=1:
            coefficient = 1.0
        elif coefficient<=1.5:
            coefficient = 1.3
        elif coefficient<=2:
            coefficient = 1.5
        else:
            coefficient = 2.0
        return coefficient

    def calc_send_orders_value_score(self):
        """
        计算派单价值得分
        """
        send_orders_value_coefficient = 0.0
        send_orders_value_score = 0.0
        if self.dispatch_order_user_num_90d>10:
            send_orders_value_coefficient = float(self.transfer_order_pay_amount_90d)/self.dispatch_order_user_num_90d
        else:
            send_orders_value_coefficient = self.avgall_dispatch_order_record_transform_rate_90d
        if send_orders_value_coefficient <= 200:
            send_orders_value_score = 30
        elif send_orders_value_coefficient <= 400:
            send_orders_value_score = 40
        elif send_orders_value_coefficient <= 600:
            send_orders_value_score = 50
        elif send_orders_value_coefficient <= 800:
            send_orders_value_score = 60
        elif send_orders_value_coefficient <= 1000:
            send_orders_value_score = 70
        elif send_orders_value_coefficient <= 1200:
            send_orders_value_score = 80
        elif send_orders_value_coefficient <= 1400:
            send_orders_value_score = 90
        elif send_orders_value_coefficient <= 1600:
            send_orders_value_score = 100
        else:
            send_orders_value_score = 100
        return send_orders_value_score

    def calc_send_orders_conversion_score(self):
        """

        """
        send_orders_conversion_coefficient = 0.0
        send_orders_conversion_score = 0.0
        if self.dispatch_order_user_num_90d>10:
            send_orders_conversion_coefficient = float(self.transfer_order_user_num_90d)/self.dispatch_order_user_num_90d
        else:
            send_orders_conversion_coefficient = self.avgall_dispatch_order_record_transform_rate_90d
        if send_orders_conversion_coefficient <= 0.035:
            send_orders_conversion_score = 40
        elif send_orders_conversion_coefficient <= 0.065:
            send_orders_conversion_score = 50
        elif send_orders_conversion_coefficient <= 0.095:
            send_orders_conversion_score = 60
        elif send_orders_conversion_coefficient <= 0.125:
            send_orders_conversion_score = 70
        elif send_orders_conversion_coefficient <= 0.155:
            send_orders_conversion_score = 80
        elif send_orders_conversion_coefficient <= 0.185:
            send_orders_conversion_score = 85
        elif send_orders_conversion_coefficient <= 0.215:
            send_orders_conversion_score = 90
        else:
            send_orders_conversion_score = 100
        return send_orders_conversion_score

    def calc_returned_money_coefficient_score(self):
        """

        """
        returned_money_coefficient = 0.0
        if self.overdue_days > 61+3:
            returned_money_coefficient = 0.5
        elif self.overdue_days > 61+5:
            returned_money_coefficient = 0
        else:
            returned_money_coefficient = 1
        return returned_money_coefficient