<template>
  <el-dialog
    v-model="open"
    title="修改初始密码"
    width="500px"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div style="color:red;font-size: 13px;width: 100%;text-align: right;">
        *密码为8位及以上且必须包含大小写字母+特殊字符+数字相结合
    </div>
    <el-form ref="pwdRef" :model="passwordForm" :rules="passwordRules" label-width="80px">
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="passwordForm.newPassword"
          placeholder="请输入新密码"
          type="password"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="passwordForm.confirmPassword"
          placeholder="请确认新密码"
          type="password"
          show-password
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit" :loading="submitLoading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { initPassword } from "@/api/login"
import { ElMessage } from 'element-plus'
import { encryptAES, decryptAES } from '@/utils/cryptoAES'
import { getIsKey } from '@/utils/crypto'

const open = ref(false)
const pwdRef = ref(null)
const submitLoading = ref(false)

// 登录信息
const loginInfo = reactive({
  username: '',
  password: '',
  code: '',
  uuid: ''
})

const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = reactive({
  newPassword: [
    { required: true, message: "新密码不能为空", trigger: "blur" },
    { validator: validatePassword, trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "确认密码不能为空", trigger: "blur" },
    { validator: checkConfirmPassword, trigger: "blur" }
  ]
})

function checkConfirmPassword(rule, value, callback) {
  if (value !== passwordForm.newPassword) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}

function validatePassword(rule, value, callback) {
  if (checkPassword(value) === false) {
    callback(new Error("密码格式不符合要求"))
  } else {
    callback()
  }
}

function checkPassword(password) {
    // 基础长度检查
    if (!password || password.length < 8) {
        return false;
    }
    // 正则表达式验证
    const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[A-Za-z\d!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,}$/;
    return regex.test(password);
}

function show(loginData) {
  open.value = true
  reset()
  // 保存登录信息
  loginInfo.username = loginData.username
  loginInfo.password = loginData.password
  loginInfo.code = loginData.code
  loginInfo.uuid = loginData.uuid
}

function hide() {
  open.value = false
}

function reset() {
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  if (pwdRef.value) {
    pwdRef.value.resetFields()
  }
}

function submit() {
  pwdRef.value.validate(async valid => {
    if (valid) {
      submitLoading.value = true
      // 使用初始密码修改接口
      const keyObj = await getIsKey()
      const isKey = keyObj["data"];

      const requestForm = { ...loginInfo }
      let encryptNewPassword = passwordForm.newPassword;
      try {
        if("1" === isKey || 1 === isKey) {
          requestForm.username = encryptAES(loginInfo.username)
          requestForm.password = encryptAES(loginInfo.password)
          requestForm.code = encryptAES(loginInfo.code)
          encryptNewPassword = encryptAES(encryptNewPassword)
        }
      } catch (error) {}
      initPassword(requestForm.username, requestForm.password, encryptNewPassword, requestForm.code, loginInfo.uuid).then(response => {
        submitLoading.value = false
        ElMessage.success("密码修改成功，请重新登录")
        hide()
        // 通知父组件密码修改成功
        emits('passwordChanged')
      }).catch(() => {
        submitLoading.value = false
      })
    }
  })
}

defineExpose({
  show,
  hide
})

const emits = defineEmits(['passwordChanged'])
</script>
