
# coding=utf-8
from celery import shared_task
from gm_types.gaia import USER_CLASSIFY
from hippo.models import Doctor
from statistic.models import Device, MerchantDevice, ClassifyUser

_step = 100

@shared_task
def record_model_user():
    # 获取在线医生的医生id
    doctor_user_ids =  Doctor.objects.filter(is_online=True).values_list('user_id', flat=True)
    # 获取登陆过这些用户的设备
    device_ids = Device.objects.filter(user__in=set(doctor_user_ids)).values_list('id', flat=True)
    # 获取使用过这些设备的所有用户
    model_user_ids = Device.objects.filter(id__in=set(device_ids)).values_list('user', flat=True)
    # 获取这些用户用过的所有设备
    model_device_ids = Device.objects.filter(user__in=set(model_user_ids)).values_list('id', flat=True)
    # 存入设备池
    model_device_ids = list(set(model_device_ids))
    # 设备池全力量覆盖，模特用户表跑增量
    MerchantDevice.objects.all().delete()
    for i in range(0, len(model_device_ids), _step):
        MerchantDevice.objects.bulk_create([MerchantDevice(device_id=id) for id in model_device_ids[i: i+_step]])

    # model用户
    # 拿到一个设备，筛选登陆过这些设备，符合条件的用户作为模特用户
    user_ids = Device.objects.filter(id__in=model_device_ids).values_list('user', flat=True)
    model_user_ids = list(set(user_ids))

    for model_user_id in model_user_ids:
        obj, _ = ClassifyUser.objects.get_or_create(user_id=model_user_id, classify=USER_CLASSIFY.MODEL)

