<template>
  <el-upload
    v-bind="$attrs"
    list-type="picture-card"
    :file-list="fileList"
    :on-success="uploadSuccess"
  >
    <template #default>
      <i class="el-icon-plus"></i>
    </template>
    <template #file="{file}">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
          >
            <i class="el-icon-download"></i>
          </span>
          <span
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </template>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img :src="dialogImageUrl" alt="" style="width: 100%;">
  </el-dialog>
</template>

<script lang="ts">
import { computed, defineComponent, PropType, reactive, toRefs } from 'vue'
import { download } from 'skzz-utils/download'
import { getDataByKey } from 'skzz-utils/getDataByKey'

type FileList = {
  name: string
  url: string
  [key: string]: any
}

type Key = {
  name: string
  path: string
}
export default defineComponent({
  name: 'SkImageUpload',
  props: {
    baseUrl: String,
    modelValue: {
      type: Array as PropType<Array<FileList>>,
      default: () => ([]),
    },
    downloadUrl: String,
    dataKey: {
      type: Object as PropType<Key>,
      default: () => ({
        name: 'data.fileName',
        path: 'data.filePath',
      }),
    },
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const states = reactive({
      disabled: true,
      dialogVisible: false,
      dialogImageUrl: '',
    })
    const fileList = computed(() => props.modelValue)
    const uploadSuccess = res => {
      fileList.value.push({
        name: getDataByKey(res, props.dataKey.name),
        url: props.downloadUrl + getDataByKey(res, props.dataKey.path),
      })
      emit('update:modelValue', fileList)
    }
    const handleRemove = file => {
      const index = fileList.value.findIndex(item => item.url === file.url)
      fileList.value.splice(index, 1)
      emit('update:modelValue', fileList)
    }
    const handleDownload = file => {
      download(file.url, file.name)
    }
    const handlePictureCardPreview = file => {
      states.dialogImageUrl = file.url
      states.dialogVisible = true
    }
    return {
      ...toRefs(states),
      fileList,
      uploadSuccess,
      handleRemove,
      handleDownload,
      handlePictureCardPreview,
    }
  },
})
</script>
<style lang="scss" scoped>

</style>
