<script setup lang="ts">
import { ref, watch } from 'vue'
import { UpFileToken } from '@/api/public/index'
import { ElMessage, genFileId, ElLoading } from 'element-plus'
import { GlobalStore } from '@/stores/index'
import type { UploadProps, UploadRawFile, UploadFile, UploadFiles } from 'element-plus'

interface FileListType {
  url?: string
  name?: string | number
}

interface ProTableProps {
  // isImg?: boolean // 是否只能上传图片
  disabled?: boolean
  limit: number
  accept: string
  modelValue: string | string[]
  listType?: string
  errorText?: string
  successText?: string
}

const upload = ref()
const globalStore = GlobalStore()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const uploadData = {
  token: '',
  key: ''
}
let loadingInstance: any = null
const emit = defineEmits<{ (event: 'update:modelValue', value: string | string[]): void }>()

// 图片查看 放大
const handlePictureCardPreview = async (file: any) => {
  dialogImageUrl.value = file.url as string
  dialogVisible.value = true
}
// 图片上传之前
const beforeUpload = (file: any) => {
  loadingInstance = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  uploadData.key = file.name
}

const clickToken = async () => {

  UpFileToken({ User_tokey: globalStore.GET_User_tokey }).then(res => {
    uploadData.token = res.Data as string
  })



}
// 图片上传超出界限
const handleExceed: UploadProps['onExceed'] = (files: any) => {
  upload.value.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value.handleStart(file)
  upload.value.submit()
}

// 图片上传成功
const onSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  let ERPOSS = import.meta.env.VITE_BZD_ERPOSS_APP_API
  if (limit.value === 1) {
    emit('update:modelValue', ERPOSS + response.key)
  } else {
    let keys = uploadFiles.map((item: any) => ERPOSS + item.response.key)
    emit('update:modelValue', keys)
  }
  ElMessage.success(props.successText)
  loadingInstance.close()
  console.log('上传成功onSuccess',response,uploadFile,uploadFiles)
}
// 图片上传失败
const onError = () => {
  ElMessage.error(props.errorText)
  console.log('onError')
}
// 图片移除
const handleRemove: UploadProps['onRemove'] = (uploadFile: any, uploadFiles: UploadFiles) => {
  loadingInstance.close()
  if (limit.value === 1) {
    emit('update:modelValue', '')
  } else {
    let keys = uploadFiles.map((item: any) => {
      if (item.response.key !== uploadFile.response.key) {
        return item.response.key
      }
    })
    emit('update:modelValue', keys)
  }
}

// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<ProTableProps>(), {
  disabled: false,
  listType: 'picture-card',
  errorText: '图片上传失败!!',
  successText: '图片上传成功!!'
})

const fileList = ref<FileListType[]>([])
// const isImg = ref<boolean>(props.isImg)
const limit = ref<number>(props.limit)

watch(
  () => props.modelValue,
  pre => {
    if (pre && fileList.value.length !== limit.value) {
      if (limit.value === 1) {
        fileList.value.push({
          url: pre as string,
          name: genFileId()
        })
      } else {
        ; (pre as string[]).forEach((item: string) => {
          fileList.value.push({
            url: item,
            name: genFileId()
          })
        })
      }
    }
  }
)

const clearfileList = () => {
  fileList.value = []
}
defineExpose({
  clearfileList
})
</script>

<template>
  <div>
    <el-upload ref="upload" :accept="accept" :disabled="disabled" v-model:file-list="fileList"
      action="https://up-z2.qiniup.com" :list-type="listType" :limit="limit" :before-upload="beforeUpload"
      :auto-upload="true" :on-success="onSuccess" :on-error="onError" :on-exceed="handleExceed" :on-remove="handleRemove"
      :on-preview="handlePictureCardPreview" :data="uploadData" @click="clickToken">
      
      <!-- <el-upload v-model:file-list="data.fileList" style="width: 50px;height: 50px;" action="https://up-z2.qiniup.com"
        :disabled="data.drawerTiti == '详情' ? true : false" list-type="picture-card" :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload> -->

      <slot></slot>
      <template #tip>
        <div class="el-upload__tip">
          <slot name="tip"></slot>
        </div>
      </template>
    </el-upload>
    <el-dialog v-model="dialogVisible" style="z-index: 10;" :append-to-body="true">
      <img w-full :src="dialogImageUrl" class="full-img" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style scoped>
.full-img {
  width: 100%;
  height: 100%;
}
.el-upload--picture-card {
    height: 50px;
    width: 50px;
}
</style>
