<template>
  <el-form :model="formData" ref="applyForm" label-width="auto" :rules="rules">
    <el-row>
      <el-col :span="24">
        <el-form-item :label="label" prop="attachment">
          <template v-if="preview&&JSON.stringify(singleFile) !== '{}'&&JSON.stringify(singleFile)!=='null'">
            <el-button type="primary" link @click="handleDownload(singleFile)" style="font-size: 16px">
              {{ singleFile ? singleFile?.originalFileName : formData.singleFile?.originalFileName }}
            </el-button>
            <el-button type="danger" link @click="deleteSingleFile(singleFile,1)">删除</el-button>
          </template>
          <template v-else-if="!preview||JSON.stringify(singleFile) == '{}'||singleFile==null">
            <file-upload @getFile="getAttachment" :showFileList="showFileList" :multiple="false" :maxSize="1"
                         :disabled="isSingleFile" @delete="deleteAttachment"/>
          </template>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="其他文件">
          <el-card style="width: 100%">
            <file-upload @getFile="getOtherFile"/>
            <fvTable style="width: 100%;max-height: 300px;" v-if="showTable" :tableConfig="tableConfig"
                     :data="allFileList" :isSettingCol="false" :pagination="false">
              <template #empty>
                <el-empty :image-size="90" description="暂无数据" style="padding: 0"/>
              </template>
            </fvTable>
          </el-card>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup lang="jsx">
import FileUpload from '@/components/FileUpload.vue'
import {deleteFile, downloadFile} from "@/api/project-demand";
import {ElMessageBox, ElNotification} from "element-plus";

const props = defineProps({
  showFileList: {
    type: Boolean,
    default: false
  },
  label: {
    type: String,
    default: '项目附件'
  },
  showTable: {
    type: Boolean,
    default: true
  },
  preview: {
    type: Boolean,
    default: false
  },
  otherFileList: {
    type: Array,
    default: []
  },
  formData: {
    type: Object,
    default: {}
  }
})
const emit = defineEmits(["getAttachment", "getOtherFile"])
const tableConfig = reactive({
  columns: [
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: '80',
    },
    {
      prop: 'originalFileName',
      label: '文件名',
      align: 'center',
    },
    {
      prop: 'tag',
      label: '标签',
      align: 'center'
    },
    {
      prop: 'size',
      label: '文件大小',
      align: 'center',
      currentRender: ({row, index}) => (parseInt(row.size / 1024) + 'KB')
    },
    {
      prop: 'oper',
      label: '操作',
      align: 'center',
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        let btn = []
        btn.push({label: '下载', func: () => handleDownload(row), type: 'primary'})
        // if (row.newFile){
        //   btn.push({label: '删除', func: () => handleDelete(row), type: 'primary'})
        // }
        return (
            <div style={{width: '100%'}}>
              {
                btn.map(item => (
                    <el-button
                        type={item.type}
                        onClick={() => item.func()}
                        link
                    >
                      {item.label}
                    </el-button>
                ))
              }
              {
                row.newFile || props.preview || !props.preview ?
                    <popover-delete name={row.originalFileName} type={'文件'} btnType={'danger'}
                                    perm={['mosr:requirement:del']}
                                    onDelete={() => handleDelete(row)}/>
                    : ''
              }
            </div>
        )
      }
    }
  ]
})
const rules = reactive({
  attachment: [{required: true, message: '请上传附件', trigger: ['blur', 'change']}],
})
const applyForm = ref()
const singleFile = ref()
const isSingleFile = ref(false)
const allFileList = ref([])
watch(() => props.showTable, (newVal) => {
  props.showTable = newVal
}, {deep: true})
watch(() => props.formData.fileList, (newVal) => {
  console.log('newVal-fileList', newVal)
  if (props.preview) {
    newVal?.forEach(item => {
      allFileList.value.push(item)
    })
  }
}, {deep: true})
watch(() => props.otherFileList, (newVal) => {
  console.log('newotherFileList', newVal,props.formData)
  if (props.preview) {
    if (props.formData.fileList === null || props.formData.fileList.length === 0) {
      allFileList.value = newVal
    } else {
      newVal?.forEach(item => {
        allFileList.value.push(item)
      })
    }
  } else {
    allFileList.value = newVal
  }
}, {deep: true})
watch(() => props.formData.singleFile, (newVal) => {
  console.log('singleFile', newVal)
  singleFile.value = newVal
}, {deep: true})
watch(() => isSingleFile.value, (newVal) => {
  isSingleFile.value = newVal
}, {deep: true})
const handleDelete = (row) => {
  deleteFile(row.fileId).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      allFileList.value.splice(allFileList.value.findIndex((item) => item.id === row.fileId), 1);
    }
  });
}
const getAttachment = (val) => {
  isSingleFile.value = true
  emit('getAttachment', val)
}
const getOtherFile = (val) => {
  emit('getOtherFile', val)
}
const deleteAttachment = (val) => {
  deleteFile(val).then(res => {
    if (res.code === 1000) {
      ElNotification({
        title: '提示',
        message: "删除成功",
        type: 'success'
      })
      isSingleFile.value = false
      singleFile.value = null
    }
  });
}
const deleteSingleFile = (row, type) => {
  ElMessageBox.confirm(`确认删除名称为${row.originalFileName}的文件吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteFile(row.fileId).then(res => {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: res.code === 1000 ? 'success' : 'error'
      })
      if (res.code === 1000) {
        isSingleFile.value = false
        if (type === 1) {
          singleFile.value = null
        } else {
          props.otherFileList.splice(props.otherFileList.findIndex((item) => item.id === row.fileId), 1);
        }
      }
    });
  }).catch(() => {
    ElNotification({
      title: '提示',
      message: "用户取消删除! ",
      type: 'warning'
    })
  })
}
const handleDownload = (row) => {
  downloadFile(row.fileId).then(res => {
    const blob = new Blob([res])
    let a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = row.originalFileName
    a.click()
  })
}
defineExpose({
  validate() {
    return applyForm.value.validate()
  },
  clearValidate() {
    return applyForm.value.clearValidate()
  },
  allFileList,
  singleFile,
  isSingleFile
})
</script>

<style scoped>
:deep(.el-table--fit ) {
  height: 300px !important;
}
</style>
