<template>
  <div style="display: flex">
    <FileView :mode="mode" :file-list="fileList" @remove="handleRemove" />
    <el-upload
      v-if="mode !== 'look'"
      v-bind="$attrs"
      :file-list="fileList"
      :action="action"
      :headers="{ accesstoken: userStore.getToken }"
      :on-success="handleSuccess"
      list-type="picture-card"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
    >
      <el-icon>
        <Plus />
      </el-icon>
    </el-upload>
  </div>
</template>

<script setup lang="ts">
import FileView from './FileView.vue'
import { useUserStoreWithOut } from '../../../../../store/modules/user'
import { computed, ref, watch } from 'vue'
import type { UploadUserFile } from 'element-plus'

const userStore = useUserStoreWithOut()

const action = '/openapi/api/file/upload'
const fileList = ref<UploadUserFile[]>([])

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  // 展示模式
  mode: {
    type: String,
    default: 'add'
  },
  // 资源大小限制
  maxSize: {
    type: Number,
    default: 20
  }
})
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      fileList.value = val.split(',').map((item) => {
        return {
          url: item
        }
      })
    }
  },
  {
    immediate: true
  }
)

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

const handleRemove = (file) => {
  console.log(file)
  fileList.value = fileList.value.filter((item) => item.uid !== file.uid)
}

const handleSuccess = (response) => {
  fileList.value.push({
    url: response.data.fileUrl
  })
  console.log(fileList.value)
  emits('update:modelValue', fileList.value.map((item) => item.url).join(','))
}

const fileUrls = computed(() => {
  return fileList.value.map((item) => item.url).join(',')
})

defineExpose({
  fileUrls
})

const beforeUpload = (file) => {
  const isLimit = file.size / 1024 / 1024 <= props.maxSize
  if (!isLimit) {
    ElMessage.error('文件超出规定大小')
  }
  return isLimit
}
const handleExceed = () => {
  ElMessage.error('文件数量超出限制!')
}
const reset = () => {
  fileList.value = []
}
</script>

<style lang="less" scoped>
:deep(.el-upload--picture-card) {
  --el-upload-picture-card-size: 100px;
}
</style>
