<template>
  <div v-if="userStore.userInfo">
    <template v-if="!smLess">
      <h4 class="p">编辑资料</h4>
      <el-divider />
    </template>
    <div class="p outer flex">
      <el-avatar class="self-center" :size="100" :src="getAvatarURL(userStore.userInfo.avatar)" />
      <div class="self-center flex gap-2">
        <el-upload :show-file-list="false" :http-request="upload">
          <template #trigger>
            <el-link type="primary" :icon="Upload" :disabled="uploading" :underline="false">
              上传头像
            </el-link>
          </template>
        </el-upload>
      </div>
    </div>
    <el-divider />
    <div class="p outer">
      <el-form
        ref="formRef"
        class="flex flex-col items-stretch md-p-l-100px md-p-r-100px"
        hide-required-asterisk
        @submit.prevent
        :model="data"
        :rules="rules"
      >
        <el-form-item prop="name" label="用户名">
          <el-input v-model="data.name" />
        </el-form-item>
        <el-form-item
          :class="{
            'self-center': !smLess,
          }"
        >
          <el-button
            :class="{
              'w-full': smLess,
            }"
            type="primary"
            native-type="submit"
            @click="submit"
            :loading="submitting"
          >
            保存设置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.p {
  padding: 0 var(--main-h-padding);
}
.outer {
  @apply flex flex-col gap-10px;
}
</style>
<script lang="ts">
import { getAvatarURL, patchRequest, request, uploadAvatar, validateAvatarFile } from '@/api';
import { minUsernameLength } from '@/components/app/LoginRegisterDialog.vue';
import { ordinarySchema } from '@/schemas/response';
import { useMediaStore } from '@/stores/media';
import { useUserStore } from '@/stores/user';
import { Upload } from '@element-plus/icons-vue';
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadRequestHandler,
} from 'element-plus';
import { storeToRefs } from 'pinia';
import { defineComponent, reactive, ref } from 'vue';
import type { RouteLocationNormalized } from 'vue-router';
function validate({ params: { id } }: RouteLocationNormalized) {
  if (!useUserStore().isSelf(id as string)) {
    ElMessage.error('不能编辑其他用户哦');
    return { name: 'User', params: { id } };
  }
}
export default defineComponent({
  beforeRouteEnter: validate,
  beforeRouteUpdate: validate,
});
</script>
<script setup lang="ts">
const userStore = useUserStore();
const uploading = ref(false);
const { smLess } = storeToRefs(useMediaStore());
const upload: UploadRequestHandler = async ({ file }) => {
  if (!validateAvatarFile(file)) return;
  uploading.value = true;
  try {
    const uploadResp = await uploadAvatar(file);
    if (!uploadResp) return;
    const changeResp = await request(ordinarySchema, {
      url: '/api/user/avatar',
      method: 'put',
      params: { code: uploadResp.data },
      errorDescription: '上传头像失败',
    });
    if (!changeResp) return;
    await userStore.updateSelfUserInfo();
    ElMessage.success('头像上传成功');
  } finally {
    uploading.value = false;
  }
};
const formRef = ref<FormInstance>();
const data = reactive({
  name: userStore.userInfo!.name,
});
const rules = reactive<FormRules<typeof data>>({
  name: [
    { required: true, message: '请输入用户名' },
    { min: minUsernameLength, message: `用户名长度不能小于${minUsernameLength}位` },
  ],
});
const submitting = ref(false);
async function submit() {
  try {
    await formRef.value!.validate();
  } catch {
    return;
  }
  submitting.value = true;
  const res = await patchRequest(data, userStore.userInfo!, {
    name: (name) =>
      request(ordinarySchema, {
        url: '/api/user/rename',
        method: 'put',
        data: {
          id: userStore.userInfo!.id,
          newName: name,
        },
        errorDescription: '修改用户名失败',
      }),
  });
  if (res === 'succeed') {
    await userStore.updateSelfUserInfo();
    ElMessage.success('修改成功');
  }
  submitting.value = false;
}
</script>
