<template>
  <el-dialog
    v-model="visible"
    title="修改头像"
    width="600px"
    :before-close="fnClose"
  >
    <el-form :model="form" :rules="rules" label-width="100px" ref="formRef">
      <el-form-item label="头像" prop="file">
        <layout-upload
          v-model:file-list="form.file"
          accept=".jpg,.jpeg,.png"
          list-type="picture-card"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="fnSubmit">确认</el-button>
      <el-button @click="fnClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import LayoutUpload from "@/components/upload/index.vue";
import { debounce } from "throttle-debounce";
import useFormValidate from "@/assets/js/useFormValidate.js";
import { setAvatar } from "@/request/api.js";
import { ElMessage } from "element-plus";
import { ref } from "vue";
import { useVModels } from "@vueuse/core";
import { useUserStore } from "@/pinia/user.js";

const userStore = useUserStore();
const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false,
  },
  form: {
    type: Object,
    required: true,
    default: () => ({}),
  },
});
const emits = defineEmits(["update:visible", "update:form"]);
const { visible, form } = useVModels(props, emits);
const formRef = ref(null);
const rules = {
  file: [{ required: true, message: "请上传头像", trigger: "change" }],
};
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    if (!form.value.file[0].raw) {
      ElMessage.warning("没有修改图片，不需要保存");
      return;
    }
    const formData = new FormData();
    formData.append("FFILE", form.value.file[0].raw);
    const resData = await setAvatar(formData);
    fnClose();
    ElMessage.success("修改成功");
    userStore.setUserInfo({
      ...userStore.getUserInfo,
      userPhoto: resData.userPhoto,
    });
  },
  { atBegin: true }
);
const fnClose = () => {
  formRef.value.resetFields();
  visible.value = false;
};
</script>

<style scoped lang="scss"></style>
