<template>
  <div class="project-file">
    <BaseTable
      showIndex
      tableName="NODE_DETAIL_FILE"
      ref="tableRef"
      full-height
      :params="searchParams"
      :api="dataQueryDirApi"
      :actionList="actionList"
    >
      <template #leftOptions>
        <el-button :disabled="freeze" icon="plus" @click="openDialog('add')" type="primary">
          上传
        </el-button>
      </template>
      <template #fileType="{ row }">
        <!-- {{ ALL_FILE_TYPE.O[row.fileType] || '--' }} -->
        <FileTypeChange v-model="row.fileType" :id="row.id" />
      </template>
      <template #fileSize="{ row }">
        {{ formatFileSize(row.fileSize) }}
      </template>
    </BaseTable>
    <Dialog
      v-model="dialogVisible"
      :diaTitle="isEditDialog ? '编辑' : '上传文件'"
      :width="500"
      :height="500"
      show-confirm-button
      show-cancel-button
      show-footer
    >
      <div class="content">
        <TableForm ref="tableFormRef" tableName="NODE_DETAIL_FILE" v-model:data="editRowInfo" />
      </div>
      <template #footer>
        <div>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUploadFun">确定</el-button>
        </div>
      </template>
    </Dialog>
    <FilePreview v-model="previewVisible" :fileId="previewFileId" />
  </div>
</template>

<script lang="ts" setup>
import BaseTable from '@/components/common/table/baseTable.vue';
import Dialog from '@/components/common/dialog/index.vue';
import { onBeforeUnmount, onMounted, ref } from 'vue';
import {
  batchAddFileInfoApi,
  dataDelFileApi,
  dataQueryDirApi,
  dataUpdateFileApi,
} from '@/api/data/data';
import TableForm from '@/components/common/table/tableForm.vue';
import { upload } from '@/api/request';
import { formatFileSize } from '@/utils/file';
import { ElMessage } from 'element-plus';
import FilePreview from '@/components/common/filePreview/index.vue';
import { downloadFileById } from '@/utils/file';
import emitter from '@/utils/eventBus';
import FileTypeChange from '@/components/common/fileTable/fileTypeChange.vue';

const env = import.meta.env;
const PREFIX = env.VITE_API_PREFIX_PROJECT;

const props = defineProps({
  projectId: {
    type: Number,
    default: 0,
  },
  projectName: {
    type: String,
    default: '',
  },
  projectUuid: {
    type: String,
    default: '',
  },
  freeze: {
    type: Boolean,
    default: false,
  },
});

const searchParams = ref({ uuid: props.projectUuid, queryTarget: 2 });

