# @Author    : Rocky
# @File      : DeviceController.py.py
# @Time      : 2025/2/19 11:22
import requests
from django.views.generic.base import View

from Controller.WeChatMiniProgram.CommonController import CommonObj
from Object.Enums.WeChatEnum import WeChatMiniProgramAPIEnum, WeChatMiniProgramConfigEnum
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject


class DeviceView(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):
        lang = request_dict.get('lang', 'cn')
        response = ResponseObject(lang)
        if operation == 'getSnTicket':
            return self.get_sn_ticket(request_dict, response)

    @staticmethod
    def get_sn_ticket(request_dict, response):
        """
        获取设备票据
        https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/hardware-device/getSnTicket.html
        @param request_dict:
        @param response:
        @return: res
        """
        uid = request_dict.get('uid', None)
        device_type = request_dict.get('device_type', None)
        if not all([uid, device_type]):
            return response.json(444)
        try:
            # 根据设备型号确定model_id
            model_id = WeChatMiniProgramConfigEnum.ModelIdDict.value['device_type']
            # 从缓存中获取票据
            redis_obj = RedisObject()
            sn_ticket_key = WeChatMiniProgramConfigEnum.SnTicketKey.value
            sn_ticket = redis_obj.get_data(sn_ticket_key)
            if sn_ticket:
                res = {
                    'sn_ticket': sn_ticket
                }
                return response.json(0, res)

            access_token = CommonObj.get_access_token()
            url = WeChatMiniProgramAPIEnum.getSnTicketAPI.value.format(access_token)
            data = {
                'sn': uid,
                'model_id': model_id
            }
            r = requests.post(url=url, json=data, timeout=5)
            result = eval(r.content)
            errcode = result.get('errcode')
            assert errcode == 0
            sn_ticket = result['sn_ticket']
            # 保存到Redis,五分钟有效
            redis_obj.set_ex_data(key=sn_ticket_key, val=sn_ticket, expire=60*5)
            res = {
                'sn_ticket': sn_ticket
            }
            return response.json(0, res)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
