# -*- coding:utf-8 -*-
# author:gm
# mail: zhangguodong@igengmei.com
# datetime:2020/4/24 3:32 下午
# software: PyCharm

from api.models.advertise_management import AdvertiseManagement
from django.utils import timezone
from injection.data_sync.views import write_to_es
from api.tool.log_tool import logging_exception
from celery import shared_task


class CPTSync(object):

    def __init__(self):
        pass

    def get_update_serviceids(self):
        ads = AdvertiseManagement.objects.distinct().values("service_id")
        datas = []
        for id in ads:
            datas.append(id)
            if len(datas) > 20:
                try:
                    write_to_es("service", datas, None)
                    datas = []
                except Exception as e:
                    datas = []
                    logging_exception()


@shared_task
def get_update_serviceids():
    ads = list(AdvertiseManagement.objects.distinct().values_list("service_id", flat=True))
    datas = []
    for id in ads:
        datas.append(id)
        if len(datas) > 20:
            try:
                write_to_es("service", datas, None)
                datas = []
            except Exception as e:
                datas = []
                logging_exception()
    write_to_es("service", datas, None)


@shared_task
def compute_doctor_score():
    from statistic.models import DoctorRankFactor, ClueDoctorSmartRank
    import datetime

    date_str = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d")
    doctor_ids = DoctorRankFactor.objects.filter(partition_date=date_str).values_list('doctor_id')

    try:
        partion_date = ClueDoctorSmartRank.objects.all().order_by('-id').first().partion_date
    except:
        partion_date = ""

    # 删除数据
    # max_id = ClueDoctorSmartRank.objects.all().aggregate(Max('id'))['id__max']
    # if max_id:
    #     ClueDoctorSmartRank.objects.filter(id__lte=max_id).delete()

    if partion_date != date_str:
        for doctor_id in doctor_ids:
            doctor_id = str(doctor_id[0])
            smart_rank = DoctorRankFactor.get_doctor_score(doctor_id)

            ClueDoctorSmartRank.objects.create(doctor_id=doctor_id, smart_rank=smart_rank, partion_date=date_str)
