<template>
  <Dialog
    v-model="diaVisible"
    diaTitle="附件"
    width="60%"
    height="70%"
    @close="closeFun"
    show-footer
  >
    <BaseTable
      ref="tableRef"
      showIndex
      tableName="DEMAND_ATTACHMENT"
      :params="{ uuid: demandId }"
      :api="queryDemandFilesApi"
      :searchLimitNum="3"
      :actionList="actionList"
      fullHeight
    >
      <template #fileSize="{ row }">
        {{ formatFileSize(row.fileSize) }}
      </template>
      <template #fileType="{ row }">
        {{ ALL_FILE_TYPE.O[row.fileType] }}
      </template>
    </BaseTable>
    <template #footer>
      <div>
        <el-button @click="closeFun">取消</el-button>
        <el-button type="primary" @click="closeFun">确认</el-button>
      </div>
    </template>
  </Dialog>
  <FilePreview v-model="previewVisible" :fileId="previewFileId" />
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import Dialog from '@/components/common/dialog/index.vue';
import { dataDelFileApi } from '@/api/data/data';
import { formatFileSize } from '@/utils/file';
import { ElMessage } from 'element-plus';
import { downloadFileById } from '@/utils/file';
import { useDict } from '@/utils/useDict';
import FilePreview from '@/components/common/filePreview/index.vue';
import { useI18n } from 'vue-i18n';
import { queryDemandFilesApi } from '@/api/project/demand';

const { t } = useI18n();

const actionList = ref([
  {
    title: t('通用.预览'),
    type: 'primary',
    hide: (row: any) => row.fileResource === 'EP',
    click: (row: any) => {
      reviewFile(row.id);
    },
  },
  {
    title: t('通用.下载'),
    type: 'primary',
    click: (row: any) => {
      if (row.fileResource === 'EP') {
        window.open(row.fileUrl, '_blank');
      } else {
        downloadFile(row);
      }
    },
  },
  {
    title: t('通用.删除'),
    needConfirm: true,
    confirmTip: t('通用.确认删除吗'),
    type: 'danger',
    hide: (row: any) => row.fileResource === 'EP',
    click: (row: any) => {
      deleteFileFun(row.id);
    },
  },
]);
const props = defineProps<{
  visible: boolean;
  demandId: string;
}>();

const emits = defineEmits(['update:visible']);
const { ALL_FILE_TYPE } = useDict('ALL_FILE_TYPE');

const diaVisible = computed({
  get: () => props.visible,
  set: (val) => {
    emits('update:visible', val);
  },
});

const previewVisible = ref(false);
const previewFileId = ref<any>('');

const closeFun = () => {
  diaVisible.value = false;
};
const tableRef = ref();
const deleteFileFun = async (id: number) => {
  const res: any = await dataDelFileApi({ delFileId: id });
  if (res.code === 200) {
    ElMessage.success('删除成功');
    tableRef.value.resetFun();
  }
};

const downloadFile = (row: any) => {
  downloadFileById(row.id);
};

const reviewFile = (id: number) => {
  previewFileId.value = id;
  previewVisible.value = true;
};
</script>
