<template>
  <Dialog
    :flag="passwordDialogVisible"
    width="496px"
    msg-title="修改密码"
    @submit-form="submitHandler"
    @reset-form="togglePasswordDialog(false)"
  >
    <div class="dialog-content">
      <div class="ruleDesc">
        特殊字符：`、!、@、#、$、%、^、&、*、(、)、_、+、{、}、"、:、?、>、&lt;、`、,、.、/、'、;、[、]、=、-、\、|
      </div>
      <div class="ruleDesc">
        密码规则：长度为8-20个字符，并且必须包含数字、大写字母、小写字母、特殊字符
      </div>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-position="top"
        class="password-form"
      >
        <el-form-item label="旧密码" prop="old">
          <el-input
            v-model="formData.old"
            autocomplete="off"
            size="default"
            placeholder="请输入旧密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new">
          <el-input
            v-model="formData.new"
            size="default"
            placeholder="请输入新密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="再次确认新密码" prop="repeat">
          <el-input
            v-model="formData.repeat"
            size="default"
            placeholder="请再次确认新密码"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { changePassword } from '@/api/newLogin'
import Dialog from '@/components/dialog/index.vue'
import { useUserStore } from '@/store/user'
import { ElMessage, FormInstance } from 'element-plus'
import MD5 from 'blueimp-md5'

const emit = defineEmits(['logout'])

const userStore = useUserStore()
const { passwordDialogVisible, UserId } = storeToRefs(userStore)
const { togglePasswordDialog } = userStore

const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  old: '',
  new: '',
  repeat: '',
})
const repeatValidator = (rule: any, value: any, callback: any) => {
  if (value !== formData.new) {
    return callback(new Error('两次输入的密码不一致，请重新输入'))
  }
  return callback()
}
// 表单验证
const formRules = {
  old: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  new: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  repeat: [
    { required: true, message: '请再次确认新密码', trigger: 'blur' },
    { validator: repeatValidator, trigger: 'blur' },
  ],
}
const submitHandler = () => {
  formRef.value?.validate(valid => {
    if (valid) {
      submitNewPassword()
    } else {
      return false
    }
  })
}
const submitNewPassword = async () => {
  try {
    const { code, message }: any = await changePassword({
      userId: UserId.value,
      originPassword: MD5(formData.old),
      newPassword: formData.new,
    })
    if (Number(code) !== 0) {
      throw new Error('修改失败')
    }
    ElMessage.success('修改成功')
    togglePasswordDialog(false)
    setTimeout(() => {
      ElMessage.info('请重新登录')
      emit('logout')
    }, 2000)
  } catch (error: any) {
    ElMessage.error(error.message ?? '修改失败')
  }
}
</script>

<style lang="scss" scoped>
.dialog-content {
  margin-left: 20px;
  .ruleDesc {
    line-height: 2;
    margin-bottom: 22px;
    color: #101611;
  }
}
</style>
