import json
import ssl

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import random

from DCbackend import settings
from DCbackend.utils.common import success, fail
# 在你的视图函数中使用这个方法
from django.http import JsonResponse

from DCbackend.utils.token import encrypt
from backend.models import Admin


class SMSService:
    # 发送短信
    @staticmethod
    def send_sms(phone_number, code):
        client = AcsClient(settings.oss_key_id, settings.oss_key_secret, settings.region_id)

        request = CommonRequest()
        request.set_accept_format('json')
        request.set_domain('dysmsapi.aliyuncs.com')
        request.set_method('POST')
        request.set_protocol_type('https')
        request.set_version('2017-05-25')  # 更正版本号
        request.set_action_name('SendSms')

        request.add_query_param('RegionId', settings.region_id)
        request.add_query_param('PhoneNumbers', phone_number)
        request.add_query_param('SignName', settings.SignName)
        request.add_query_param('TemplateCode', "SMS_270860270")
        request.add_query_param('TemplateParam', json.dumps({"code": code}))


        response = client.do_action_with_exception(request)
        print(str(response, encoding='utf-8'))
        return json.loads(response)

    #发送验证码
    @staticmethod
    def tailPhone(request):
        phone = request.POST.get("phone")
        verification_code = ''.join(random.choices('0123456789', k=6))
        result = SMSService.send_sms(phone, verification_code)
        if result and result.get('Code') == 'OK':
            adminInfo = Admin.objects.filter(mobile=phone).first()
            if adminInfo:
                # 如果查询到了数据
                adminInfo.verification_code = verification_code
                adminInfo.save()
                return success("验证码发送成功")
            else:
                return fail("查无此人")
        else:
            return fail("验证码发送失败")
    #校验验证码
    @staticmethod
    def codeCheckout(request):
        phone = request.POST.get("phone")
        verification_code = request.POST.get("verification_code")
        admin_exists  = Admin.objects.filter(mobile=phone,verification_code = verification_code).exists()
        if admin_exists:
            return success("验证成功")
        else:
            return fail("验证失败,请检查验证码和手机号")
    #修改密码
    @staticmethod
    def updatePassword(request):
        newPassword1 = request.POST.get("new_password1")
        newPassword2 = request.POST.get("new_password2")
        phone = request.POST.get("phone")

        if newPassword1 == newPassword2:
            newPassword = newPassword1
            adminInfo = Admin.objects.filter(mobile=phone).first()
            if adminInfo:
                adminInfo.password = encrypt(newPassword)
                adminInfo.verification_code = ""
                adminInfo.save()
                return success("修改成功")
            else:
                return fail("修改失败")
        else:
            return fail("两次密码不相同")




    #获取模版列表
    @staticmethod
    def get_aliyun_sms_templates(access_key_id, access_key_secret, region_id=settings.region_id, page_size=10, page_index=1):
        """
        获取阿里云短信模板列表
        :param access_key_id: 阿里云访问密钥ID
        :param access_key_secret: 阿里云访问密钥密码
        :param region_id: 地域ID，默认为上海
        :param page_size: 每页显示的模板数量
        :param page_index: 页码
        :return: 短信模板列表
        """
        client = AcsClient(access_key_id, access_key_secret, region_id)

        request = CommonRequest()
        request.set_accept_format('json')
        request.set_domain('dysmsapi.aliyuncs.com')
        request.set_method('POST')
        request.set_protocol_type('https')
        request.set_version('2017-05-25')
        request.set_action_name('QuerySmsTemplateList')  # 修改为正确的Action名称

        request.add_query_param('PageSize', page_size)
        request.add_query_param('PageIndex', page_index)

        response = client.do_action_with_exception(request)
        response_json = json.loads(response)

        return response_json

    @staticmethod
    def getTemplates(request):
        page_size = int(request.GET.get('page_size', 10))
        page_index = int(request.GET.get('page_index', 1))

        templates = SMSService.get_aliyun_sms_templates(
            settings.oss_key_id,
            settings.oss_key_secret,
            page_size=page_size,
            page_index=page_index
        )
        return JsonResponse(templates)


    @staticmethod
    def getSMScount(request):

        return success(SMSService.get_aliyun_sms_remaining())


    @staticmethod
    def get_aliyun_sms_remaining():
        # 创建AcsClient实例
        client = AcsClient(settings.oss_key_id, settings.oss_key_secret, settings.region_id)

        # 创建request,并设置参数
        request = CommonRequest()
        request.set_accept_format('json')
        request.set_domain('dysmsapi.aliyuncs.com')
        request.set_method('POST')
        request.set_protocol_type('https')
        request.set_version('2017-05-25')
        request.set_action_name('QuerySendDetails')

        # 设置业务参数
        request.add_query_param('PhoneNumber', '1234567890')  # 示例手机号
        request.add_query_param('SendDate', '20230101')  # 示例日期
        request.add_query_param('PageSize', '1')
        request.add_query_param('CurrentPage', '1')

        # 发起请求并获取响应
        response = client.do_action_with_exception(request)

        # 解析响应
        import json
        result = json.loads(response)

        # 获取剩余短信数量
        remaining_count = result.get('TotalCount', 0)

        return result

