# coding:utf-8
"""免费招募活动相关push service。"""

from datetime import datetime

from django.conf import settings
from gm_types.gaia import FREER_RECRUITMENT_PUSH_TYPE

from utils.wechat_applet_tools import applet_template_push
from api.util.user_util import simple_user_info_by_user_ids
from api.util.user_util import get_open_id_by_user_id
from api.tool.wechat_push import get_wechat_access_token
from rpc.tool.log_tool import logging_exception, user_logger


class FreeRecruitmentPushService(object):

    @classmethod
    def get_grade(cls, vote_num):

        if vote_num < 3:
            return {"percent": 40, "grade": "基础"}
        elif vote_num < 5:
            return {"percent": 50, "grade": "中级"}
        elif vote_num < 10:
            return {"percent": 60, "grade": "高级"}
        elif vote_num >= 10:
            return {"percent": 80, "grade": "最高"}

    @classmethod
    def get_template_id(cls, push_type):

        if push_type == FREER_RECRUITMENT_PUSH_TYPE.VOTED:  # 好友助力
            return settings.FREE_RECRUITMENT_TEMPLATE["VOTED"]

        elif push_type == FREER_RECRUITMENT_PUSH_TYPE.ACTIVITY_STARTED:  # 活动开始
            return settings.FREE_RECRUITMENT_TEMPLATE["ACTIVITY_STARTED"]

        elif push_type == FREER_RECRUITMENT_PUSH_TYPE.ACTIVITY_ENDED:  # 活动结束
            return settings.FREE_RECRUITMENT_TEMPLATE["ACTIVITY_ENDED"]

        raise Exception("找不到对应的push_type")

    @classmethod
    def get_template_data(cls, push_type, user_id, extra_info):

        data = {}
        if push_type == FREER_RECRUITMENT_PUSH_TYPE.VOTED:  # 好友助力

            nick_name = extra_info.get("nick_name")
            vote_num = extra_info.get("vote_num")
            if not nick_name or not vote_num:
                return

            data = {
                "keyword1": {
                    "value": u"您的锦鲤好友已经帮你助力{vote_num}次，抽中免费招募概率持续增加".format(vote_num=vote_num),
                },
                "keyword2": {
                    "value": u"{nick_name}".format(nick_name=nick_name)
                },
                "keyword3": {
                    "value": datetime.now().strftime("%Y年%m月%d日 %H:%M:%S")
                },
                "keyword4": {
                    "value": u"概率增加至{percent}%，锦鲤等级：{grade}".format(**cls.get_grade(vote_num))
                },
            }

        elif push_type == FREER_RECRUITMENT_PUSH_TYPE.ACTIVITY_STARTED:  # 活动开始

            start_time = extra_info.get("start_time")
            end_time = extra_info.get("end_time")
            activity_title = extra_info.get("activity_title")
            if not any([start_time, end_time, activity_title]):
                return

            data = {
                "keyword1": {
                    "value": u"您预约的免费招募活动：{title}".format(title=activity_title),
                },
                "keyword2": {
                    "value": u"{start_time}".format(start_time=start_time)
                },
                "keyword3": {
                    "value": u"{end_time}".format(end_time=end_time)
                },
            }

        elif push_type == FREER_RECRUITMENT_PUSH_TYPE.ACTIVITY_ENDED:  # 活动结束

            nick_name = extra_info.get("nick_name")
            activity_title = extra_info.get("activity_title")
            if not any([nick_name, activity_title]):
                return

            data = {
                "keyword1": {
                    "value": u"{title}".format(title=activity_title)
                },
                "keyword2": {
                    "value": u"{nick_name}".format(nick_name=nick_name)
                },
                "keyword3": {
                    "value": u"已经结束，我们会电话联系抽中报名者"
                },
                "keyword4": {
                    "value": u"快打开小程序，还有0元秒杀好礼大优惠等你拿！"
                },
            }

        return data

    @classmethod
    def send_template_msg(cls, push_type, extra_info, user, page, form_id):

        template_id = cls.get_template_id(push_type)
        data = cls.get_template_data(push_type, user["user_id"], extra_info)
        if not data:
            user_logger.info("send_template_msg not fund data")
            return

        open_id = get_open_id_by_user_id(user['user_id'])
        if not open_id:
            return

        access_token = get_wechat_access_token()
        applet_template_push(
            access_token,
            open_id,
            template_id,
            form_id,
            data=data,
            page=page
        )