const isEditDialog = ref(false);
const previewVisible = ref(false);
const previewFileId = ref<any>('');
const dialogVisible = ref(false);
const actionList = ref<any>([
  {
    title: '预览',
    type: 'primary',
    click: (row: any) => {
      previewFileId.value = row.id;
      previewVisible.value = true;
    },
  },
  {
    title: '下载',
    type: 'primary',
    click: (row: any) => {
      downloadFile(row.id);
    },
  },
  {
    title: '编辑',
    type: 'primary',
    click: (row: any) => {
      openDialog('edit', row);
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确认删除？',
    click: (row: any) => {
      deleteFileFun(row.id);
    },
  },
]);

const editRowInfo = ref({});

const oldFile = ref();

const openDialog = (type: string, row?: any) => {
  isEditDialog.value = type === 'edit';
  dialogVisible.value = true;
  if (type === 'edit' && row) {
    row.fileType = String(row.fileType);
    row.files = [{ name: row.originalName, id: row.id }];
    oldFile.value = {
      id: row.id,
    };
    editRowInfo.value = { ...row };
  } else if (type === 'add') {
    editRowInfo.value = {};
  }
};

const tableFormRef = ref();
const tableRef = ref();

const confirmUploadFun = async () => {
  const valid = await tableFormRef.value.validateFun();
  if (valid) {
    const fromData = tableFormRef.value.getFormDataFun();
    const sourceFiles: any = [];
    // 有文件更新
    if (fromData.files?.length > 0) {
      for (let index = 0; index < fromData.files.length; index++) {
        const form = new FormData();
        if (fromData.remarks) {
          form.append('remarks', fromData.remarks);
        }
        if (fromData.fileType) {
          form.append('fileType', fromData.fileType);
        }
        // 选了新文件上传
        if (fromData.files[index]?.raw) {
          form.append('fileName ', fromData.files[index].name);
          form.append('file ', fromData.files[index].raw);
        }
        if (isEditDialog.value) {
          if (fromData.files[index]?.raw) {
            sourceFiles.push({
              fileName: fromData.files[index]?.raw.name,
              size: fromData.files[index]?.raw.size,
              raw: fromData.files[index]?.raw,
              fileType: fromData.fileType,
            });
          } else {
            if (fromData.id) {
              form.append('id', fromData.id);
            }
            await dataUpdateFileApi(form);
          }
        } else {
          if (fromData.files[index]?.raw) {
            sourceFiles.push({
              fileName: fromData.files[index]?.raw.name,
              size: fromData.files[index]?.raw.size,
              raw: fromData.files[index]?.raw,
              fileType: fromData.fileType,
            });
          } else {
            form.append('nodeId ', String(props.projectId));
            form.append('projectId ', String(props.projectId));
            form.append('uuid ', String(props.projectUuid));
            form.append('projectName ', props.projectName);
            await upload(`${PREFIX}node/uploadProjectFiles`, form);
          }
        }
      }
      if (sourceFiles.length > 0) {
        const params = {
          sourceFiles,
          uploadTaskId: new Date().getTime(),
          projectId: props.projectUuid,
          uuid: props.projectUuid,
          type: 0,
          remarks: fromData.remarks,
        };
        batchAddFileInfoApi(params).then((res: any) => {
          if (res.code === 200) {
            res.data.forEach((item: any, index: number) => {
              emitter.emit('ADD_UPLOAD_FILE', {
                file: fromData.files[index]?.raw,
                data: {
                  ...item,
                  isApprove: 0,
                  taskType: 5,
                  callbackFlag: '/project/projectList',
                },
              });
            });
          }
        });
      }
      if (isEditDialog.value) {
        const oldFileInfo = fromData.files.find((item: any) => item?.id === oldFile.value.id);
        if (!oldFileInfo) {
          dataDelFileApi({ delFileId: oldFile.value.id });
        }
      }
    } else {
      // 无文件更新
      const form = new FormData();
      if (fromData.remarks) {
        form.append('remarks', fromData.remarks);
      }
      if (fromData.fileType) {
        form.append('fileType', fromData.fileType);
      }
      if (isEditDialog.value) {
        if (fromData.id) {
          form.append('id', fromData.id);
        }
        await dataUpdateFileApi(form);
      } else {
        form.append('nodeId ', String(props.projectId));
        form.append('projectId ', String(props.projectId));
        form.append('uuid ', String(props.projectUuid));
        form.append('projectName ', props.projectName);
        await upload(`${PREFIX}node/uploadProjectFiles`, form);
      }
    }
    tableRef.value.resetFun();
    dialogVisible.value = false;
  }
};
const deleteFileFun = async (id: number) => {
  const res: any = await dataDelFileApi({ delFileId: id });
  if (res.code === 200) {
    ElMessage.success('删除成功');
    tableRef.value.resetFun();
  }
};
const downloadFile = (id: any) => {
  downloadFileById(id);
};

const uploadFinishedFun = (data: any) => {
  if (data.callbackFlag === '/project/projectList') {
    tableRef.value.resetFun();
  }
};

onMounted(() => {
  emitter.on('UPLOAD_FINISHED', uploadFinishedFun);
});

onBeforeUnmount(() => {
  emitter.off('UPLOAD_FINISHED', uploadFinishedFun);
});
</script>

<style lang="scss" scoped>
.project-file {
  height: 100%;
}
</style>
