# coding=utf-8

import json
from datetime import datetime

from celery import shared_task
from django.conf import settings
from django.db.models import Q

from gm_types.gaia import TOPRANK_TYPE, TAG_V3_TYPE, SLIDE_VERSION
from gm_upload import set_text_watermark

from rpc.context import get_rpc_remote_invoker
from rpc.tool.log_tool import personal_slide_logger
from rpc.cache import personal_slide_cache, personal_slide_cache_image
from gaia.routers import thread_local
from api.models import City
from group.service import GroupService
from group.models import GroupTagV3
from api.models.toprank import TopRankMeddle
from agile.models import TagV3
from agile.models.tag import TagMapCity


api_toprank_search = "doris/search/bangdan"
api_poseidon_page = "poseidon/visual/page/detail"
rpc_invoker = get_rpc_remote_invoker()

images_conf = {
    "same_city_group": {
        SLIDE_VERSION.V1: {
            2: "slide/2020/08/18/0efa427f10",
            3: "slide/2020/08/18/6ea0b3a992",
            4: "banner/2020/08/18/6c39def742",
        },
        SLIDE_VERSION.V2: {
            2: "slide/2020/08/18/769e6f853a",
            3: "slide/2020/08/18/78bce4597c",
            4: "banner/2020/08/18/c8d9a344d2",
        },
    },
    "same_city_toprank_doctor": {
        SLIDE_VERSION.V1: {
            2: "slide/2020/08/18/03af33b821",
            3: "slide/2020/08/18/6b53a58786",
            4: "banner/2020/08/18/6edc54c1db",
        },
        SLIDE_VERSION.V2: {
            2: "slide/2020/08/18/a8dcb1f7bc",
            3: "slide/2020/08/18/764c22859d",
            4: "banner/2020/08/18/6d6d425ed4",
        },
    },
    "same_city_toprank_hospital": {
        SLIDE_VERSION.V1: {
            2: "slide/2020/08/18/f04b993b66",
            3: "slide/2020/08/18/0031571f19",
            4: "banner/2020/08/18/30a92af6f9",
        },
        SLIDE_VERSION.V2: {
            2: "slide/2020/08/18/9799c822b7",
            3: "slide/2020/08/18/01059fe13a",
            4: "banner/2020/08/18/a4f14e82a4",
        },
    },
    "same_city_clinical_doctor": {
        SLIDE_VERSION.V1: {
            2: "slide/2020/08/18/cab4369b32",
            3: "slide/2020/08/18/97ff11da22",
            4: "banner/2020/08/18/7e4d5f63bb",
        },
        SLIDE_VERSION.V2: {
            2: "slide/2020/08/18/10c64e6826",
            3: "slide/2020/08/18/10c64e6826",
            4: "banner/2020/08/18/ca18d21c6a",
        },
    },
    "same_city_kuaishang": {
        SLIDE_VERSION.V1: {
            2: "slide/2020/08/18/382ba04ffc",
            3: "slide/2020/08/18/fe05ea5630",
            4: "banner/2020/08/18/084fa7ff08",
        },
        SLIDE_VERSION.V2: {
            2: "slide/2020/08/18/a4b7afb42d",
            3: "slide/2020/08/18/a5d67fa893",
            4: "banner/2020/08/18/ae2bccfc7d",
        },
    },
    "same_city_new_user_skill": {
        SLIDE_VERSION.V1: {
            2: "2020/08/31/d9e470c360",
            3: "2020/08/31/e650b456b1",
            4: "2020/08/31/938f6f662f",
        },
        SLIDE_VERSION.V2: {
            2: "2020/08/31/32e712e5a6",
            3: "2020/08/31/59618c9989",
            4: "2020/08/31/f186059c9c",
        },
    },
}


def image_name(path, city_id, show_version):
    image = '/'.join(["slide", path, show_version, city_id])
    return image


def set_text(title, image_url, image, dis_x=28):

    persistentId = set_text_watermark(
        title, image_url, image,
        bucket_name="hera",
        font_size=384,
        text_color="FFFFFF",
        font_name='微软雅黑',
        dis_x=dis_x,
        dis_y=15,
    )

    return persistentId


