# coding:utf8

import json
import random
import time

from sms.utils.smsfactory import send_sms
from rpc.tool.protocol import PushUrlProtocol
from gm_types.push import PUSH_STAT_CATEGORY
from gm_types.push import PUSH_INFO_TYPE
from gm_types.push import AUTOMATED_PUSH
from gm_types.gaia import ORDER_SOURCE
from api.tool.log_tool import momo_stat_logger
from .user_tool import get_user_by_id

"""
约束
－ 显示销售量要大于实际销售量
－ 显示销售量不能大于显示总数
"""


def order_increase(actual_total, actual_volume, show_total, show_volume):
    increase = random.randint(1, 3)
    return show_volume + increase


def send_order_expired_remind(phone, order_id, service_name, receiver_id, time_left=600):
    """remind user order will be expired in time_left mins(sms and push).

    args:
        time_left: seconds before order expired, default is 600, 10mins
    """
    mins = time_left / 60
    if mins < 1:
        mins = 1
    content = u'您的订单{}将于{}分钟后失效，请您尽快支付！【更美】'.format(service_name, mins)

    kwargs = {
        'user_ids': [receiver_id],
        'push_type': AUTOMATED_PUSH.PAYMENT_REMINDER,
        'platform': ['android', 'iPhone'],
        'extra': {
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'pushUrl': PushUrlProtocol.ORDER_DETAIL.format(id=order_id),
            },
        'alert': content,
    }
    from api.tasks.push_task import automate_push_task
    automate_push_task(**kwargs)
    send_sms(phone, 17, [{'order_id': service_name}])


def push_refund_message(order):
    service_name = order.service.name + order.order_multiattribute
    content = u'您的订单{}已退款！'.format(service_name)
    kwargs = {
        'user_ids': [order.user.id],
        'push_type': AUTOMATED_PUSH.PAYMENT_REFUNDED,
        'platform': ['android', 'iPhone'],
        'extra': {
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'pushUrl': PushUrlProtocol.ORDER_DETAIL.format(id=order.id),
            'push_url': PushUrlProtocol.ORDER_DETAIL.format(id=order.id),
        },
        'alert': content,
    }
    from api.tasks.push_task import automate_push_task
    automate_push_task(**kwargs)


def send_remind_to_evaluate_order(order):
    push_msg = u'亲，您有待评价订单哦，快去评价吧'
    url = PushUrlProtocol.UPDATE_DIARY_OPERATION.format(id=order.diary.id)

    kwargs = {
        'user_ids': [order.user.id],
        'push_type': AUTOMATED_PUSH.PAYMENT_EVALUATE,
        'platform': ['android', 'iPhone'],
        'extra': {
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'pushUrl': url,
            },
        'alert': push_msg,
    }
    from api.tasks.push_task import automate_push_task
    automate_push_task(**kwargs)


def send_repurchase_reminder_msg(order, days):
    service_snapshot = json.loads(order.service_snapshot)
    push_msg = u'距离你上次购买%s项目已经%s个月了，再做一次效果会更好哦，点击再次购买～'
    month = days / 30
    push_msg = push_msg % (service_snapshot['name'], month)

    kwargs = {
        'user_ids': [order.user.id],
        'push_type': AUTOMATED_PUSH.PAYMENT_AGAIN,
        'platform': ['android', 'iPhone'],
        'extra': {
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'pushUrl': PushUrlProtocol.PROMOTION_DETAIL.format(id=order.service.id),
            },
        'alert': push_msg,
    }
    from api.tasks.push_task import automate_push_task
    automate_push_task(**kwargs)

    # send notification
    from api.tool.notification_tool import send_notification
    send_notification(
        order.user.id,
        u'复购提醒',
        push_msg,
        PushUrlProtocol.PROMOTION_DETAIL.format(id=order.service.id)
    )

    # send sms
    sms_msg = push_msg + u'更美APP下载地址: http://dwz.cn/2e23Hq 【更美】'
    send_sms(order.phone, 21, [{'service': service_snapshot['name']}, {'number': month}])


def push_cash_back_message(order, price):
    service_name = order.service.name + order.order_multiattribute
    content = u'您的订单{}已返现{}元！'.format(service_name, price)
    kwargs = {
        'user_ids': [order.user.id],
        'push_type': AUTOMATED_PUSH.PAYMENT_CASH_BACK,
        'platform': ['android', 'iPhone'],
        'extra': {
            'type': PUSH_INFO_TYPE.GM_PROTOCOL,
            'pushUrl': PushUrlProtocol.ORDER_DETAIL.format(id=order.id),
            },
        'alert': content,
    }
    from api.tasks.push_task import automate_push_task
    automate_push_task(**kwargs)


def get_momo_stat_log_info(order):
    """
    格式化 陌陌打点参数信息
    :param order:
    :return:
    """
    from api.models import Person
    from api.models.types import PLATFORM_CHANNEL

    if order.source != ORDER_SOURCE.MOMO:
        return {}

    p = Person.objects.filter(user_id=order.user_id).last()
    if p and p.platform == PLATFORM_CHANNEL.MOMO:

        def _convert_momo_user_id(user):
            """从我们的用户信息，切出momo_user_id"""
            username = user and user.username or ""
            return username.startswith("momo_") and username.split("momo_", 1)[-1] or ""

        user = get_user_by_id(order.user_id)
        _data = {
            "momo_user_id": _convert_momo_user_id(user),
            "product_id": order.service_id,
            "service_item_id": order.service_item_id,
            "order_id": order.id,
            "money": order.real_payment,
        }
        return _data
    else:
        return {}


def send_momo_stat_log_info_when_order_refunded(order):
    from gm_types.gaia import MOMO_STAT_LOG_TYPE
    from api.tasks.period_task import momo_stat_log

    momo_param_info = get_momo_stat_log_info(order)
    if momo_param_info:
        # 异步打点前，落日志
        _data = {
            "source": "momo_pre_stat_log",
            "momo_stat_log_type": MOMO_STAT_LOG_TYPE.ORDER_REFUND_SUCCESS,
            "info_list": [momo_param_info, ],
            "pre_stat_log_time": time.time(),
        }
        momo_stat_logger.info("momo_pre_stat_log_info:{}".format(json.dumps(_data)))
        momo_stat_log.delay(
            info_list=[momo_param_info, ],
            stat_log_type=MOMO_STAT_LOG_TYPE.ORDER_REFUND_SUCCESS
        )


def get_live_order_stat_log(order):
    """
    格式化 直播订单转化信息
    :param order:
    :return:
    """

    return {
        "user_id": order.user_id,
        "order_id": order.id,
        "service_id": order.service_id,
        "service_item_id": order.service_item_id,
        "money": order.service_price
    }