# coding=utf-8
# create by oldman at 2018/1/10
import json
from datetime import datetime, date, timedelta
from django.contrib.auth.models import User
from django.db import models
from django.utils.timezone import now
from gm_types.doctor import USER_BROWSING_TYPE
from gm_types.gaia import TAG_TYPE

from api.models import City
from api.models import UserExtra 
from relation.models import UserTagRelation
from hippo.models import Merchant
from hippo.models import Doctor
from gm_types.gaia import USER_CLASSIFY
from django.conf import settings
from django.db.models import QuerySet

CAN_USE_TYPE = [TAG_TYPE.BODY_PART, TAG_TYPE.BODY_PART_SUB_ITEM, TAG_TYPE.ITEM_WIKI]


class UserBrowsing(models.Model):
    class Meta:
        verbose_name = u'用户浏览统计'
        app_label = 'hippo'
        db_table = 'hippo_user_browsing'

    user = models.ForeignKey(User, verbose_name=u'浏览用户')
    last_browsing_time = models.DateTimeField(verbose_name=u'最后浏览时间', default=now())
    merchant = models.ForeignKey(Merchant, verbose_name=u'浏览商户')

    def get_user_info(self):
        """
        返回用户信息
        :return:
        """
        userextra = UserExtra.objects.get(user_id=self.user.id)
        try:
            from statistic.models import Device
            interest = Device.get_interest(self.user)
        except:
            interest = u'暂无'
        city_id = userextra.current_city_id

        try:
            city_name = City.objects.get(id=city_id).name
        except:
            city_name = u'暂无'

        from api.tool.user_tool import filter_user_nick_name
        return {
            'name': filter_user_nick_name(self.user),
            'interest': interest,
            'city_name': city_name
        }

    def get_data(self):
        """
        获取数据
        :return:
        """
        user_info = self.get_user_info()
        doctor = self.merchant.doctor
        user_key = u'_'.join(map(str, sorted([self.user.id, doctor.user.id])))
        return {
            'name': user_info.get('name'),
            'interest': user_info.get('interest'),
            'city_name': user_info.get('city_name'),
            'user_key': user_key,
            'id': self.id
        }


class UserBrowsingDetail(models.Model):
    class Meta:
        verbose_name = u'用户浏览统计详情'
        app_label = 'hippo'
        db_table = 'hippo_user_browsing_detail'

    userbrowsing = models.ForeignKey(UserBrowsing, verbose_name=u'用户浏览统计')
    user = models.ForeignKey(User, verbose_name=u'浏览用户')
    page_type = models.IntegerField(verbose_name=u'页面类型', choices='', default=0)
    browsing_time = models.DateTimeField(verbose_name=u'浏览时间', default=now())
    info_id = models.CharField(verbose_name=u'浏览的ID', null=True, blank=True, max_length=50)

    def get_data(self):
        page_name = ''
        if self.page_type == USER_BROWSING_TYPE.DOCTOR:
            from hippo.models import Doctor
            doctor = Doctor.objects.get(id=self.info_id)
            page_name = doctor.name
        if self.page_type == USER_BROWSING_TYPE.SERVICE:
            from api import Service
            service = Service.objects.get(id=self.info_id)
            page_name = service.name

        if self.page_type == USER_BROWSING_TYPE.HOSPITAL:
            from hippo.models import Hospital
            hospital = Hospital.objects.get(id=self.info_id)
            page_name = hospital.name
        from api.tool.user_tool import filter_user_nick_name
        return {
            'name': filter_user_nick_name(self.user),
            'page_name': page_name,
            'page_type': USER_BROWSING_TYPE.getDesc(self.page_type),
            'browsing_time': self.browsing_time.strftime("%Y-%m-%d %H:%M:%S")
        }

# class ClassifyUser(models.Model):
#     class Meta:
#         unique_together = (
#             "user", "classify"
#         )
#         # app_label = 'api'
#         verbose_name = "用户分类"
#         db_table = "api_classifyuser"
#
#     user_id = models.IntegerField(verbose_name=u'用户')
#     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 MerchantUvStat(models.Model):
    class Meta:
        verbose_name = u'商户uv统计'
        app_label = 'hippo'
        db_table = 'hippo_merchant_uv_stat_streaming'
        unique_together = ('user_id', 'merchant_id')

    class MerchantUvStatManager(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)

    user_id = models.CharField(verbose_name=u'用户ID', max_length=50, null=True)
    user_name = models.CharField(verbose_name=u'用户昵称', max_length=50, null=True)
    city_name = models.CharField(verbose_name=u'城市名字', max_length=50, null=True)
    last_browsing_time = models.DateTimeField(verbose_name=u'最后浏览时间', default=now())
    doctor_id = models.CharField(verbose_name=u'医生ID', max_length=100)
    merchant_id = models.BigIntegerField(verbose_name=u'商户ID')
    tag = models.TextField(verbose_name=u'用户标签', null=True)

    def get_data(self):
        cal_time = datetime.now() - timedelta(days=2)
        can_conversation = MerchantPvStat.objects.filter(
            is_over_three_seconds=True, browsing_time__gte=cal_time,
            user_id=self.user_id, merchant_id=self.merchant_id).exists()
        doctor = Merchant.objects.get(id=self.merchant_id).doctor
        user_key = u'_'.join(map(str, sorted([int(self.user_id), int(doctor.user_id)])))
        user = User.objects.get(id=self.user_id)
        return {
            'name': user.last_name,
            'interest': ','.join([usertag.related_tag.name for usertag in UserTagRelation.objects.filter(
                user_id=self.user_id, related_tag__tag_type__in=CAN_USE_TYPE)][0:3]),
            'city_name': self.city_name,
            'user_key': user_key,
            'id': self.id,
            'user_id': self.user_id,
            'can_conversation': can_conversation
        }


class MerchantPvStat(models.Model):
    class Meta:
        verbose_name = u'用户pv统计'
        app_label = 'hippo'
        db_table = 'hippo_merchant_pv_stat_streaming' 
        unique_together = ('user_id', 'merchant_id', 'browsing_time')

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

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

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

    user_id = models.CharField(verbose_name=u'用户ID', max_length=50, null=True)
    user_name = models.CharField(verbose_name=u'用户昵称', max_length=50, null=True)
    city_name = models.CharField(verbose_name=u'城市名字', max_length=50, null=True)
    browsing_time = models.DateTimeField(verbose_name=u'浏览时间', default=now())
    page_type = models.IntegerField(verbose_name=u'页面类型', choices=USER_BROWSING_TYPE)
    page_name = models.CharField(verbose_name=u'页面名称', max_length=100, null=True)
    is_over_three_seconds = models.BooleanField(verbose_name=u'是否停留超过3秒')
    doctor_id = models.CharField(verbose_name=u'医生ID', max_length=100)
    merchant_id = models.BigIntegerField(verbose_name=u'商户ID')

    def get_data(self):
        user = User.objects.get(id=self.user_id)
        return {
            'name': user.last_name,
            'page_name': self.page_name,
            'page_type': USER_BROWSING_TYPE.getDesc(self.page_type),
            'browsing_time': self.browsing_time.strftime("%Y-%m-%d %H:%M:%S")
        }


class MerchantDailyConv(models.Model):
    class Meta:
        verbose_name = u'商户每日主动私信统计'
        app_label = 'hippo'

    merchant_id = models.BigIntegerField(verbose_name=u'商户ID', db_index=True)
    user_id = models.CharField(verbose_name=u'用户ID', max_length=50, null=True)
    date = models.DateField(verbose_name=u'主动私信时间', default=date.today)
