#!/usr/bin/env python
# coding=utf-8
import json
import datetime

from api.models import Person
from api.models import Service
from doctor.models import Notification

from api.tool.user_tool import filter_user_nick_name, get_portrait_by_user
from api.tool.datetime_tool import get_timestamp
from api.tool.log_tool import logging_exception
from rpc.cache import doctor_patient_cache

from gm_types.gaia import REFUND_STATUS


class Patient(object):
    """医生患者 since 2.2.0
        暂时使用redis存储，放在这以后方便迁移数据库
    """

    @classmethod
    def join_patient_list(cls, doctor_id, last_notify, order=None, refund=None, diary=None, topic=None):
        """
            加入患者列表
            args:
                doctor_id: 相关医生id
                last_notify: 关联患者的最后一条通知id, 用户展示列表中的数据显示
                order: !=None时，因订单相关操作 加入 患者列表
                        目前订单操作包括 --> 验证美购、购买美购
                refund: !=None时，因退款相关操作 加入 患者列表
                        目前退款操作包括 --> 申请退款
                diary: !=None时，因案例相关操作加入 患者列表
                        目前案例操作包括 --> 创建或更新日记本

            在redis中存储的结构：
                prefix --> doctor_patient
                key --> doctor_id ==> list存储[person_id1, person_id2, ....], 目的保证排序
                key --> doctor_id + '_data' ==> hash存储(person_id, value)
                        value格式如下(JSON的格式存储):
                            *patient_id: 相关患者（用户），即person_id
                            *user_id: 用于私信需要
                            *last_notify: 关联患者的最后一条通知的id
                            *operation_name: 手术名称，即 service.name取【】中的内容 / diary.title
                            *operation_time: 手术时间，也就是订单的验证时间，仅当 验证时记录, 存毫秒数
                            *updated_time: 患者信息更新时间，用于在患者列表排序的, 存毫秒数
            added in 7.6.40 topic 传入的是所需要的dict info
                            
        """
        person_id = str(last_notify.person_id)
        if refund and refund.status != REFUND_STATUS.PROCESSING:  # 退款：只有申请推荐影响排序
            pass
        else:
            doctor_patient_cache.lrem(doctor_id, 1, person_id)  # 从列表中移除
            doctor_patient_cache.lpush(doctor_id, person_id)  # 加入到表头, 保证排序
        info = {
                'patient_id': person_id,
                'last_notify': last_notify.id,
                'updated_time': get_timestamp(datetime.datetime.now()),
                }
        if order:
            info['operation_name'] = cls.gen_opeartion_name(order.service.name)
            info['operation_time'] = get_timestamp(order.validate_time)
        elif refund:
            info['operation_name'] = cls.gen_opeartion_name(refund.order.service.name)
        elif diary:
            if diary.service_id:
                _s = Service.objects.get(id=diary.service_id)
                service_name = _s.name
                info['operation_name'] = cls.gen_opeartion_name(service_name)
            else:
                info['operation_name'] = diary.title
            info['operation_time'] = get_timestamp(diary.operation_time)
        elif topic:
            if topic.get('service_id'):
                _s = Service.objects.get(id=topic.get('service_id'))
                service_name = _s.name
                info['operation_name'] = cls.gen_opeartion_name(service_name)

        info = json.dumps(info)
        doctor_patient_cache.hset(cls.gen_data_key(doctor_id), person_id, info)

    @classmethod
    def data(cls, doctor_id, patient_id):
        """获得患者的信息
        """
        info = None
        try:
            info = json.loads(doctor_patient_cache.hget(cls.gen_data_key(doctor_id), patient_id))
            person = Person.objects.get(id=info['patient_id'])
            info['user_id'] = person.user.id
            info['user_name'] = filter_user_nick_name(person.user)
            info['portrait'] = get_portrait_by_user(person.user)
            info['noti'] = Notification.objects.get(id=info['last_notify']).to_dict()
        except:
            logging_exception()
            return None
        return info

    @staticmethod
    def gen_data_key(doctor_id):
        return doctor_id + u'_data'

    @staticmethod
    def gen_opeartion_name(name):
        """取美购名称【】外的内容"""
        try:
            index = name.index(u'】')
            return name[index+1:]
        except:
            return name
