# coding=utf-8
# create by oldman at 2018/1/10
import datetime
from celery import shared_task
from django.db import transaction
from gm_types.doctor import USER_BROWSING_TYPE
from gm_types.gaia import DOCTOR_TYPE
from hippo.models import Doctor, logging_exception
from hippo.models import MerchantRelevance
from hippo.models.userbrowsing import UserBrowsing, UserBrowsingDetail


@shared_task
def add_user_browsing(data_info):
    """
    添加一条用户浏览记录
    :param data_info:
    :return:
    """
    try:
        with transaction.atomic():
            info_id = data_info.get('id')
            page_type = data_info.get('page_type')
            last_browsing_time = data_info.get('browsing_time',
                                               datetime.datetime.now()
                                               )
            if page_type == USER_BROWSING_TYPE.SERVICE:
                from api import Service
                service = Service.objects.get(id=info_id)
                doctor = service.doctor
            if page_type == USER_BROWSING_TYPE.DOCTOR:
                doctor = Doctor.objects.get(id=info_id)
            if page_type == USER_BROWSING_TYPE.HOSPITAL:
                doctor = Doctor.objects.filter(hospital_id=info_id,
                                               doctor_type=DOCTOR_TYPE.OFFICER
                                               ).first()
            merchant = MerchantRelevance.objects.get(doctor_id=doctor.id).merchant
            user_browsing, _ = UserBrowsing.objects.get_or_create(user_id=data_info.get('user_id'),
                                                                  merchant=merchant
                                                                  )
            user_browsing.last_browsing_time = last_browsing_time
            user_browsing.save()
            user_browsing.last_browsing_time = data_info.get('browsing_time', datetime.datetime.now())
            user_browsing.save()
            UserBrowsingDetail.objects.create(
                user_id=data_info.get('user_id'),
                page_type=page_type,
                browsing_time=last_browsing_time,
                info_id=info_id,
                userbrowsing=user_browsing
            )
    except Exception:
        logging_exception()
