<template>
  <Dialog :title="dialogTitle" width="80%" v-model="dialogVisible" @closed="beforeClose" center>
    <el-card class="hl-card-info">
      <el-row>
        <el-col>
          <el-card class="hl-incard">
            <el-col>
              <el-upload ref="uploadRef" :file-list="uploadFiles" multiple :action="uploadUrl" :headers="{
                    Authorization: 'Bearer ' + getAccessToken(),
                    'tenant-id': getTenantId()
                  }" name="files" :show-file-list="false" :auto-upload="false" :data="uploadData" :on-change="uploadChange" class="upload-file-uploader">
                <el-button type="primary">
                  <Icon icon="ep:upload-filled" />上传
                </el-button>
              </el-upload>
            </el-col>
            <el-table :data="formData.attachments"  v-loading="tableLoading" class="hl-table">
              <el-table-column fixed type="index" width="100" label="序号" align="center" />
              <el-table-column prop="name" label="文件名称" align="center" />
              <el-table-column prop="createTime" align="center" label="上传时间" :formatter="dateFormatter" />
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button link type="danger" size="small" @click="handleDeleteAttachment(scope.$index)">
                    删除
                  </el-button>
                  <el-button v-if="!!scope.row.id" link type="primary" size="small" @click="downloadAttachment(scope.row.name, scope.row.url)">
                    下载
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    <template #footer>
      <el-button @click="dialogVisible=false" size="large">取 消</el-button>
      <el-button @click="submitForm" type="success" size="large">保 存</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import {ref, toRefs} from "vue";
import {ElTable, UploadUserFile} from 'element-plus'
import {deleteFileLogic, downloadFile, getFilePage} from "@/api/infra/file";
import {getAccessToken, getTenantId} from "@/utils/auth";
import download from "@/utils/download";
import {dateFormatter} from "@/utils/formatTime";

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()
const dialogVisible = ref(false) // 弹窗的是否展示
const tableLoading = ref(false)

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数

const props = defineProps({
  title: String,
  id: Number,
  type: String,
  fileType: String
})
const businessId = toRefs(props).id
const businessType = toRefs(props).type
const businessFileType = toRefs(props).fileType
const dialogTitle = toRefs(props).title
watch(props, (newProps) => {
  handleQuery()
})



const formData = ref({
  attachments: []
})

const reset = () => {
  formData.value = {
    attachments: []
  }
}

const uploading = ref(false)
const uploadUrl = ref(import.meta.env.VITE_UPLOAD_BATCH_URL)
const uploadRef = ref()
const uploadFiles = ref<UploadUserFile[]>([])
const uploadData = ref({
  businessType: businessType?.value,
  businessId: businessId?.value,
  businessFileType: businessFileType?.value
})

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if(uploadFiles.value.length > 0){
    uploadData.value.businessId = businessId?.value
    uploadData.value.businessFileType = businessFileType?.value
    await uploadRef.value!.submit()
    message.success(t('cropper.uploadSuccess'))
  }
  dialogVisible.value = false
}

// 下载文件
const downloadAttachment = async (name, url) => {
  const data = await downloadFile(url)
  download.any(data, name)
}

const uploadChange = (file, files) => {
  uploadFiles.value = files
  refreshAttachments(files)
}

const refreshAttachments = (files) => {
  formData.value.attachments = formData.value.attachments.filter((value, index, array) => {
    return value.id
  })

  for (let i = 0; i < files.length; i++) {
    let file = files[i]
    file.businessFileType = businessFileType?.value
    file.createTime = new Date()
    formData.value.attachments.push(file)
  }
  // 排序
  formData.value.attachments.sort((v1, v2) => v1.createTime - v2.createTime)
}

// 删除附件
const handleDeleteAttachment = async (index) => {
  const deletedAttachments = formData.value.attachments.splice(index, 1)
  for (let i = 0; i < deletedAttachments.length; i++) {
    const attachment = deletedAttachments[i]
    if (attachment.id) {
      // 清理已上传文件
      await deleteFileLogic(attachment.id)
    }
    // 清理待上传文件
    uploadFiles.value = uploadFiles.value.filter((file1) => {
      return file1.name != attachment.name
    })
  }
}

const handleQuery = async () => {
  tableLoading.value = true
  reset()
  try {
    // 附件信息
    let attParams = {
      pageNo: 1,
      pageSize: 99,
      businessId: businessId?.value,
      businessType: businessType?.value,
      businessFileType: businessFileType?.value
    }
    formData.value.attachments = (await getFilePage(attParams)).list
  }finally {
    tableLoading.value = false
  }
}

const beforeClose = () => {

}

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  handleQuery()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>

