#!/usr/bin/env python
# coding=utf-8

from django.db import models
from django.conf import settings
from django.db.models import QuerySet, IntegerField

from api.tool.datetime_tool import get_timestamp_or_none

from .doctor import Doctor


class SaleDetail(models.Model):
    """销售详情"""

    class Meta:
        app_label = 'doctor'

    doctor = models.ForeignKey(Doctor, null=False, verbose_name=u'关联的医生')
    # 存储当月第一天
    date = models.DateField(null=False, verbose_name=u'统计月份')

    order_total = models.IntegerField(default=0, verbose_name=u"成单量")
    validated_total = models.IntegerField(default=0, verbose_name=u"验证单量")
    refund_total = models.IntegerField(default=0, verbose_name=u"退款单量")

    # 当月销售的所有美购信息, json array
    # 例：[{"id": int, "order_total": int, "validated_total": int, "refund_total": int, "start_time": xxx}, {...}]
    # 相关美购的信息每个item包括：美购id，单个美购当月成单量，单个美购当月验证单量，单个美购当月退款单量，美购上线时间
    # json array 按照美购上线时间倒序排序（最新上线的美购在第一个）
    service_infos = models.TextField(verbose_name=u'相关美购')


class WorkReport(models.Model):
    """工作日报"""

    class Meta:
        app_label = 'doctor'

    doctor = models.ForeignKey(Doctor, null=False, verbose_name=u'关联的医生')
    date = models.DateField(null=False, verbose_name=u'日报日期')

    msg_received = models.IntegerField(default=0, verbose_name=u"私信-收到")
    msg_sended = models.IntegerField(default=0, verbose_name=u"私信-发出")

    # 包括所有类型帖子的回复、日记本的回复、回复的回复
    replied = models.IntegerField(default=0, verbose_name=u"回复帖子数")
    best_replied = models.IntegerField(default=0, verbose_name=u"优质问答数")

    service_saled_users = models.IntegerField(default=0, verbose_name=u"美购-购买人次")
    service_saled_money = models.FloatField(verbose_name=u"美购-销售金额")
    service_validated_users = models.IntegerField(default=0, verbose_name=u"美购-验证人次")
    service_validated_money = models.FloatField(verbose_name=u"美购-入账金额")

    diary_created = models.IntegerField(default=0, verbose_name=u"创建新日记本人数")
    diary_updated = models.IntegerField(default=0, verbose_name=u"更新日记本人数")
    # 日记本和日记贴
    diary_replied = models.IntegerField(default=0, verbose_name=u"日记本-评论数")
    # 日记本和日记贴
    diary_voted = models.IntegerField(default=0, verbose_name=u"日记本-新点赞")
    diary_home = models.IntegerField(default=0, verbose_name=u"日记本-上首页数")

    reservation_accepted = models.IntegerField(default=0, verbose_name=u"预约-医生确认的预约")

    def to_data(self):
        return {
            'date': get_timestamp_or_none(self.date),
            'msg_received': self.msg_received,
            'msg_sended': self.msg_sended,
            'replied': self.replied,
            'best_replied': self.best_replied,
            'service_saled_users': self.service_saled_users,
            'service_saled_money': self.service_saled_money,
            'service_validated_users': self.service_validated_users,
            'service_validated_money': self.service_validated_money,
            'diary_created': self.diary_created,
            'diary_updated': self.diary_updated,
            'diary_replied': self.diary_replied,
            'diary_voted': self.diary_voted,
            'diary_home': self.diary_home,
            'reservation_accepted': self.reservation_accepted,
        }


class TrafficStat(models.Model):
    """医生流量分析"""

    class Meta:
        app_label = 'doctor'
        db_table = 'ml_doctor_stat_updates'

    class TrafficStatManager(models.Manager):
        """!!!这个表没有在zhengxing库里"""

        def get_queryset(self):
            qs = QuerySet(self.model).using(settings.DOCTOR_TRAFFIC_DB)
            return qs

    objects = models.Manager().db_manager(using=settings.DOCTOR_TRAFFIC_DB)

    # doctor = models.ForeignKey(Doctor, null=False)
    doctor_id = models.CharField(verbose_name=u'医生ID', max_length=100, null=False)
    date = models.CharField(null=False, max_length=20, verbose_name="统计日期")
    service_pv_num = models.IntegerField(null=True, verbose_name='美购详情页浏览数')
    home_pv_num = models.IntegerField(null=True, verbose_name='医生/机构主页浏览数')
    phone_received_num = models.IntegerField(null=True, verbose_name='接听电话数')
    phone_not_received_num = models.IntegerField(null=True, verbose_name='未接听电话数')
    conversation_num = models.IntegerField(null=True, verbose_name='私信对话数')
    created_order_num = models.IntegerField(null=True, verbose_name='创建订单数')
    created_order_money = models.IntegerField(null=True, verbose_name='创建订单总额')
    paid_order_num = models.IntegerField(null=True, verbose_name='支付订单数')
    paid_order_money = models.IntegerField(null=True, verbose_name='支付订单总额')
    validate_order_num = models.IntegerField(null=True, verbose_name='验证订单数')
    validate_order_money = models.IntegerField(null=True, verbose_name='验证订单总额')
    new_diary_book_num = models.IntegerField(null=True, verbose_name='新增有效日记本数')
    new_diary_num = models.IntegerField(null=True, verbose_name='新增日记贴数')