def log(data):

    if settings.DEBUG:
        print(data)

    if isinstance(data, str):
        data = data
    elif isinstance(data, (dict, list, tuple)):
        data = json.dumps(data)
    else:
        data = str(data)

    personal_slide_logger.info(data)


@shared_task
@thread_local(DB_FOR_READ_OVERRIDE=settings.SLAVE_DB_NAME)
def same_city_group():
    """同城小组"""

    tag_ids = list(TagV3.objects.filter(tag_type=TAG_V3_TYPE.CITY).values_list("id", flat=True))
    city2tag = {
        item.city_id: item.tag_id
        for item in TagMapCity.objects.filter(tag_id__in=tag_ids)
    }

    for city in City.objects.all():
        tag_id = city2tag.get(city.id)
        if not tag_id:
            continue

        group_tag = GroupTagV3.objects.filter(tag_v3_id=tag_id, is_online=True).first()
        group_id = None
        if group_tag:
            group_id = group_tag.group_id

        if not group_id:
            continue

        try:
            group = GroupService.safe_get(group_id)
        except:
            continue

        join_cnt = GroupService.join_cnt(group)
        title = "{}{}人加入".format(city.name, join_cnt if join_cnt < 10000 else ('%.1f万' % (join_cnt/10000.0)))

        k = "same_city_group"
        for show_version in [SLIDE_VERSION.V1, SLIDE_VERSION.V2]:

            cache = "same_city_group:{}".format(show_version)
            image = image_name(k, city.id, show_version)
            set_text(title, images_conf[k][show_version].get(len(city.name), 4), image)

            log({"key": k, "title": title, "city_id": city.id, "img": image, "target_id": group_id, "show_version": show_version})
            personal_slide_cache.hset(cache, city.id, json.dumps({"img": image, "target_id": group_id}))


def get_toprank_meddle(city_id, rank_type):
    """获取人工干预的数据"""

    now = datetime.now()
    query = Q(city_id=city_id, rank_type=rank_type, is_online=True, start_time__lt=now, end_time__gt=now)
    target_ids = list(TopRankMeddle.objects.filter(query).values_list("target_id", flat=True))

    return target_ids


@shared_task
@thread_local(DB_FOR_READ_OVERRIDE=settings.SLAVE_DB_NAME)
def same_city_toprank_doctor(force=False):
    """医生榜单"""

    for city in City.objects.all():

        data = rpc_invoker[api_toprank_search](
             device_id='',
             user_city_tag_id=city.tag_id,
             size=15,
             offset=0,
             is_officer=False,
             unit_ids=get_toprank_meddle(city.id, TOPRANK_TYPE.doctor),
        ).unwrap()
        doctor_ids = [item["id"] for item in data if "id" in item]

        k = "same_city_toprank_doctor"

        for show_version in [SLIDE_VERSION.V1, SLIDE_VERSION.V2]:

            img_cache = "same_city_toprank_doctor_img:{}".format(show_version)
            cache = "same_city_toprank_doctor:{}".format(show_version)

            if len(doctor_ids) >= 10:

                image = personal_slide_cache_image.hget(img_cache, city.id)
                if not image or force:
                    title = "{}口碑名医榜单出炉".format(city.name)
                    image = image_name(k, city.id, show_version)
                    set_text(title, images_conf[k][show_version].get(len(city.name), 4), image)

                log({"key": k, "city_id": city.id, "img": image, "show_version": show_version})
                personal_slide_cache_image.hset(img_cache, city.id, image)
                personal_slide_cache.hset(cache, city.id, image)
            else:
                personal_slide_cache.hdel(cache, city.id)


