<script setup lang="ts">
import defaultAvatar from '@/assets/img/default-avatar.png'
import { ref } from 'vue'
import { uploadImagesInBatches } from '../utils/uploadImg.ts'

const userStore = useUserStore()
const userInfo = userStore.userInfo
const message = useMessage()

const ruleForm = ref({})
function onShowModel() {
  ruleForm.value.nickName = userInfo.nickName
  ruleForm.value.avatar = userInfo.avatar
  ruleForm.value.brief = userInfo.brief
  ruleForm.value.userId = userInfo.userId
}

const rules = ref({
  nickName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' },
  ],
})
// 文件输入引用
const pictureInput = ref<HTMLInputElement | null>(null)
function handlePictureInput() {
  pictureInput.value?.click()
}

// 处理图片上传
async function handlePictureChange(event: Event) {
  const files = (event.target as HTMLInputElement).files
  if (!files || files.length === 0)
    return

  if (files.length > 1) {
    message.error('只能选择 1 张图片')
    return
  }

  const imageFiles = Array.from(files).filter(file => file.type.startsWith('image/'))
  if (imageFiles.length === 0) {
    message.error('请选择有效的图片文件')
    return
  }

  try {
    const pictureResultList = await uploadImagesInBatches(imageFiles)
    event.target.value = ''
    ruleForm.value.avatar = pictureResultList[0]
  }
  catch (error) {
    message.error('图片上传失败')
  }
}

async function saveInfo() {
  const res = await request.post('/system/user/updateUserInfo', ruleForm.value)
  const data = await userStore.getUserInfo()
  onCloseModel()
}

const isVisible = ref(false)
function onCloseModel() {
  isVisible.value = false
}
defineExpose({
  isVisible,
})
// 生命周期钩子
onMounted(() => {
  // initFormData()
})
</script>

<template>
  <NModal
    v-model:show="isVisible"
    :on-after-leave="onCloseModel"
    :on-after-enter="onShowModel"
    preset="card"
    style="width: 400px"
    :mask-closable="false"
  >
    <div class="rounded-full flex justify-center overflow-hidden mb-4">
      <img class="block w-[60px] h-[60px] rounded-full" :src="ruleForm.avatar || defaultAvatar" alt="编辑">
    </div>
    <div class="flex justify-center mb-2">
      <button class="cursor-pointer text-center text-base text-[#222] dark:text-[#fff] dark:border-[#AABEFF1A] border-0  bg-[#F1F2F8] hover:bg-[#ECEEF5] dark:bg-[#1C1D29] dark:hover:bg-[#2A2D3D]  font-medium leading-[3rem] w-[116px] h-12 rounded-lg" @click="handlePictureInput">
        更换头像
      </button>
      <input
        ref="pictureInput"
        type="file"
        accept="image/*"
        class="hidden"
        @change="handlePictureChange"
      >
    </div>
    <n-form ref="formRef" :model="ruleForm" :rules="rules">
      <n-form-item path="nickName" label="用户名">
        <n-input v-model:value="ruleForm.nickName" placeholder="请输入用户名" @keydown.enter.prevent />
      </n-form-item>
      <n-form-item label="简介" path="textareaValue">
        <n-input
          v-model:value="ruleForm.brief"
          placeholder="请输入简介"
          type="textarea"
          :autosize="{
            minRows: 3,
            maxRows: 5,
          }"
        />
      </n-form-item>
    </n-form>
    <div class="flex justify-center items-center ">
      <button class="w-1/2 flex justify-center mx-1 bg-[#f1f2f2] py-3 rounded-lg align-middle border-0 cursor-pointer" @click="onCloseModel">
        暂不修改
      </button>
      <!-- <div class="w-1/2 flex justify-center mx-1 bg-[#f1f2f2] py-3 rounded-lg align-middle">
      暂不修改
      </div> -->

      <button class="w-1/2 flex justify-center mx-1 bg-[#213df5] py-3 rounded-lg align-middle color-[#fff] border-0 cursor-pointer" @click="saveInfo">
        确定修改
      </button>
      <!-- <div class="w-1/2 flex justify-center mx-1 bg-[#213df5] py-3 rounded-lg align-middle color-[#fff]">
        确定修改
      </div> -->
    </div>
  </NModal>
</template>

<style scoped>
.form {
  /* cursor: pointer; */
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.form-item {
  margin-bottom: 10px;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
}

.form-item input {
  width: 200px;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

.form-item button {
  padding: 5px 10px;
  background-color: #007bff;
  color: #fff;
  border: none;
}
</style>
