<template>

  <el-card :class="mergeParameters.cardClass">
    <div class="clearfix" style="display: flex; align-items: center; justify-content: space-between;">
      <span><span style="color: red;" v-if="mergeParameters.required">*</span>{{ mergeParameters.title }}</span>
      <el-upload
          ref="upload"
          :show-file-list="false"
          :action="mergeParameters.url"
          :multiple="mergeParameters.multiple"
          :auto-upload="mergeParameters.autoUpload"
          :on-error="mergeFileActions.error"
          :on-change="mergeFileActions.change"
          :on-success="mergeFileActions.success"
          :headers="mergeParameters.headers">
        <el-button v-if="mergeParameters.mode !== 'detail' && mergeParameters.isShowBtn" slot="trigger" type="primary">
          <template #icon>
            <font-awesome-icon icon="upload"/>
          </template>
          选择文件
        </el-button>
      </el-upload>
    </div>

    <div>
      <el-table :data="tableData" border style="width: 100%; padding-top: 5px;">
        <el-table-column fixed prop="name" :label="mergeParameters.tableTitle + '名称'"/>
        <el-table-column v-if="mergeParameters.isShowType" fixed prop="type"
                         :label="mergeParameters.tableTitle + '文件类型'" width="200" align="center"></el-table-column>
        <el-table-column v-if="mergeParameters.autoUpload" fixed prop="uploadStatus"  width="100" label="上传状态"></el-table-column>
        <el-table-column fixed="right" label="操作" width="120" align="center" class-name="control-column">
          <template #default="scope">
            <el-space>
              <el-link type="primary" v-if="isDowload(scope.row)" size="small" @click="downloadFile(scope.row)">
                {{ isPicture(scope.row.name) ? '查看' : '下载' }}
              </el-link>
              <el-link type="primary" size="small" v-if="mergeParameters.mode !== 'detail'"
                       @click="deleteRow(scope.$index, tableData,scope.row)">
                删除
              </el-link>

            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <PictureView ref="pictureViewRef"/>
  </el-card>
</template>

<script setup>

import {computed, defineEmits, defineProps, reactive, ref} from "vue"
import {merge} from "lodash"
import {ElMessage} from "element-plus"
import PictureView from "@pages/common/PictureView.vue";
const pictureViewRef = ref(null)
const props = defineProps({
  parameters: {
    type: Object,
    default: () => ({})
  },
  fileActions: {
    type: Object,
  },
  filesData: {
    type: Array,
    default: () => []
  }
})

const onError = (err, file, fileList) => { // 文件上传失败时的钩子
  ElMessage.error('上传失败!' + err)
}

const deleteRow = (index, fileList ,row) => { // 点击删除时的方法
  const source = Object.assign([], fileList)
  let id = fileList[index].id// 记录删除的ID
  fileList.splice(index, 1)
  emit('on-remove', fileList, id, {index: index, source: source},row)
}

const viewPicture = (scope) => { // 预览图片
}

const isPicture = (fileName) => { // 是否是图片
  return /\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileName)
}

const isDowload = (file) => { // 是否显示下载按钮
  return mergeParameters.mode !== 'add' && file.url
}

const downloadFile = (row) => { // 下载文件
  if (row && row.downloadUrl) {
    if (/(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(row.type) || /\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(row.name)) {
      pictureViewRef.value.viewPicture(row.downloadUrl)
    } else {
      window.open(row.downloadUrl)
    }
  }
}

const onChange = (file, fileList) => { // 文件上传时的钩子
  emit('on-change', file)
}

const onSuccess = (response, file, fileList) => { // 文件上传成功时的钩子
  let data = response.data
  data.bz = mergeParameters.autoUpload ? mergeParameters.title : fileMap[file.uid] ? fileMap[file.uid] : '' // 当自动上传时，上传文件备注默认为标题
  data.fileType = mergeParameters.fileType
  if (response.result === 'success') {
    data.uploadStatus = '上传成功'
    if (mergeParameters.autoUpload) { // 自动上传
      emit('on-success', data, file)
    } else { // 手动上传回调
      data.uid = file.uid
      emit('on-manual-success', data)
    }
  } else {
    ElMessage.error('上传失败!:'+response.msg)
  }
}

const defaultParameters = {
  headers: {},
  url: null,
  title: '文件上传',
  tableTitle: '材料',
  autoUpload: false,
  required: true,
  multiple: true,
  mode: 'add',
  isShowBtn: true,
  isShowType: true,
  fileType: '',
  cardClass: 'box-card'
}

const defaultFileActions = {
  error: onError,
  change: onChange,
  success: onSuccess
}

const fileMap = reactive(merge({}))
const mergeParameters = reactive(merge({}, defaultParameters, props.parameters))
const mergeFileActions = reactive(merge({}, defaultFileActions, props.fileActions))

const emit = defineEmits(['on-remove', 'on-success', 'on-manual-success', 'update:actions'])

const mergeActions = reactive(merge({}, defaultFileActions, props.actions))
emit('update:actions', mergeActions)

const tableData = computed(() => {
  let arr = []
  for (let data of props.filesData) {
    arr.push(data)
  }
  return arr
})

</script>

<style scoped lang="scss">
.el-card {
  width: 100%;
}

.linkFix {
  .el-link {
    margin-right: 10px !important;
  }
}

:deep(.el-table) {
  padding-top: 0px !important;
}

:deep(.el-card__body) {
  padding: 10px 20px;
}
</style>
