<template>
  <el-dialog
    title="个人中心"
    v-model="visible"
    width="1200px"
    :append-to-body="true"
    :destroy-on-close="true"
  >
    <el-form
      ref="passwordFormRef"
      v-model:model="passwordForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
          v-model="passwordForm.oldPassword"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input
          v-model="passwordForm.password"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="passwordForm.confirmPassword" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm"> 修改密码 </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  getUserDetailApi,
  updateHeadImg,
  updateBaseInfo,
} from "@/api/system/user/index";
import { useUserStoreHook } from "@/store/modules/user";
import SingleUpload from "@/components/Upload/SingleUpload.vue";

const userStore = useUserStoreHook();
const activeName = ref("first");
const visible = ref(false);
const userInfo = ref<any>({});
const headUrl = ref("");

const show = () => {
  visible.value = true;
};

defineExpose({ show });

const uploadHeadFinish = () => {
  updateHeadImg(userStore.user.userId, { avatar: headUrl.value }).then(() => {
    ElMessage.success("头像上传成功");
  });
};
// =============== 修改密码相关
const passwordFormRef = ref();
const passwordForm = ref({
  oldPassword: "",
  password: "",
  confirmPassword: "",
});
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入"));
  } else if (value !== passwordForm.value.password) {
    callback(new Error("两次密码不一致，请重新输入!"));
  } else {
    callback();
  }
};
const rules = reactive({
  oldPassword: [{ required: true, trigger: "blur" }],
  password: [{ required: true, trigger: "blur" }],
  confirmPassword: [
    { required: true, validator: validatePass, trigger: "blur" },
  ],
});

const submitForm = () => {
  passwordFormRef.value.validate((valid: boolean) => {
    if (valid) {
      updateBaseInfo(userStore.user.userId, {
        password: passwordForm.value.password,
        oldPassword: passwordForm.value.oldPassword,
      }).then(() => {
        ElMessage.success("密码修改成功");
        visible.value = false;
        passwordFormRef.value.resetFields();
      });
    }
  });
};

const resetForm = () => {
  passwordFormRef.value.resetFields();
};
</script>

<style scoped lang="scss">
.lable {
  font-weight: bolder;
}
</style>
