# -*- encoding: utf-8 -*-
"""
@File    : CloudServiceController.py
@Time    : 2022/12/8 10:23
@Author  : stephen
@Email   : zhangdongming@asj6.wecom.work
@Software: PyCharm
"""
import json
import time

from django.views import View

from Ansjer.config import LOGGER
from Model.models import CouponCombo, CouponModel
from Object.Enums.RedisKeyConstant import RedisKeyConstant
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject


class CloudServiceController(View):

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.GET, request, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.POST, request, operation)

    def validation(self, request_dict, request, operation):
        token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
        lang = request_dict.get('lang', token.lang)
        response = ResponseObject(lang)
        if token.code != 0:
            return response.json(token.code)
        user_id = token.userID
        if operation == 'save-photo':
            return self.get_combo_list_by_coupon(user_id, response)
        else:
            return response.json(404)

    @classmethod
    def get_combo_list_by_coupon(cls, request_dict, response):
        """
        根据优惠券获取套餐列表
        @param request_dict: couponId 优惠券ID
        @param request_dict: couponType 优惠券类型
        @param response: 响应结果
        """
        coupon_id = int(request_dict.get('couponId', 0))
        coupon_type = int(request_dict.get('couponType', 0))
        if coupon_id == 0:
            return response.json(444)
        coupon_combo_qs = CouponCombo.objects.filter(coupon_type=coupon_type, coupon_id=coupon_id).values('combo_id')
        combo_list = []
        if not coupon_combo_qs.exists():
            return combo_list
        for item in coupon_combo_qs:
            combo_list.append(item['combo_id'])
        return combo_list

    @classmethod
    def get_user_coupon_list(cls, user_id):
        """
        获取用户未使用优惠券配置ID列表
        @param user_id: 用户id
        @return: coupon_ids 列表，可能为空
                  如果没有未使用的优惠券，返回空列表 []
        """
        try:
            now_time = int(time.time())
            coupon_conf_ids = CouponModel.objects.filter(
                userID=user_id,
                use_status=0,
                distribute_time__lte=now_time,
                valid_time__gt=now_time
            ).values_list('coupon_config__id', flat=True)  # 使用 values_list 获取 ID 列表

            return list(coupon_conf_ids)  # 可能为空
        except Exception as e:
            LOGGER.error('获取用户优惠券异常:userID:{}, error_line:{}, error_msg:{}'
                         .format(user_id, e.__traceback__.tb_lineno, repr(e)))
            return []

    @classmethod
    def get_combo_list(cls, coupon_type, coupon_id):
        """
        根据优惠券类型与优惠券ID，获取关联套餐列表
        :param coupon_type: 优惠券类型
        :param coupon_id: 优惠券ID
        :return: 关联的套餐ID列表
        """
        try:
            redis_obj = RedisObject()  # 创建 Redis 对象以访问缓存
            # 构建 Redis 缓存键
            conf_key = f'{RedisKeyConstant.BASIC_CLOUD_COUPON.value}{coupon_type}:{coupon_id}'

            # 尝试从 Redis 获取数据
            conf_data = redis_obj.get_data(conf_key)
            if conf_data:  # 如果缓存中存在数据，则直接返回
                return json.loads(conf_data)

                # 从数据库中查询关联的套餐ID
            combo_qs = CouponCombo.objects.filter(coupon_type=coupon_type, coupon_id=coupon_id).values('combo_id')

            # 初始化套餐ID列表
            combo_list = []
            if combo_qs.exists():  # 检查查询集是否存在数据
                for item in combo_qs:
                    combo_list.append(item['combo_id'])  # 逐个添加套餐ID

            # 将查询结果存入 Redis 缓存
            redis_obj.set_data(conf_key, json.dumps(combo_list), expire=RedisKeyConstant.EXPIRE_TIME_24_HOURS)

            return combo_list  # 返回套餐ID列表

        except Exception as e:
            # 记录异常信息和相关上下文
            LOGGER.error('获取优惠券套餐异常: couponID: {}, error_line: {}, error_msg: {}'
                         .format(coupon_id, e.__traceback__.tb_lineno, repr(e)))
            return []  # 返回空列表以表示失败

    @classmethod
    def get_coupon_list(cls, coupon_type, combo_id):
        """
        根据优惠券类型与套餐ID，获取关联优惠券列表
        @param coupon_type: 优惠券类型
        @param combo_id: 套餐id
        @return: coupon_list
        """
        coupon_combo_qs = CouponCombo.objects.filter(coupon_type=coupon_type, combo_id=combo_id) \
            .values('coupon_id')
        coupon_list = []
        if not coupon_combo_qs.exists():
            return coupon_list
        for item in coupon_combo_qs:
            coupon_list.append(item['coupon_id'])
        return coupon_list
