<template>
  <el-table border :data="fileList">
    <el-table-column align="center" :label="label1">
      <template #default="{ row }">
        <template v-if="row.createdBy">
          {{ row.name }}
        </template>
        <el-input
          v-else v-model.trim="allName[`${row.id}`]" clearable :loading="allLoading[`${row.id}`]"
          placeholder="不填则为默认文件名称"
        />
      </template>
    </el-table-column>
    <el-table-column align="center" :label="label2">
      <template #default="{ row, $index }">
        <upload-file-link v-if="row.createdBy" :file-id="row.id" :file-name="row.name">
          {{ row.name }}
        </upload-file-link>
        <upload-file-single
          v-else :accept="accept" :auto-upload="false" :index-key="`${row.id}`" :max-size="20"
          :file-name="allName[`${row.id}`]" :loading="allLoading[`${row.id}`]"
          @on-change="$event => onChange($event, row.id)" @on-success="$event => onSuccess($event, row, $index)"
          @on-error="onError(row.id)"
        />
      </template>
    </el-table-column>
    <el-table-column align="center" :label="label3" width="200px">
      <template #default="{ row, $index }">
        <el-popconfirm v-if="row.createdBy" :title="popconfirm" :disabled="disabled" @confirm="remove($index)">
          <template #reference>
            <el-button type="danger" :disabled="disabled" link>
              删除
            </el-button>
          </template>
        </el-popconfirm>
        <template v-else>
          <el-button type="primary" :loading="allLoading[`${row.id}`]" link @click="save(row.id)">
            保存
          </el-button>
          <el-button type="danger" :loading="allLoading[`${row.id}`]" link @click="remove($index)">
            取消
          </el-button>
        </template>
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup name="ThUploadTable">
import type { UploadFile } from 'element-plus'

const props = withDefaults(defineProps<{
  /** 上传格式 */
  accept?: string
  /** 列1的文字 */
  label1?: string
  /** 列2的文字 */
  label2?: string
  /** 列3的文字 */
  label3?: string
  disabled?: boolean
  /** 文件列表，支持v-model */
  fileList?: FileVO[]
  /** 删除按钮提示文字 */
  popconfirm?: string
}>(), {
  accept: '.jpeg,.jpg,.png,.bmp',
  label1: '文件名称',
  label2: '图片上传',
  label3: '操作',
  fileList: () => [],
  popconfirm: '是否删除本行？',
})

const emit = defineEmits<{
  (event: 'update:fileList', fileList?: FileVO[]): void
}>()

const allName = reactive<Record<string, string | undefined>>({})

const allLoading = reactive<Record<string, boolean | undefined>>({})

function onSuccess(file: FileVO, row: FileVO, index: number) {
  const indexKey = `${row.id}`
  const newList = [...props.fileList.slice(0, index), file, ...props.fileList.slice(index + 1)]
  emit('update:fileList', newList)
  allLoading[indexKey] = false
}

function onError(id: number) {
  const indexKey = `${id}`
  allLoading[indexKey] = false
}

function onChange(uploadFile: UploadFile, id: number) {
  const indexKey = `${id}`

  if (uploadFile.status !== 'ready') {
    allLoading[indexKey] = false
    return
  }
  if (allName[indexKey])
    return

  const arr = uploadFile.name.split('.')
  arr.pop()
  /** 去除拓展名的文件名 */
  const newFilename = arr.join('.')
  // 特殊情况时例如：.npmrc 使用原始文件名
  allName[indexKey] = newFilename || uploadFile.name
}

function save(id: number) {
  const indexKey = `${id}`
  allLoading[indexKey] = true
}

function remove(index: number) {
  const newList = [...props.fileList.slice(0, index), ...props.fileList.slice(index + 1)]
  emit('update:fileList', newList)
}
</script>
