#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
__title__ = ''
__author__ = 'xierong@gmei.com'
__mtime__ = '17/11/14'
'''
import datetime
from django.conf import settings

from gm_types.user_hierarchy import EventType
from user_hierarchy.models import UserEventLog

from utils.rpc import get_rpc_invoker
from utils.rpc import logging_exception

from ..manager.event_dispatcher import TaskEvent
from ..tasks import add_user_growth, add_user_point
from .user_task_cache import user_task_cache



class TaskCenter(object):
    def __init__(self, user_id, event_type=None, related_item=None, session_key=None):
        self.task_cache = user_task_cache
        self.user_key = str(user_id)+'_'+datetime.datetime.today().strftime('%Y-%m-%d')
        self.task_event = TaskEvent()

        self.event_type = event_type
        self.user_id = user_id
        self.item_id = related_item
        self.session_key = session_key

    def get_reveal_data(self, only_record_event=False):
        re_data = {'growth_value': 0, 'point_value': 0, 'submit_count': 0}
        self._get_task_operate_times()

        if only_record_event:
            return re_data

        value_dict = self.task_event.get_reveal_data(self.event_type, self.operate_count, self.user_id)
        re_data.update(value_dict)
        re_data['submit_count'] = self.operate_count

        return re_data

    def get_daily_task(self):
        # 获取每日任务清单
        re_data = {'uni_task': [], 'multi_task': []}
        uni_task_k_lst = self.task_event.get_diff_type_task('uni')
        multi_task_k_lst = self.task_event.get_diff_type_task('multi')
        for item_k in uni_task_k_lst:
            item_v = self.task_cache.hget(self.user_key, item_k)
            re_data['uni_task'].append({
                'sub_title': '+{0}成长值 +{1}美分'.format(self.task_event.event_handler.get(item_k)[self.task_event.GROWTH_KEY],
                                                     self.task_event.event_handler.get(item_k)[self.task_event.POINT_KEY]),
                'status': 1 if item_v else 0
            })
        for item_k in multi_task_k_lst:
            item_v = self.task_cache.hget(self.user_key, item_k)
            item_v_int = int(item_v) if item_v else 0
            re_data['multi_task'].append({
                'sub_title': '+{0}成长值 +{1}美分'.format(self.task_event.event_handler.get(item_k)[self.task_event.GROWTH_MULTI_KEY],
                                                     self.task_event.event_handler.get(item_k)[self.task_event.POINT_MULTI_KEY]),
                'achieved_count': item_v_int,
                'total_amount': self.task_event.muitl_times,
                'status': 1 if item_v_int >= self.task_event.muitl_times else 0
            })
        return re_data


    def _get_task_operate_times(self):
        # 返回当前请求的操作次数
        operate_count = 1

        if self.task_cache.exists(self.user_key):
            if self.task_cache.hget(self.user_key, self.event_type):
                operate_count = int(self.task_cache.hget(self.user_key, self.event_type)) + 1
                self.task_cache.hincrby(self.user_key, self.event_type)
            else:
                self.task_cache.hset(self.user_key, self.event_type, operate_count)
        else:
            self.task_cache.hset(self.user_key, self.event_type, operate_count)
            today = datetime.datetime.today()
            self.task_cache.expire(self.user_key, (today.replace(hour=0, minute=0, second=0) - today).seconds)

        self.operate_count = operate_count  # 操作次数

    def check_daily_max_limit(self, current_value, item_type='point'):
        # 返回应该加的具体值
        add_v = 0
        if item_type == 'point':
            today_point_v = get_user_point_today_value(self.session_key)
            if today_point_v < settings.POINT_DAILY_LIMIT:
                daily_last_v = settings.POINT_DAILY_LIMIT - today_point_v
                add_v = daily_last_v if daily_last_v < current_value else current_value
        else:
            today_growth_v = UserEventLog().get_user_today_value(self.user_id)

            if today_growth_v < settings.GROWTH_DAILY_LIMIT:
                daily_last_v = settings.GROWTH_DAILY_LIMIT - today_growth_v
                add_v = daily_last_v if daily_last_v < current_value else current_value

        return add_v


    def add_work(self, version):
        value_dict = self.task_event.get(self.user_id, self.event_type, self.operate_count)
        if self.task_event.is_max_limit:
            point_value = self.check_daily_max_limit(value_dict['point_value'], 'point')
            growth_value = self.check_daily_max_limit(value_dict['growth_value'], 'growth')
        else:
            point_value, growth_value = value_dict['point_value'], value_dict['growth_value']

        if point_value or growth_value:
            type_info = self.task_event.get_matched_real_type(self.event_type, self.operate_count)
            real_point_type = type_info['point_type']
            real_growth_type = type_info['growth_type']
            if real_growth_type:
                add_user_growth.delay(self.user_id, real_growth_type, self.item_id, growth_value, version)
            if real_point_type:
                add_user_point.delay(self.user_id, real_point_type, point_value)




def get_user_point_today_value(session_key):
    try:

        from helios.rpc import create_default_invoker
        today_point_v = create_default_invoker(debug=settings.DEBUG).with_config(
            dump_curl=True, session_key=session_key
        )['api/pointsinfo/get_daily_value']().unwrap()

    except:
        logging_exception()
        today_point_v = 0

    return today_point_v
