<template>
  <div class="task-performance-page">
    <div class="task-img-box">
      <DragUploader :disabled="!canUpdate" @beforeUpload="beforeUploadFun">
        <BaseTable
          tableName="TASK_IMAGE_FILE"
          ref="baseTableRef"
          v-model:viewType="viewType"
          :api="getSimulationTaskFilesApi"
          :params="apiParam"
          :show-checkbox="showCheckbox"
          :actionList="actionList"
          :full-height="true"
        >
          <template v-if="showLeftOptions" #leftOptions>
            <el-form v-if="viewType === 'card'" inline class="column-form">
              <el-form-item label="列数：">
                <el-input-number v-model="columnCount" :min="1" :max="20" :step="1" />
              </el-form-item>
            </el-form>
            <AddFile
              ref="AddFileRef"
              :accept="accept"
              :api="batchAddFileInfoForTaskApi"
              :fileType="FILE_TYPE.PNG_FILE"
              tableName="TASK_DETAIL_UPLOAD_FILE"
              callbackFlag="RESULT_IMAGE_UPLOAD_FINISHED"
              :discipline="taskData?.discipline"
              multiple
              :data="{
                dirId: nodeFIleId,
                projectId: null,
                uuid: taskId,
              }"
              @finished="uploadFinishedFun"
            >
              <el-button v-if="canUpdate">上传文件</el-button>
            </AddFile>
            <el-button type="primary" class="ml12" @click="downLoadFun">下载文件</el-button>
          </template>

          <template #cardTemplate="{ tableData }">
            <ImageCard
              ref="imageCardRef"
              :list="tableData"
              :columnCount="columnCount"
              :showDelete="showLeftOptions && canUpdate"
              @download="downloadFileFun"
              @preview="previewFileFun"
              @delete="deleteFun"
            />
          </template>

          <template #type="{ row }">
            <span>{{ getfileType(row) }}</span>
          </template>
          <template #fileSize="{ row }">
            <span>{{ row.formatFileSize }}</span>
          </template>
        </BaseTable>
      </DragUploader>
    </div>

    <FilePreview v-model="previewVisible" :fileId="currentRow?.id" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { batchAddFileInfoForTaskApi } from '@/api/project/run';
import { queryTaskRunApi } from '@/api/project/run';
import { NODE_TYPE } from '@/utils/enum/node';
import { FILE_TYPE } from '@/utils/enum/file';
import {
  downloadFileById,
  downloadFileByStream,
  getFileUploadAcceptFun,
  queryFileIdByNodeIdFun,
} from '@/utils/file';
import BaseTable from '@/components/common/table/baseTable.vue';
import FilePreview from '@/components/common/filePreview/index.vue';
import AddFile from '@/components/common/addFile/index.vue';
import ImageCard from './imageCard.vue';
import { dataOverViewDeleteSimulationNodeFilesApi } from '@/api/data/dataOverView';
import { getSimulationTaskFilesApi } from '@/api/data/dataAnalysis';
import DragUploader from '@/components/common/dragUploader/index.vue';

const props = defineProps({
  taskId: {
    type: String,
    default: '',
  },
  showLeftOptions: {
    type: Boolean,
    default: true,
  },
  taskData: {
    type: Object,
    default: () => ({}),
  },
  // 是否可以更新
  canUpdate: {
    type: Boolean,
    default: true,
  },
  showCheckbox: {
    type: Boolean,
    default: true,
  },
});

const baseTableRef = ref();
const imageCardRef = ref();

const viewType = ref('card');
const columnCount = ref(4);

const exampleList = ref<any>([]);
const nodeFIleId = ref<any>('');
const accept = ref<any>('');

const queryTaskRunFun = async (id: any) => {
  const res: any = await queryTaskRunApi({ taskId: id });
  if (res && res.code === 200) {
    const list = res.data.map((item: any) => {
      return {
        ...item,
        name: item.runName,
        type: NODE_TYPE.RUN,
      };
    });
    return list;
  } else {
    return [];
  }
};

const currentRow = ref();
const previewVisible = ref(false);
const previewFileFun = (row: any) => {
  currentRow.value = row;
  previewVisible.value = true;
};

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

const actionList = ref([
  {
    title: '下载',
    type: 'primary',
    click: (row: any) => {
      downloadFileFun(row);
    },
  },
  {
    title: '预览',
    type: 'primary',
    click: (row: any) => {
      previewFileFun(row);
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '删除后不可恢复，确认删除吗？',
    click: (row: any) => {
      deleteFun(row);
    },
    hide: () => {
      return !props.showLeftOptions || !props.canUpdate;
    },
  },
]);

const deleteFun = async (row: any) => {
  const param = {
    deleteId: row.id,
    dataType: 2,
  };

  try {
    const res: any = await dataOverViewDeleteSimulationNodeFilesApi(param);
    if (res && res.code === 200) {
      baseTableRef.value.resetFun();
    }
  } catch {}
};

const getfileType = (data: any) => {
  const fileType = data.originalName.split('.').pop();
  return fileType;
};

const apiParam = ref<any>({});

watch(
  () => props.taskId,
  async (newVal) => {
    const task = [
      {
        name: '当前任务',
        id: newVal,
        uuid: newVal,
        type: NODE_TYPE.TASK,
      },
    ];
    apiParam.value = {
      uuid: newVal,
      fileBizType: FILE_TYPE.PNG_FILE,
      fileName: '',
      startTime: '',
      endTime: '',
      level: NODE_TYPE.TASK,
    };
    const runList = await queryTaskRunFun(newVal);
    exampleList.value = task.concat(runList);
  },
  {
    immediate: true,
  }
);

const uploadFinishedFun = (data: any) => {
  if (data.callbackFlag === 'RESULT_IMAGE_UPLOAD_FINISHED') {
    baseTableRef.value.resetFun();
    if (imageCardRef.value) {
      imageCardRef.value.reloadFailedImages();
    }
  }
};

const downLoadFun = async () => {
  if (viewType.value === 'card' && imageCardRef.value) {
    const selectedIds = imageCardRef.value.getSelectedIds() || [];
    if (selectedIds.length) {
      for (let i = 0; i < selectedIds.length; i++) {
        downloadFileByStream(selectedIds[i]);
      }
    }
    return;
  }
  const data: any = baseTableRef.value.tableRef.getCheckboxRecords() || [];
  if (data.length) {
    for (let i = 0; i < data.length; i++) {
      downloadFileByStream(data[i].id);
    }
  }
};
const AddFileRef = ref<any>();
const beforeUploadFun = (file: any) => {
  AddFileRef.value.addFileFun(file);
};
onMounted(async () => {
  accept.value = await getFileUploadAcceptFun('PNG_FILE_FORMAT');
  nodeFIleId.value = await queryFileIdByNodeIdFun(props.taskId);
});
</script>

<style lang="scss" scoped>
.task-performance-page {
  width: 100%;
  height: 100%;
  // height: 450px;

  .task-img-box {
    width: 100%;
    height: 100%;

    .img-item {
      margin-right: 10px;
      margin-bottom: 10px;
      min-height: 100px;

      .task-img {
        width: 100%;
        border: 1px solid #ddd;
        cursor: pointer;
      }

      .check {
        border: 1px solid var(--el-color-primary);
      }
    }
  }
}

.ml12 {
  margin-left: 12px;
}

.column-form {
  .el-form-item {
    margin-bottom: 0;
    margin-right: 12px;
  }
}
</style>
