#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2019/7/2
import json
from datetime import datetime, timedelta

from api.models import Order, ServiceTag, Tag
from gm_types.gaia import ORDER_STATUS, TAG_TYPE
from rpc.tool.log_tool import info_logger

# http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=23890522


def get_target_all_parents_tags_by_tag_id(tag_id):

    """
    获取三级标签所有的二级，一级标签
    :param tag_id: 812
    :return:
    """
    tag_ids_set = set()
    try:
        target = Tag.objects.get(id=tag_id, is_online=True)
        tag_ids_set.add(tag_id)
    except Tag.DoesNotExist:
        return set()

    # 这里可能是二级标签集合, 也可能是一级标签集合
    tag_objs = target.online_parent_tags()

    # 当前标签为三级标签, 过滤出所有的二级标签
    if target.tag_type == TAG_TYPE.ITEM_WIKI:
        for body_part_sub_item_tag in filter(
                lambda x: x.tag_type == TAG_TYPE.BODY_PART_SUB_ITEM, tag_objs):
            body_part_tag_objs = filter(
                lambda x: x.tag_type == TAG_TYPE.BODY_PART, body_part_sub_item_tag.online_parent_tags()
            )
            for body_part_tag in body_part_tag_objs:
                tag_ids_set.add(body_part_tag.id)

            tag_ids_set.add(body_part_sub_item_tag.id)
    elif target.tag_type == TAG_TYPE.BODY_PART_SUB_ITEM:
        # 当前标签为二级标签, 过滤出所有的一级标签
        for _tag in filter(lambda x: x.tag_type == TAG_TYPE.BODY_PART, tag_objs):
            tag_ids_set.add(_tag.id)

    return tag_ids_set


def doctor_care(day, tag_ids):
    """
    术后关怀
    :param day: 获取指定天数的用户
    :param tag_ids: 标签
    :return: 返回满足条件的用户user_ids
    """
    if not isinstance(tag_ids, list):
        return []

    # 获取第xx天
    today, all_satisfied_tag_ids = datetime.today(), set()
    target_day = today - timedelta(days=day)
    target_zerotoday = target_day - timedelta(
        hours=today.hour,
        minutes=today.minute,
        seconds=today.second,
        microseconds=today.microsecond
    )
    target_lasttoday = target_zerotoday + timedelta(
        hours=23, minutes=59, seconds=59
    )

    # 获取所有符合条件的一级, 二级, 三级
    for tag_id in tag_ids:
        all_satisfied_tag_ids |= get_target_all_parents_tags_by_tag_id(tag_id)

    info_logger.info("all_satisfied_tag_ids, counts: %d" % len(all_satisfied_tag_ids))

    all_service_ids = set(ServiceTag.objects.filter(
        tag_id__in=all_satisfied_tag_ids).values_list('service_id', flat=True))

    info_logger.info("all_service_ids, counts: %d, 美购ID: %s" % (
        len(all_service_ids), json.dumps(list(all_satisfied_tag_ids))
    ))

    user_ids = list(set(Order.objects.filter(
        status__in=[ORDER_STATUS.USED, ORDER_STATUS.SETTLED],
        validate_time__range=(target_zerotoday, target_lasttoday),
        service_id__in=all_service_ids
    ).values_list("user_id", flat=True)))

    info_logger.info("satisfied user_ids: %s" % json.dumps(list(user_ids)
    ))

    return user_ids
