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

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
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 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")
    partition_date = models.CharField(max_length=8, verbose_name=u'日期')

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

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


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)



