import json

from django.db.models import F
from django.http import QueryDict
from django.views import View
from Ansjer.config import LOGGER

from Model.models import DeviceVersionInfo, CountryAPN, LanguageModel, CountryLanguageModel, CountryModel
from Object.Enums.RedisKeyConstant import RedisKeyConstant
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService


class APNConfigView(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):
        response = ResponseObject('en')
        tko = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
        LOGGER.info(f'APNConfigView -- tko: {tko.code}, request_dict: {request_dict}')
        if tko.code != 0:
            return response.json(tko.code)
        response.lang = tko.lang
        userID = tko.userID
        if operation == 'APNConfigList':
            return self.get_apn_config(request_dict, response)
        elif operation == 'CountryCodeList':
            return self.get_country_code_list(request_dict, response)
        else:
            return response.json(414)

    @staticmethod
    def get_apn_config(request_dict, response):
        # 从请求字典中获取国家代码
        country_code = request_dict.get('countryCode')

        # 检查 country_code 是否存在，如果不存在，返回错误代码444
        if not country_code:
            return response.json(444)

        # 查询数据库，获取与国家代码匹配的 APN 配置信息
        country_apn_qs = CountryAPN.objects.filter(iso=country_code).values('username', 'password',
                                                                            apnName=F('apn_name'),
                                                                            apnAddress=F('apn_address'),
                                                                            authType=F('auth_type'))

        return response.json(0, list(country_apn_qs))

    @staticmethod
    def get_country_code_list(request_dict, response):
        lang = request_dict.get('lang', 'en')

        # 获取语言 ID
        language = LanguageModel.objects.filter(lang=lang).first()

        if not language:
            language = LanguageModel.objects.filter(lang='en').first()

        iso_list = CountryAPN.objects.all().values("iso")
        # 查询tb_country_language和tb_country，获取国家名称和国家iso2代码
        countries = CountryLanguageModel.objects.filter(language=language,
                                                        country__country_code__in=iso_list).select_related(
            'country').order_by(
            'country__country_name')

        # 返回国家名和对应的 country_code
        country_iso_list = [{
            'countryName': country.country_name,
            'countryCode': country.country.country_code
        } for country in countries]

        return response.json(0, country_iso_list)
