<template>
  <BaseTable
    showIndex
    tableName="NODE_DETAIL_FILE"
    ref="tableRef"
    :params="{uuid:projectUuid,queryTarget:2}"
    :api="dataQueryDirApi"
    :actionsWidth="200"
  >
    <template #leftOptions>
      <el-button
        icon="plus"
        @click="openDialog('add')"
        type="primary"
      >
        上传
      </el-button>
    </template>
    <template #fileType="{ row }">
      {{ PROJECT_FILE_TYPE.O[row.fileType] }}
    </template>
    <template #fileSize="{ row }">
      {{ formatFileSize(row.fileSize) }}
    </template>
    <template #tableActions="{ row }">
      <div class="gl-table-actions">
        <el-link type="primary" @click="openTabReviewFile(row.id)">预览</el-link>
        <el-link type="primary" @click="downloadFile(row.id)">下载</el-link>
        <el-link type="primary" @click="openDialog('edit',row)">编辑</el-link>
        <el-popconfirm title="确认删除？" @confirm="deleteFileFun(row.id)">
          <template #reference>
            <el-link type="danger">删除</el-link>
          </template>
        </el-popconfirm>
      </div>
    </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" />
    </div>
    <template #footer>
      <div>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmUploadFun">确定</el-button>
      </div>
    </template>
  </Dialog>

</template>
<script lang='ts' setup>
import BaseTable from '@/components/common/table/baseTable.vue';
import Dialog from '@/components/common/dialog/index.vue';
import { nextTick, onMounted, ref } from 'vue';
import { dataDelFileApi, dataQueryDirApi, dataUpdateFileApi } from '@/api/data/data';
import TableForm from '@/components/common/table/tableForm.vue';
import { upload } from '@/api/request';
import { useDict } from '@/utils/useDict';
import { formatFileSize, openTabReviewFile } from '@/utils/file';
import { ElMessage } from 'element-plus';

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

const { PROJECT_FILE_TYPE } = useDict('PROJECT_FILE_TYPE');

const props = defineProps<{
  projectId: number;
  projectName: string;
  projectUuid: string;
}>();
// NODE_DETAIL_FILE
// const headData = ref<any[]>([
//   { title: '序号', key: 'index', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 100 },
//   { title: '文件名', key: 'fileName', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 300 },
//   { title: '文件描述', key: 'description', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 200 },
//   { title: '文件类型', key: 'fileType', isShow: true, inputMode: 'select', type: 1, inForm: false, required: true, width: 120 },
//   { title: '文件大小', key: 'fileSize', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 120 },
//   { title: '创建人', key: 'creator', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 150 },
//   { title: '修改时间', key: 'updateTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true, width: 180 },
// ]);

const isEditDialog = ref(false);

const dialogVisible = ref(false);

const openDialog = (type: string, row?:any) => {
  isEditDialog.value = type === 'edit';
  dialogVisible.value = true;
  nextTick(() => {
    if (type === 'edit' && row) {
      row.fileType = String(row.fileType);
      row.files = [{ name: row.originalName }];
      tableFormRef.value.setFormDataFun(row);
    } else if (type === 'add') {
      tableFormRef.value.resetFun();
    }
  });
};
const tableFormRef = ref();
const tableRef = ref();

const confirmUploadFun = async() => {
  const valid = tableFormRef.value.validateFun();
  if (valid) {
    const fromData = tableFormRef.value.getFormDataFun();

    // 有文件更新
    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) {
          console.log('编辑文件', fromData);
          if (fromData.id) {
            form.append('id', fromData.id);
          }
          await dataUpdateFileApi(form);
        } else {
          console.log('上传文件', fromData);
          form.append('nodeId ', String(props.projectId));
          form.append('projectId ', String(props.projectId));
          form.append('uuid ', String(props.projectUuid));
          form.append('projectName ', props.projectName);
          // form.append('fileName ', fromData.files[0].name);
          // form.append('file ', fromData.files[0].raw);
          await upload(`${PREFIX}node/uploadProjectFiles`, form);
        }
      }
    } else {// 无文件更新
      const form = new FormData();
      if (fromData.remarks) {
        form.append('remarks', fromData.remarks );
      }
      if (fromData.fileType) {
        form.append('fileType', fromData.fileType);
      }
      if (isEditDialog.value) {
        console.log('编辑文件', fromData);
        if (fromData.id) {
          form.append('id', fromData.id);
        }
        await dataUpdateFileApi(form);
      } else {
        console.log('上传文件', fromData);
        form.append('nodeId ', String(props.projectId));
        form.append('projectId ', String(props.projectId));
        form.append('uuid ', String(props.projectUuid));
        form.append('projectName ', props.projectName);
        // form.append('fileName ', fromData.files[0].name);
        // form.append('file ', fromData.files[0].raw);
        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:string) => {
  const downloadUrl = `${env.VITE_API_FILE_URL}/data/downloadFile?fileId=${id}`;
  window.open(downloadUrl, '_blank');
};
// const fileSearchFun = async(params:any) => {
//   const res:any = await fileSearchApi({
//     'searchType': '1',
//     // 'searchDirLen': 0,
//     // 'conditionLen': 0,
//     // 'searchDir': 'string',
//     // 'searchCondition': 'string',
//     // 'len': 0,
//     'currentPage': 0,
//     'pageSize': 10,
//     'parentDirId': props.nodeLevel2Id,
//     // 'fileName': 'string',
//     'createrId': 'string',
//   });
//   // 处理返回的数据
//   if (res && res.code === 200) {
//     // 例如：更新表格数据
//     // tableData.value = res.data.list;
//     console.log('文件搜索结果', res.data.list);
//   }
// };

onMounted(() => {
});

</script>
<style lang="scss" scoped>
</style>
