# _*_coding:utf-8_*_

import re

from django.contrib.auth.hashers import make_password
from django.db.models import F
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView

from main.settings import BASE_DIR

from ..models import *
from ..utils.j_config import JConfig
from ..utils.j_dict import JDict
from ..utils.custom_response import util_response
from ..utils.custom_tool import request_params_wrapper, flow_service_wrapper
from ..services.login_service import LoginService

root_config = JConfig.get_section(str(BASE_DIR) + '/config.ini', 'xj_user', encode='utf-8-sig')
module_config = JDict(root_config)
jwt_secret_key = module_config.jwt_secret_key or "@zxmxy2021!"
expire_day = module_config.expire_day or 7
expire_second = module_config.expire_second or 0


class UserPasswordCaptcha(APIView):
    """
    通过短信验证码重置用户密码
    注意：每次修改密码都会创建新的 Auth 记录，以保留历史密码记录
    """
    permission_classes = (AllowAny,)
    model = BaseInfo
    params = None

    @request_params_wrapper
    @flow_service_wrapper
    def post(self, request, *args, request_params, **kwargs):
        phone = str(request_params.get('phone', ''))
        new_password = str(request_params.get('new_password', ''))
        sms_code = str(request_params.get('code', ''))

        # 参数校验
        if not phone:
            return util_response(err=2002, msg="手机号不能为空")

        if not new_password:
            return util_response(err=2003, msg="新密码不能为空")

        if not sms_code:
            return util_response(err=2004, msg="验证码不能为空")

        # 手机号格式校验
        if not re.match(r'(^1[356789]\d{9}$)|(^\+?[78]\d{10}$)', phone):
            return util_response(err=2006, msg="手机号格式不正确")

        # 导入短信验证服务
        try:
            from xj_captcha.services.sms_service import SmsService
        except ImportError:
            return util_response(err=5000, msg="验证码服务不可用")

        # 校验短信验证码
        sms, sms_err = SmsService.check_sms({"phone": phone, "sms_code": sms_code})
        if sms_err:
            return util_response(data=None, err=4774, msg=sms_err)

        # 查询该手机号下的所有用户（按注册时间倒序，取最新注册的账号）
        user_set = BaseInfo.objects.filter(phone=phone, is_delete=0).order_by("-register_time")

        # 检查用户是否存在
        if not user_set.exists():
            return util_response(err=2007, msg=f"手机号不存在：{phone}")

        # 取最新注册的账号（第一条）
        last_user = user_set.annotate(user_id=F("id")).extra(select={"user_uuid": 'REPLACE(uuid, "-", "")'}).first()

        # 生成新的 Token
        token = LoginService.make_token(user_id=last_user.id, user_uuid=last_user.user_uuid, account=phone)

        # 创建新的 Auth 记录（保留历史密码）
        try:
            new_auth = Auth.objects.create(
                user_id=last_user.id,
                password=make_password(new_password, None, 'pbkdf2_sha1'),
                plaintext=new_password,
                token=token,
            )
        except Exception as e:
            return util_response(err=5001, msg=f"密码重置失败: {str(e)}")

        # 返回成功响应
        return Response(data={
            'err': 0,
            'msg': 'ok',
            'data': {
                "user_id": last_user.id,
                "user_uuid": last_user.user_uuid,
                "username": last_user.username,
                "token": token,
            },
        }, status=None, template_name=None, content_type=None)


class MyApiError(Exception):
    def __init__(self, message, err_code=4010):
        self.msg = message
        self.err = err_code

    def __str__(self):
        return repr(self.msg)