<template>
  <div class="app-container">
    <TableSearch
        :queryParams="queryParams"
        :showSearch="showSearch"
        queryRef="queryRef"
        @refresh="resetQuery"
        @search="handleQuery"
    >
      <template #one>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
          <el-form-item label="文件名" prop="fileName">
            <el-input
                v-model="queryParams.fileName"
                clearable
                placeholder="请输入文件名"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
          <el-form-item label="文件类型" prop="fileType">
            <el-select v-model="queryParams.fileType">
              <el-option v-for="item in fileType" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </template>

    </TableSearch>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['system:file:add']"
            icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            type="success"-->
      <!--            plain-->
      <!--            icon="Edit"-->
      <!--            :disabled="single"-->
      <!--            @click="handleUpdate"-->
      <!--            v-hasPermi="['system:file:edit']"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['system:file:remove']"
            :disabled="multiple"
            icon="Delete"
            plain
            type="danger"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            type="warning"-->
      <!--            plain-->
      <!--            icon="Download"-->
      <!--            @click="handleExport"-->
      <!--            v-hasPermi="['system:file:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="文件名" prop="fileName" show-overflow-tooltip/>
      <el-table-column align="center" label="文件类型" prop="fileType">
        <template #default="scope">
          {{ fileType.find(item => item.value === scope.row.fileType)["label"] }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="上传时间" prop="uploadTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建者" prop="createBy"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="100">
        <template #default="scope">
          <el-icon style="cursor: pointer" @click="handlePreview(scope.row)">
            <View/>
          </el-icon>
          <!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:file:edit']">修改</el-button>-->
          <!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:file:remove']">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />

    <!-- 添加或修改文件管理对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body class="file-upload" width="500px" @close="getList()">
      <el-upload
          v-model:file-list="uploadFileList"
          :action="`${data.baseUrl}/system/file/upload`"
          :before-upload="beforeAvatarUpload"
          :data="{fileType:uploadFileType}"
          :headers="{
                'authorization':  getToken()
              }"
          :limit="1"
          :on-error="uploadError"
          :on-success="uploadSuccess"
          class="file-uploader"
      >
        <el-icon style="font-size:28px;color: #8c939d;width: 178px;height: 178px;text-align: center;">
          <Plus/>
        </el-icon>
        <template #tip>
          <div class="el-upload__tip">
            支持格式：json/ xlsx/ txt / png / jpg / jpeg / mp3 / mp4
          </div>
        </template>
      </el-upload>

      <!--      <template #footer>-->
      <!--        <div class="dialog-footer">-->
      <!--          <el-button type="primary" @click="submitUplodaForm">确 定</el-button>-->
      <!--          <el-button @click="cancel">取 消</el-button>-->
      <!--        </div>-->
      <!--      </template>-->
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog v-model="openPreview" :title="title" append-to-body width="600px">
      <div style="height: 50vh">
        <!--文字-->
        <!--图片-->
        <template v-if="currentFile.fileType===1">
          <el-image :preview-src-list=[currentFile.filePath] :src="currentFile.filePath"
                    fit="fill" style="width: 100%; height: 100%">
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <picture/>
                </el-icon>
              </div>
            </template>
          </el-image>
        </template>
        <!--音频-->
        <template v-if="currentFile.fileType===2">
          <audio :src="currentFile.filePath" controls style="width: 100%;height: 100%"></audio>
        </template>
        <!--视频-->
        <template v-if="currentFile.fileType===3">
          <video :src="currentFile.filePath" controls style="width: 100%;height: 100%"></video>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script name="File" setup>
import {addFile, delFile, getFile, listFile, updateFile} from "@/api/system/file"
import {fileType, supportType} from "@/enum/index.js";
import {Plus, View} from "@element-plus/icons-vue";
import TableSearch from "@/components/TableSearch/index.vue";
import {getToken} from "@/utils/auth.js";
import {parseTime} from "../../../utils/ruoyi.js";

const {proxy} = getCurrentInstance()

const fileList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const openPreview = ref(false)
const currentFile = ref({})
const uploadFileList = ref([])
const uploadFileType = ref(null)

const data = reactive({
  baseUrl: import.meta.env.VITE_APP_BASE_API,
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {}
})

const {queryParams, form, rules} = toRefs(data)

/** 查询文件管理列表 */
function getList() {
  loading.value = true
  listFile(queryParams.value).then(response => {
    fileList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    fileId: null,
    fileName: null,
    filePath: null,
    fileSize: null,
    fileType: null,
    uploadBy: null,
    uploadTime: null,
    md5: null
  }
  proxy.resetForm("fileRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.fileId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "文件上传"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _fileId = row.fileId || ids.value
  getFile(_fileId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改文件管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["fileRef"].validate(valid => {
    if (valid) {
      if (form.value.fileId != null) {
        updateFile(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addFile(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _fileIds = row.fileId || ids.value
  proxy.$modal.confirm('是否确认删除文件管理编号为"' + _fileIds + '"的数据项？').then(function () {
    return delFile(_fileIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/file/export', {
    ...queryParams.value
  }, `file_${new Date().getTime()}.xlsx`)
}

getList()

/** 文件预览操作 */
function handlePreview(row) {
  console.log(row)
  if (row?.fileName?.endsWith('.json')) {
    window.open(row.filePath)
    return
  }
  openPreview.value = true
  title.value = row.fileName
  currentFile.value = row
}

const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile.type)
  const {label = undefined, value = undefined} = supportType?.find(item => item.label === rawFile.type)
  if (label) {
    uploadFileType.value = value
    return true
  }
  proxy.$modal.msgError(`暂不支持上传格式为${rawFile.type}的文件`)
  return false
}

const uploadSuccess = (e) => {
  proxy.$modal.msgSuccess("上传成功")
  uploadFileList.value = []
}
const uploadError = (e) => {
  console.log("uploadError", e)
}
</script>
