<template>
  <!--  :limit="limit" :on-exceed="handleExceed"-->
  <div>
    <div class="fileUploadBox">
      <el-upload
        :action="uploadImgUrl"
        :headers="headers"
        :show-file-list="false"
        :on-success="uploadSuccess"
        :before-upload="handleBeforeUpload"
      >
        <div class="uploadBox">
          <el-icon size="20"><DocumentAdd /></el-icon>
          <div class="file">选择文件</div>
        </div>
      </el-upload>
    </div>
    <div class="tip">(支持Word,Excel,PDF,图片格式)</div>
    <el-table v-loading="loading" :data="fileTableList">
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column label="文件名" align="center" prop="fileName" width="200" />
      <!-- sortable -->
      <el-table-column label="上传时间" align="center" prop="createTime" width="200">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传人" align="center" prop="creatorName" />
      <el-table-column label="文件类型" align="center" prop="fileType" />
      <el-table-column
        label="操作"
        align="left"
        width="250"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template #default="scope">
          <el-button type="primary" link @click="downloadFile(scope.row)">下载</el-button>
          <el-button
            v-if="isImageFile(scope.row.fileName)"
            type="primary"
            link
            @click="handleView(scope.row)"
          >
            查看
          </el-button>
          <el-button type="primary" link @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="danger" link @click="handleDetele(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total >= 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getFileList"
    />
    <el-dialog title="重命名文件" v-model="editVisible" width="800px" append-to-body>
      <el-form>
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件名">
              <el-input v-model="form.fileName" placeholder="请输入文件名" maxlength="300" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="canelEdit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 图片查看器 -->
    <el-dialog v-model="imageViewerVisible" title="图片预览" width="60%">
      <div style="text-align: center">
        <el-image :src="imageUrl" fit="contain" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="FileUpload">
import { getToken } from '@/utils/auth'
import { addFile, getAppointmentFile, delFile, editAppointmentFile } from '@/api/sign/appointment'
const props = defineProps({
  activeName: { type: String, default: '' }, //tab名称
  formStatus: { type: String, default: '' }, //父组件状态，新增、修改
  idsObj: { type: Object, default: () => ({}) }, //父组件传递过来的id对象
  apiAppointmentInfoDto: { type: Object, default: () => ({}) }, //父组件传递过来的预约信息的详情
  appointmentStatus: { type: Number } //父组件传递过来的预约的状态
})
const { proxy } = getCurrentInstance()
const editVisible = ref(false)
const loading = ref(true)
const total = ref(0)
const fileTableList = ref([])
const limit = ref(2)
const fileSize = ref(10)
const headers = ref({ Authorization: 'Bearer ' + getToken() })
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + '/oss/api/oss/upload') // 上传的服务器地址
// 图片查看相关状态
const imageViewerVisible = ref(false)
const imageUrl = ref('')
const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    startTime: '',
    endTime: '',
    appointmentBizId: props.idsObj.appointmentBizId
  }
})

const { queryParams, form } = toRefs(data)
const canelEdit = () => {
  editVisible.value = false
  form.value = {}
  console.log('fileTableList', fileTableList.value)
}
const submitForm = () => {
  let obj = {
    appointmentFileBizId: form.value.appointmentFileBizId,
    fileName: form.value.fileName
  }
  editAppointmentFile(obj).then(response => {
    if (response.code == 200) {
      proxy.$modal.msgSuccess('文件名修改成功')
      editVisible.value = false
      getFileList()
    }
  })
}
const handleDetele = row => {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.fileName + '"的文件？')
    .then(function () {
      return delFile(row.appointmentFileBizId)
    })
    .then(res => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('删除成功')
        getFileList()
      }
    })
    .catch(() => {})
}
const isImageFile = fileName => {
  return /\.(jpg|jpeg|png|gif|bmp|webp|svg|ico)$/i.test(fileName || '')
}
const handleUpdate = row => {
  editVisible.value = true
  form.value = JSON.parse(JSON.stringify(row))
}
const handleView = row => {
  imageUrl.value = row.fileUrl
  imageViewerVisible.value = true
}
const downloadFile = row => {
  // 创建隐藏的下载链接
  const link = document.createElement('a')
  link.href = row.fileUrl
  link.target = '_blank' // 新窗口打开

  // 设置下载文件名（重要）
  // 从URL中提取文件名，或者使用返回的文件名
  const fileName = row.fileName
  link.download = fileName

  // 触发下载
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 上传前loading加载
function handleBeforeUpload(file) {
  // if (file.name.includes(',')) {
  //   proxy.$modal.msgError('文件名不正确，不能包含英文逗号!')
  //   return false
  // }
  const isLt = file.size / 1024 / 1024 < fileSize.value
  if (!isLt) {
    proxy.$modal.msgError(`上传文件大小不能超过 ${fileSize.value} MB!`)
    return false
  }
  // proxy.$modal.loading('正在上传文件，请稍候...')
}
// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`一次只能上传${limit.value}个文件!`)
}
const uploadSuccess = res => {
  console.log('上传成功', res)
  if (res.code == 200) {
    if (props.idsObj.appointmentBizId) {
      let submitObj = {
        appointmentBizId: props.idsObj.appointmentBizId,
        fileUrl: res.data.url,
        fileName: res.data.originalName,
        ossFileBizId: res.data.fileBizId
      }
      addFile(submitObj).then(res => {
        if (res.code == 200) {
          proxy.$message.success('文件上传成功')
          queryParams.value.pageNo = 1
          getFileList()
          // emit('handleSuccessEdit')
        }
      })
    }
  }
}
const getFileList = () => {
  loading.value = true
  try {
    getAppointmentFile(queryParams.value).then(response => {
      total.value = response.data.total
      fileTableList.value = response.data.records
      if (fileTableList.value.length > 0) {
        for (const item of fileTableList.value) {
          item.fileType = '预约文件'
        }
      }
      loading.value = false
    })
  } catch (error) {
    fileTableList.value = []
  } finally {
    loading.value = false
  }
}
watch(
  () => props.activeName,
  newVal => {
    if (newVal === 'accessories') {
      queryParams.value.pageNo = 1
      getFileList()
    }
  }
)
</script>
<style lang="scss" scoped>
.fileUploadBox {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  padding: 20px 0;
  border: 1px dashed #dcdfe6;
}
.uploadBox {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .file {
    font-size: 14px;
    margin-top: 10px;
    color: #409eff;
  }
}
.tip {
  font-size: 14px;
  color: #909399;
  margin: 10px 0 20px 0;
}
</style>
