<!-- 关键结果 -->

<template>
  <div class="result-page">
    <div class="tab-title-box">
      <el-radio-group v-model="currentDirName" @change="runResultDirChangeFun">
        <el-radio v-for="item in runDirNameList" :key="item.id" :value="item.id">{{ item.name }}</el-radio>
      </el-radio-group>
    </div>
    <div class="dir-content" v-if="runDirNameList.length && currentDirName">
      <BaseTable
        showIndex
        ref="baseTableRef"
        :tableName="tableName"
        :api="queryDirDataFun"
        :params="{
          keyResultType,
          runId:runInfo.uuid
        }"
        :action-list="actionList"
      >
        <template #leftOptions>
          <el-button @click="openFun">上传文件</el-button>
          <!-- <el-upload :show-file-list="false" :before-upload="beforeUploadFun">
            <el-button>上传文件</el-button>
          </el-upload> -->
        </template>
      </BaseTable>
    </div>
  </div>
  <el-drawer v-model="visible" :title="`文件上传`" :size="500" :close-on-click-modal="false" @close="closeFun">
    <TableForm ref="tableFormRef" :tableName="tableName" />
    <template #footer>
      <div>
        <el-button @click="closeFun">关闭</el-button>
        <el-button type="primary" @click="submitFun">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { queryRunDirApi, listSimulationKeyResultApi, addSimulationKeyResultApi, deleteSimulationKeyResultApi } from '@/api/project/run';
import { ref, defineProps, watch, nextTick, onMounted } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import { ElMessage } from 'element-plus';
import { UPLOAD_RUN_FILE_TYPE } from '@/utils/enum/file';
import TableForm from '@/components/common/table/tableForm.vue';

const env = import.meta.env;

const props = defineProps({
  currentRunIfno: {
    type: Object,
    default: () => {

    },
  },
});

const baseTableRef = ref();
const tableFormRef = ref();
const visible = ref(false);
const runInfo = ref<any>({});
const currentDirName = ref<any>();

const runDirs = ref<any>([]);
const runDirNameList = ref<any>([]);
const showPage = ref(false);

const getRunInfoDirsFun = async () => {
  showPage.value = false;
  const res: any = await queryRunDirApi({
    uuid: runInfo.value.uuid,
    size: 10,
    current: 1,
  });
  if (res && res.code === 200) {

    runDirs.value = res.data?.data.filter((item:any) => {
      return item.dataType === 1 && ['图片结果', '曲线结果', '报告结果'].includes(item.originalName);
    }) || [];
    runDirNameList.value = runDirs.value.map((item: any) => {
      return { name: item.originalName, id: item.id };
    }) || [];

    console.log(runDirNameList.value, 'runDirNameList.value');
    console.log(runDirs.value, 'runDirs.value');

    if (runDirNameList.value.length) {
      currentDirName.value = runDirNameList.value[0].id;
    }
  }
  showPage.value = true;
};

const queryDirDataFun = async (param: any) => {
  const res: any = await listSimulationKeyResultApi({
    ...param,
  });
  if (res && res.code === 200) {

    return res;
  }
};

const keyResultType = ref('1');
const reloadFun = () => {
  if (baseTableRef.value) {
    baseTableRef.value.resetFun();
  }
};
const tableName = ref('RUN_RESULT_IMAGE_TABLE');

const runResultDirChangeFun = () => {

  const name = runDirNameList.value.find((item:any) => {
    return item.id === currentDirName.value;
  })?.name;

  if (name === '图片结果') {
    tableName.value = 'RUN_RESULT_IMAGE_TABLE';
    keyResultType.value = '1';
  }
  if (name === '曲线结果') {
    tableName.value = 'RUN_RESULT_CANVAS_TABLE';
    keyResultType.value = '2';

  }
  if (name === '报告结果') {
    tableName.value = 'RUN_RESULT_REPORT_TABLE';
    keyResultType.value = '3';

  }
};

watch(() => props.currentRunIfno, async (newVal) => {

  if (newVal) {
    runInfo.value = newVal;

    nextTick(async () => {
      await getRunInfoDirsFun();
    });
  }

}, {
  immediate: true,
  deep: true,
});

const getFileType = () => {

  let type:any = UPLOAD_RUN_FILE_TYPE.CALCULATION_FILE;
  const dirName = runDirNameList.value.find((item:any) => {
    return item.id === currentDirName.value;
  })?.name;

  if (dirName === '图片结果') {
    type = UPLOAD_RUN_FILE_TYPE.PNG_FILE;
  }

  if (dirName === '曲线结果') {
    type = UPLOAD_RUN_FILE_TYPE.CANVAS_FILE;
  }

  if (dirName === '报告结果') {
    type = UPLOAD_RUN_FILE_TYPE.REPORT_FILE;
  }

  return type;

};

const closeFun = () => {
  visible.value = false;
};

const openFun = () => {
  visible.value = true;
  nextTick(() => {

    tableFormRef.value.resetFun();

  });
};

const submitFun = async () => {
  const valid = await tableFormRef.value.validateFun();
  if (valid) {
    const fromData = tableFormRef.value.getFormDataFun();
    const file = fromData.uploadFile[0].raw;
    const name = file.name;
    const paramData:any = {};

    for (const key in fromData) {
      if (key != 'extras' && key != 'uploadFile') {
        paramData[key] = fromData[key];
      }
    }

    const params = {
      fileName: name,
      name: name,
      dirId: currentDirName.value,
      file: file,
      fileType: getFileType(),
      keyResultType: keyResultType.value,
      runId: runInfo.value.uuid,
      ...paramData,
    };

    await addSimulationKeyResultApi(params).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success('上传成功');
        reloadFun();
      }
    });
    visible.value = false;

    console.log(fromData, 'fromData');

  }

};

const deleteFile = async (data:any) => {
  const res:any = await deleteSimulationKeyResultApi({
    uuid: data.uuid,
    fileId: data.fileId,
  });
  if (res && res.code === 200) {
    ElMessage.success('删除成功');
  } else {
    ElMessage.error('删除失败');

  }
};

const actionList = ref([
  {
    title: '下载',
    type: 'primary',
    click: (row:any) => {

      const downloadUrl = `${env.VITE_API_FILE_URL}/data/downloadFile?fileId=${row.fileId}`;
      window.open(downloadUrl, '_blank');
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确认删除吗？',
    click: (row:any) => {
      deleteFile(row);
    },
  },
]);

onMounted(() => {

});

</script>

<style lang="scss" scoped>
.result-page {
    width: 100%;
    height: 100%;

    .tab-title-box {
        width: 100%;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
    }
}
</style>