class TrafficStatByHour(models.Model):
    """医生流量分析按小时"""

    class Meta:
        app_label = 'doctor'
        db_table = 'al_doctor_stat_hour_repo'

    class TrafficStatByHourManager(models.Manager):
        """!!!这个表没有在zhengxing库里"""

        def get_queryset(self):
            qs = QuerySet(self.model).using(settings.DOCTOR_TRAFFIC_DB)
            return qs

    objects = TrafficStatByHourManager()

    doctor_id = models.CharField(verbose_name=u'医生ID', max_length=100, null=False)
    date = models.CharField(null=False, max_length=20, verbose_name="统计日期")
    service_pv_num = models.IntegerField(null=True, verbose_name='美购详情页浏览数')
    home_pv_num = models.IntegerField(null=True, verbose_name='医生/机构主页浏览数')
    phone_received_num = models.IntegerField(null=True, verbose_name='接听电话数')
    phone_not_received_num = models.IntegerField(null=True, verbose_name='未接听电话数')
    conversation_num = models.IntegerField(null=True, verbose_name='私信对话数')
    created_order_num = models.IntegerField(null=True, verbose_name='创建订单数')
    created_order_money = models.IntegerField(null=True, verbose_name='创建订单总额')
    paid_order_num = models.IntegerField(null=True, verbose_name='支付订单数')
    paid_order_money = models.IntegerField(null=True, verbose_name='支付订单总额')
    validate_order_num = models.IntegerField(null=True, verbose_name='验证订单数')
    validate_order_money = models.IntegerField(null=True, verbose_name='验证订单总额')
    new_diary_book_num = models.IntegerField(null=True, verbose_name='新增有效日记本数')
    new_diary_num = models.IntegerField(null=True, verbose_name='新增日记贴数')
    hour = models.IntegerField(null=True, verbose_name='小时0-23')


def async_data(start, end):
    c_old = TrafficStat.objects.filter(id__gte=start, id__lt=end).order_by('id')
    step = 1000
    count = c_old.count()
    begin = 0
    while begin + step < count:
        for c in c_old[begin: step + begin]:
            print c.id
            for i in range(0, 24):
                TrafficStatByHour.objects.create(
                    doctor_id=c.doctor_id,
                    date=c.date,
                    service_pv_num=c.service_pv_num,
                    home_pv_num=c.home_pv_num,
                    phone_received_num=c.phone_received_num,
                    phone_not_received_num=c.phone_not_received_num,
                    conversation_num=c.conversation_num,
                    created_order_num=c.created_order_num,
                    created_order_money=c.created_order_money,
                    paid_order_num=c.paid_order_num,
                    paid_order_money=c.paid_order_money,
                    validate_order_num=c.validate_order_num,
                    validate_order_money=c.validate_order_money,
                    new_diary_book_num=c.new_diary_book_num,
                    new_diary_num=c.new_diary_num,
                    hour=i
                )
        begin += step


class StatDoctorDaily(models.Model):
    """医生流量用于hera数据统计"""

    class Meta:
        app_label = 'doctor'
        db_table = 'al_doctor_stat_for_operating'
    objects = models.Manager().db_manager(using=settings.DOCTOR_TRAFFIC_DB)

    doctor_id = models.CharField('医生ID', max_length=100)
    date = models.CharField("统计日期", max_length=20)
    service_pv_num = IntegerField('美购详情页浏览数', default=0)
    home_pv_num = IntegerField('医生/机构主页浏览数', default=0)
    phone_received_num = IntegerField('接听电话数', default=0)
    phone_not_received_num = IntegerField('未接听电话数', default=0)
    conversation_num = IntegerField('私信对话数', default=0)
    created_order_num = IntegerField('创建订单数', default=0)
    created_order_money = IntegerField('创建订单总额', default=0)
    paid_order_num = IntegerField('支付订单数', default=0)
    paid_order_money = IntegerField('支付订单总额', default=0)
    validate_order_num = IntegerField('验证订单数', default=0)
    validate_order_money = IntegerField('验证订单总额', default=0)
    new_diary_book_num = IntegerField('新增有效日记本数', default=0)
    new_diary_num = IntegerField('新增日记贴数', default=0)
    paid_order_discount = IntegerField('支付订单抽成额', default=0)
