<template>
  <el-form ref="pwdRef" :model="user" :rules="rules" label-width="140px" style="width: 500px;height: 260px;">
    <el-form-item label="手机号码">
      <el-input :model-value="props.user?.mobile" placeholder="请输入手机号码" type="text" disabled />
    </el-form-item>
    <el-form-item label="验证码" prop="code">
      <el-input
        v-model="user.code"
        type="text"
        size="large"
        auto-complete="off"
        placeholder="请输入短信验证码"
      >
        <template #append>
          <el-button @click="startCountdown" :disabled="isCounting">
            {{ isCounting ? `重新发送(${countdown})` : '发送验证码' }}
          </el-button>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model="user.newPassword" placeholder="请输入新密码" type="password" show-password />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input v-model="user.confirmPassword" placeholder="请确认新密码" type="password" show-password />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">保存</el-button>
      <!--      <el-button type="danger" @click="close">关闭</el-button>-->
    </el-form-item>
  </el-form>
</template>

<script setup>
import { updateUserPwdByCode } from "@/api/system/user";
import { sendCode } from "@/api/login.js";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user.js";

const userStore = useUserStore();
const { proxy } = getCurrentInstance();

const props = defineProps({
  user: {
    type: Object
  }
});

const user = reactive({
  code: "",
  newPassword: undefined,
  confirmPassword: undefined
});

const countdown = ref(60);
const isCounting = ref(false);
const pwdRef = ref(null);

const equalToPassword = (rule, value, callback) => {
  if (user.newPassword !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const rules = ref({
  code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
  newPassword: [
    { required: true, message: "新密码不能为空", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
    { pattern: /^[^<>\"'|\\\\]+$/, message: "不能包含非法字符：< > \\\" ' \\\\ |", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "确认密码不能为空", trigger: "blur" },
    { required: true, validator: equalToPassword, trigger: "blur" }
  ]
});

function getCode() {
  const mobile = props.user?.mobile;
  if (!mobile) {
    ElMessage({ message: "未获取到手机号", type: "warning" });
    return;
  }
  // 场景: 会员用户 - 修改密码 -> scene = 3
  sendCode({ mobile, scene: 3 }).then((res) => {
    if (res.data === true) {
      ElMessage({ message: "短信已发送请注意查收", type: "success" });
    }
  });
}

const startCountdown = () => {
  if (isCounting.value) return;
  getCode();
  isCounting.value = true;
  const timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
      isCounting.value = false;
      countdown.value = 60;
    }
  }, 1000);
};

/** 提交按钮 */
function submit() {
  proxy.$refs.pwdRef.validate((valid) => {
    if (valid) {
      updateUserPwdByCode({ code: user.code, password: user.newPassword }).then((res) => {
        if (res.code === 0 && res.data) {
          ElMessageBox.confirm("修改成功,请重新登录", "提示", {
            confirmButtonText: "确认",
            showCancelButton: false,
            showClose: false,
            type: "warning"
          }).then(() => {
            userStore.logOut().then(() => {
              location.href = "/index";
            });
          });
        }
      });
    }
  });
}

/** 关闭按钮 */
function close() {
  proxy.$tab.closePage();
}
</script>