@shared_task
@thread_local(DB_FOR_READ_OVERRIDE=settings.SLAVE_DB_NAME)
def same_city_toprank_hospital(force=False):
    """机构榜单"""

    for city in City.objects.all():

        data = rpc_invoker[api_toprank_search](
             device_id='',
             user_city_tag_id=city.tag_id,
             size=15,
             offset=0,
             is_officer=True,
             unit_ids=get_toprank_meddle(city.id, TOPRANK_TYPE.hospital)
        ).unwrap()
        hospital_ids = [item["id"] for item in data if "id" in item]

        k = "same_city_toprank_hospital"

        for show_version in [SLIDE_VERSION.V1, SLIDE_VERSION.V2]:

            img_cache = "same_city_toprank_hospital_img:{}".format(show_version)
            cache = "same_city_toprank_hospital:{}".format(show_version)

            if len(hospital_ids) >= 10:
                image = personal_slide_cache_image.hget(img_cache, city.id)
                if not image or force:
                    image = image_name(k, city.id, show_version)
                    set_text("{}明星机构入榜快来看".format(city.name), images_conf[k][show_version].get(len(city.name), 4), image)

                log({"key": k, "city_id": city.id, "img": image, "show_version": show_version})
                personal_slide_cache_image.hset(img_cache, city.id, image)
                personal_slide_cache.hset(cache, city.id, image)
            else:
                personal_slide_cache.hdel(cache, city.id)


@shared_task
@thread_local(DB_FOR_READ_OVERRIDE=settings.SLAVE_DB_NAME)
def same_city_clinical_doctor(force=False):
    """视频面诊"""

    for city in City.objects.all():

        k = "same_city_clinical_doctor"

        for show_version in [SLIDE_VERSION.V1, SLIDE_VERSION.V2]:

            img_cache = "same_city_clinical_doctor_img:{}".format(show_version)
            cache = "same_city_clinical_doctor:{}".format(show_version)

            image = personal_slide_cache_image.hget(img_cache, city.id)
            if not image or force:
                title = "{}1万+人 | 在线咨询".format(city.name)
                image = image_name(k, city.id, show_version)
                set_text(title, images_conf[k][show_version].get(len(city.name), 4), image)

            log({"key": k, "city_id": city.id, "img": image, "show_version": show_version})
            personal_slide_cache_image.hset(img_cache, city.id, image)
            personal_slide_cache.hset(cache, city.id, image)


@shared_task
@thread_local(DB_FOR_READ_OVERRIDE=settings.SLAVE_DB_NAME)
def same_city_kuaishang(force=False):
    """人工咨询"""

    for city in City.objects.all():

        k = "same_city_kuaishang"

        for show_version in [SLIDE_VERSION.V1, SLIDE_VERSION.V2]:

            img_cache = "same_city_kuaishang_img:{}".format(show_version)
            cache = "same_city_kuaishang:{}".format(show_version)

            image = personal_slide_cache_image.hget(img_cache, city.id)
            if not image or force:
                title = "{}1万+人 | 已咨询".format(city.name)
                image = image_name(k, city.id, show_version)
                set_text(title, images_conf[k][show_version].get(len(city.name), 4), image)

            log({"key": k, "city_id": city.id, "img": image})
            personal_slide_cache_image.hset(img_cache, city.id, image)
            personal_slide_cache.hset(cache, city.id, image)


@shared_task
@thread_local(DB_FOR_READ_OVERRIDE=settings.SLAVE_DB_NAME)
def same_city_new_user_skill(force=False):
    """新人秒杀"""

    for city in City.objects.all():

        k = "same_city_new_user_skill"

        for show_version in [SLIDE_VERSION.V1, SLIDE_VERSION.V2]:

            img_cache = "same_city_new_user_skill_img:{}".format(show_version)
            cache = "same_city_new_user_skill:{}".format(show_version)

            image = personal_slide_cache_image.hget(img_cache, city.id)
            if not image or force:
                title = "{}热卖秒杀项目等你体验".format(city.name)
                image = image_name(k, city.id, show_version)
                set_text(title, images_conf[k][show_version].get(len(city.name), 4), image)

            log({"key": k, "city_id": city.id, "img": image, "show_version": show_version})
            personal_slide_cache_image.hset(img_cache, city.id, image)
            personal_slide_cache.hset(cache, city.id, image)
