# -*- coding: utf-8 -*-

import json

from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder

from utils.redis.rkeys import LENSMAN_PHOTO_ORDER_RECORD


r = settings.REDIS_CACHE


# 摄影师照片购买记录相关


def set_lensman_order_record(porder):
    """ 设置摄影师照片购买记录 """
    porder_info = porder.porder_info
    r.setex(LENSMAN_PHOTO_ORDER_RECORD % (porder.photo_id, porder.user_id), settings.REDIS_EXPIRED_MONTH, json.dumps(porder_info, cls=DjangoJSONEncoder))
    return porder_info


def set_lensman_order_record_by_id(photo_id, user_id):
    """ 设置摄影师照片购买记录 """
    from group.models import GroupPhotoOrderInfo
    try:
        porder = GroupPhotoOrderInfo.objects.get(photo_id=photo_id, user_id=user_id)
    except GroupPhotoOrderInfo.DoesNotExist:
        return {}
    return set_lensman_order_record(porder)


def get_lensman_order_record(photo_id, user_id):
    """ 获取摄影师照片购买记录 """
    return json.loads(r.get(LENSMAN_PHOTO_ORDER_RECORD % (photo_id, user_id)) or '{}') or set_lensman_order_record_by_id(photo_id, user_id)
