<template>
  <el-dialog :model-value="visible" class="reset-password-dialog" top="15vh" width="460px" destroy-on-close
    :close-on-click-modal="false" @update:model-value="(v) => !v && close()">
    <div class="body-wrap">
      <div class="body-header">
        <span class="body-title">{{ $t('account.resetPassword') }}</span>
        <img src="@/assets/image/close-btn.svg" alt="" class="close-btn" @click="close" />
      </div>

      <div class="reset-password-content">
        <p class="confirm-line">
          {{ $t('account.confirmReset', { id: ` ${username} ` }) }}
        </p>
        <p class="default-line">{{ $t('account.defaultPassword') }}</p>
      </div>
    </div>

    <div class="body-footer">
      <el-button @click="close">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" :loading="submitting" @click="submit">
        {{ $t('account.resetPassword') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { resetAdminAccountPassword } from "@/service/modular/admin";

const { t: $t } = useI18n();

const props = defineProps({
  visible: { type: Boolean, default: false },
  // 当前点击的表格行数据；用于读取 username
  accountData: { type: Object, default: () => ({}) },
});

const emit = defineEmits(["update:visible", "success"]);

const submitting = ref(false);
// 缓存当前要重置的账号，避免 dialog 关闭后 username 丢失
const username = ref("");

watch(
  () => [props.visible, props.accountData],
  ([vis]) => {
    if (vis) {
      username.value = props.accountData?.username || "";
    }
  },
  { immediate: true }
);

const close = () => emit("update:visible", false);

const submit = async () => {
  if (!props.accountData?.id) return;
  submitting.value = true;
  try {
    await resetAdminAccountPassword(props.accountData.id);
    ElMessage.success($t('msg.passwordResetSuccess'));
    emit("success");
    emit("update:visible", false);
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped lang="scss">
.reset-password-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;

  .confirm-line {
    font-weight: 400;
    font-size: 16px;
    color: #1D2129;
  }

  .default-line {
    background: #EAF3FF;
    border-radius: 8px 8px 8px 8px;
    font-weight: 400;
    font-size: 15px;
    color: #3289FB;
    padding: 10px 12px;
  }
}
</style>

<style lang="scss">
.reset-password-dialog {
  min-width: 410px;
  max-width: 90vw;
}
</style>
