<template>
  <el-dialog :model-value="modelValue" @update:model-value="(v) => emit('update:modelValue', v)" class="password-dialog"
    :close-on-click-modal="false" align-center destroy-on-close @closed="onClosed">
    <div class="password-body">
      <div class="body-wrap">
        <div class="password-header body-header">
          <span class="body-title">{{ $t("password.title") }}</span>
          <img src="@/assets/image/close-btn.svg" alt="" class="close-btn" @click="close" />
        </div>

        <el-form ref="formRef" :model="form" :rules="rules" class="password-form" @submit.prevent>
          <el-form-item :label="$t('password.oldPassword')" prop="oldPassword">
            <el-input v-model="form.oldPassword" type="password" show-password
              :placeholder="$t('password.pleaseInputOld')" />
          </el-form-item>
          <el-form-item :label="$t('password.newPassword')" prop="newPassword">
            <el-input v-model="form.newPassword" type="password" show-password
              :placeholder="$t('password.pleaseInputNew')" />
          </el-form-item>
          <el-form-item :label="$t('password.confirmPassword')" prop="confirmPassword">
            <el-input v-model="form.confirmPassword" type="password" show-password
              :placeholder="$t('password.pleaseInputConfirm')" />
          </el-form-item>
        </el-form>
      </div>


      <div class="password-footer body-footer">
        <el-button @click="close">{{ $t("password.cancel") }}</el-button>
        <el-button type="primary" :loading="submitting" @click="submit">确认修改</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { changePassword as hospitalChangePassword } from "@/service/modular/hospital";
import { changeMyPassword as adminChangePassword } from "@/service/modular/admin";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  // 当前角色：admin（管理端） / hospital（医院端），决定调用哪个接口
  role: {
    type: String,
    default: "admin",
    validator: (v) => ["admin", "hospital"].includes(v),
  },
});

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

const { t } = useI18n();
const router = useRouter();

const formRef = ref();
const submitting = ref(false);
const form = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

const rules = {
  oldPassword: [
    {
      required: true,
      message: () => t("password.pleaseInputOld"),
      trigger: "blur",
    },
  ],
  newPassword: [
    {
      required: true,
      message: () => t("password.pleaseInputNew"),
      trigger: "blur",
    },
    {
      min: 6,
      message: () => t("password.passwordTooShort"),
      trigger: "blur",
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: () => t("password.pleaseInputConfirm"),
      trigger: "blur",
    },
    {
      validator: (_, val, cb) =>
        val === form.newPassword ? cb() : cb(new Error(t("password.passwordMismatch"))),
      trigger: "blur",
    },
  ],
};

// 根据 role 选择调用的接口
const apiMap = {
  admin: adminChangePassword,
  hospital: hospitalChangePassword,
};

const submit = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    submitting.value = true;
    try {
      const fn = apiMap[props.role] || apiMap.admin;
      await fn({
        oldPassword: form.oldPassword,
        newPassword: form.newPassword,
      });
      ElMessage.success(t("password.success"));
      emit("success");
      emit("update:modelValue", false);
      // 保留原有逻辑：修改成功后跳到登录页
      setTimeout(() => {
        router.replace("/login");
      }, 1000);
    } catch (err) {
      console.log(err?.message || t("common.failed"));
    } finally {
      submitting.value = false;
    }
  });
};

const close = () => {
  emit("update:modelValue", false);
};

const onClosed = () => {
  form.oldPassword = "";
  form.newPassword = "";
  form.confirmPassword = "";
  formRef.value?.clearValidate();
};
</script>

<style lang="scss">
.password-dialog {
  .password-body {
    width: 458px;

    .body-wrap {
      padding: 24px;
      background: #fff;
    }


    .password-form {
      margin-top: 27px;

      .el-form-item {
        margin-bottom: 18px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          font-weight: normal;
          font-size: 14px;
          color: #1D2129;
          width: 6em;
        }

        .el-input__wrapper {
          padding: 4px 12px;
          border-radius: 8px;
        }
      }
    }

    .password-footer {
      // display: flex;
      // justify-content: flex-end;
      // gap: 12px;
      // margin-top: 24px;

      // .el-button {
      //   min-width: 96px;
      //   height: 36px;
      //   border-radius: 8px;
      // }

      button {
        width: 126px;
        height: 38px;
      }
    }
  }
}
</style>