<template>
  <!-- 修改密码对话框 -->
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable :close-on-click-modal="false">
    <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px" label-position="left">
      <el-form-item label="输入原密码" prop="oldPassword">
        <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" show-password clearable />
      </el-form-item>

      <el-form-item label="输入新密码" prop="newPassword">
        <el-input
          v-model="passwordForm.newPassword"
          type="password"
          placeholder="请输入6-16位的密码,包含字母和数字"
          show-password
          clearable
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <div style="display: flex; align-items: center; width: 100%">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            show-password
            clearable
            style="flex: 1"
          />
          <el-link type="primary" :underline="false" style="margin-left: 12px" @click="handleForgotPassword"> 忘记密码 </el-link>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 忘记密码对话框 -->
  <el-dialog v-model="forgotPasswordVisible" title="忘记密码" width="500px" draggable :close-on-click-modal="false">
    <el-form
      ref="forgotPasswordFormRef"
      :model="forgotPasswordForm"
      :rules="forgotPasswordRules"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="手机号码">
        <span>{{ maskedPhone }}</span>
      </el-form-item>

      <el-form-item label="" prop="verificationCode">
        <div style="display: flex; gap: 12px; width: 100%">
          <el-input v-model="forgotPasswordForm.verificationCode" placeholder="请输入" clearable style="flex: 1" />
          <el-button type="primary" :disabled="codeCountdown > 0" @click="sendLoginCode">
            {{ codeCountdown > 0 ? `${codeCountdown}秒后重新获取` : "获取验证码" }}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="输入新密码" prop="newPassword">
        <el-input
          v-model="forgotPasswordForm.newPassword"
          type="password"
          placeholder="请输入6-16位的密码,包含字母和数字"
          show-password
          clearable
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleForgotPasswordCancel">取消</el-button>
        <el-button type="primary" :loading="forgotPasswordLoading" @click="handleForgotPasswordConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onBeforeUnmount } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { validatePassword, validateConfirmPassword } from "@/utils/eleValidate";
import { forgetPassword, getPhoneCode } from "@/api/modules/newLoginApi";
import { localGet } from "@/utils/index";

const dialogVisible = ref(false);
const loading = ref(false);
const passwordFormRef = ref<FormInstance>();

const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
});

// 忘记密码对话框
const forgotPasswordVisible = ref(false);
const forgotPasswordLoading = ref(false);
const forgotPasswordFormRef = ref<FormInstance>();
const codeCountdown = ref(0);
let countdownTimer: NodeJS.Timeout | null = null;

// 获取用户手机号
const userPhone = computed(() => {
  return localGet("iphone") || localGet("geeker-user")?.userInfo?.phone || "";
});
// 掩码显示手机号
const maskedPhone = computed(() => {
  if (!userPhone.value || userPhone.value.length !== 11) {
    return "";
  }
  return userPhone.value.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
});

const forgotPasswordForm = reactive({
  verificationCode: "",
  newPassword: ""
});

// 表单验证规则
const passwordRules: FormRules = {
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [{ required: true, validator: validatePassword, trigger: "blur" }],
  confirmPassword: [
    {
      required: true,
      validator: validateConfirmPassword(() => passwordForm.newPassword),
      trigger: "blur"
    }
  ]
};

// 忘记密码表单验证规则
const forgotPasswordRules: FormRules = {
  verificationCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  newPassword: [{ required: true, validator: validatePassword, trigger: "blur" }]
};

// 打开对话框
const openDialog = () => {
  dialogVisible.value = true;
  // 重置表单
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields();
  }
};

// 取消
const handleCancel = () => {
  dialogVisible.value = false;
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields();
  }
};

// 确定
const handleConfirm = async () => {
  if (!passwordFormRef.value) return;

  await passwordFormRef.value.validate(async valid => {
    if (!valid) return;

    loading.value = true;
    try {
      const res: any = await forgetPassword({
        type: 1,
        phone: userPhone.value,
        // verificationCode: "",
        oldPassword: passwordForm.oldPassword,
        newPassword: passwordForm.newPassword,
        confirmNewPassword: passwordForm.newPassword
      });

      if (res.code === 200) {
        ElMessage.success(res.msg || "密码修改成功");
        dialogVisible.value = false;
        if (passwordFormRef.value) {
          passwordFormRef.value.resetFields();
        }
      } else {
        ElMessage.error(res.msg || "密码修改失败，请重试");
      }
    } catch (error: any) {
      ElMessage.error(error?.msg || error?.message || "密码修改失败，请重试");
    } finally {
      loading.value = false;
    }
  });
};

const handleForgotPassword = () => {
  dialogVisible.value = false;
  forgotPasswordVisible.value = true;
  // 重置表单
  if (forgotPasswordFormRef.value) {
    forgotPasswordFormRef.value.resetFields();
  }
  // 重置倒计时
  codeCountdown.value = 0;
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
};
// ----------------------忘记密码-------------------------
// 发送短信验证码
const sendLoginCode = async () => {
  let phoneCode: any = await getPhoneCode({ phone: userPhone.value, appType: "2", businessType: 6 });
  if (phoneCode.code === 200) {
    ElMessage.success("验证码已发送");
    // 开始倒计时
    codeCountdown.value = 60;
    countdownTimer = setInterval(() => {
      codeCountdown.value--;
      if (codeCountdown.value <= 0) {
        if (countdownTimer) {
          clearInterval(countdownTimer);
          countdownTimer = null;
        }
      }
    }, 1000);
  }
};

// 忘记密码取消
const handleForgotPasswordCancel = () => {
  forgotPasswordVisible.value = false;
  if (forgotPasswordFormRef.value) {
    forgotPasswordFormRef.value.resetFields();
  }
  // 清除倒计时
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
  codeCountdown.value = 0;
};

// 忘记密码确定
const handleForgotPasswordConfirm = async () => {
  if (!forgotPasswordFormRef.value) return;

  await forgotPasswordFormRef.value.validate(async valid => {
    if (!valid) return;

    forgotPasswordLoading.value = true;

    try {
      const res: any = await forgetPassword({
        phone: userPhone.value,
        verificationCode: forgotPasswordForm.verificationCode,
        type: 0,
        newPassword: forgotPasswordForm.newPassword
      });

      if (res.code === 200) {
        ElMessage.success(res.msg || "密码修改成功");
        forgotPasswordVisible.value = false;
        if (forgotPasswordFormRef.value) {
          forgotPasswordFormRef.value.resetFields();
        }
        // 清除倒计时
        if (countdownTimer) {
          clearInterval(countdownTimer);
          countdownTimer = null;
        }
        codeCountdown.value = 0;
      } else {
        ElMessage.error(res.msg || "密码修改失败，请重试");
      }
    } catch (error: any) {
      ElMessage.error(error?.msg || error?.message || "密码修改失败，请重试");
    } finally {
      forgotPasswordLoading.value = false;
    }
  });
};

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
});

defineExpose({ openDialog });
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
