<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue';

import { useVModel } from '@vueuse/core';
import { Modal, Upload } from 'ant-design-vue';

import { uploadFile } from '#/api/core/upload';
import { Icon } from '#/components/icon';

defineOptions({
  name: 'UploadImage',
  inheritAttrs: false,
});

const props = defineProps({
  modelValue: {
    type: Array as () => string[],
    default: () => [],
  },
  multiple: {
    type: Boolean,
    default: true,
  },
  maxCount: {
    type: Number,
    default: 9,
  },
});

const emits = defineEmits(['update:modelValue']);

const mValue = useVModel(props, 'modelValue', emits, {
  passive: true,
});

// 初始化 fileList
const fileList = ref([]);
const isInitializing = ref(true);

// 同步 modelValue 到 fileList
const syncModelToFileList = (urls: string[]) => {
  // console.log('[UploadImage] 同步 modelValue 到 fileList:', urls);
  fileList.value = urls.map((url) => ({
    uid: url,
    name: url.split('/').pop() || 'file',
    status: 'done',
    url,
  }));
};

// 同步 fileList 到 modelValue
const syncFileListToModel = () => {
  const urls = fileList.value
    .filter((file) => file.status === 'done' && file.url)
    .map((file) => file.url);

  // console.log('[UploadImage] 同步 fileList 到 modelValue:', urls);
  mValue.value = urls;
};

// 监听 modelValue 变化
watch(props.modelValue, (newVal) => {
  // console.log('[UploadImage] 检测到 modelValue 变化:', newVal);
  if (!isInitializing.value) {
    syncModelToFileList(newVal);
  }
});

// 监听 fileList 变化
watch(fileList, (newVal) => {
  // console.log('[UploadImage] 检测到 fileList 变化:', newVal);
  if (!isInitializing.value) {
    syncFileListToModel();
  }
});

// 组件挂载时初始化
onMounted(() => {
  // console.log('[UploadImage] 组件挂载，初始化 fileList:', props.modelValue);
  syncModelToFileList(props.modelValue);

  nextTick(() => {
    isInitializing.value = false;
    // console.log('[UploadImage] 初始化完成');
  });
});

// 新增：监听父组件传入的 props 变化
watch(
  () => props.modelValue,
  (newVal) => {
    // console.log('[UploadImage] 父组件传入新的 modelValue:', newVal);
    syncModelToFileList(newVal);
  },
  { deep: true, immediate: true },
);

const customRequest = async (e: any) => {
  try {
    // console.log('[UploadImage] 开始上传文件:', e.file.name);
    const res = await uploadFile({
      file: e.file,
    });

    // 更新 fileList
    fileList.value = [
      ...fileList.value.filter((file) => file.status !== 'uploading'),
      {
        uid: res.url,
        name: e.file.name,
        status: 'done',
        url: res.url,
      },
    ];

    // console.log('[UploadImage] 文件上传成功:', res.url);
    // 触发上传完成回调
    e.onSuccess?.(res);
  } catch (error) {
    console.error('[UploadImage] 上传失败:', error);
    e.onError?.(error);
  }
};

const handleRemove = (file: any) => {
  // console.log('[UploadImage] 删除文件:', file.name);
  // 从 fileList 中移除
  fileList.value = fileList.value.filter((item) => item.uid !== file.uid);
};

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const handlePreview = async (file) => {
  // console.log('[UploadImage] 预览文件:', file.name);
  previewImage.value = file.response?.url || file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value =
    file.name ||
    file.url?.slice(Math.max(0, file.url.lastIndexOf('/') + 1)) ||
    '预览图片';
};

// 计算是否还能上传更多图片
const showUploadButton = computed(() =>
  props.multiple
    ? fileList.value.length < props.maxCount
    : fileList.value.length === 0,
);
</script>

<template>
  <Upload
    :file-list="fileList"
    :custom-request="customRequest"
    :multiple="multiple"
    :limit="maxCount"
    :show-upload-list="{ showPreviewIcon: true, showRemoveIcon: true }"
    list-type="picture-card"
    @remove="handleRemove"
    @preview="handlePreview"
  >
    <div v-if="showUploadButton" class="upload-button">
      <Icon icon="ant-design:plus-outlined" />
      <div class="ant-upload-text">上传图片</div>
    </div>
  </Upload>
  <Modal
    v-model:visible="previewVisible"
    :title="previewTitle"
    footer=""
    width="60%"
  >
    <img alt="example" style="width: 100%" :src="previewImage" />
  </Modal>
</template>

<style lang="less" scoped>
.m-avatar-wrap {
  position: relative;
  height: 102px;
  width: 102px;

  .m-avatar-icon-delete {
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.3s;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border-radius: 0 0 0 4px;
    padding: 2px 4px;
  }

  &:hover .m-avatar-icon-delete {
    opacity: 1;
  }
}

.upload-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  cursor: pointer;
}
</style>
