# coding: utf-8
import json

from gm_types.gaia import PLATFORM_CHANNEL, PROMOTION_CHANNEL_NAME, MOMO_STAT_LOG_TYPE, MOMO_STAT_LOG_MESSAGE_TYPE

from api.models import Person, Service
from api.tool.user_tool import get_user_from_context
from api.tasks.period_task import momo_stat_log
from pay.models import MomoStatLog
from rpc.decorators import bind_context, bind


@bind('api/cooperatechannel/stat')
def stat(info_list, stat_log_type, promotion_channel_name):
    if promotion_channel_name == PROMOTION_CHANNEL_NAME.MOMO:
        momo_stat_log(info_list, stat_log_type)
    else:
        pass


@bind_context('api/momo/stat')
def momo_stat(ctx, momo_stat_log_type, service_id):
    """打点方法 暴露出来

    :param MOMO_STAT_LOG_MESSAGE_TYPE momo_stat_log_type: 打点类型
    :param int service_id: 美购ID
    :return:
    """
    user = get_user_from_context(ctx)
    p = Person.objects.filter(user_id=user.id).last()
    hospital_id = Service.objects.filter(id=service_id).values_list('doctor__hospital_id', flat=True).first()
    if p and p.platform == PLATFORM_CHANNEL.MOMO:
        username = user.username
        momo_user_id = "" if not username or not username.startswith("momo_") else username.split("momo_", 1)[-1]
        info_list = {
            "momo_user_id": momo_user_id,
            "product_id": service_id,
            "hospital_id": hospital_id and hospital_id or "",
        }
        json_text = json.dumps(info_list)
        if momo_stat_log_type == MOMO_STAT_LOG_TYPE.CONVERSATION_FIRST_REPLY:
            MomoStatLog(message_type=MOMO_STAT_LOG_MESSAGE_TYPE.CONVERSATION_FIRST_REPLY, json_text=json_text).save()
