<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" row-key="id" :request-api="listAlgorithmTaskTrackApi">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" v-auth="['demo:algorithmTaskTrack:add']" icon="CirclePlus" @click="dialogVisibleAddTask = true"> 新增 </el-button>
        <!--        <el-button type="primary" v-auth="['demo:algorithmTaskTrack:import']" icon="Upload" plain @click="batchAdd"> 导入-->
        <!--        </el-button>-->
        <!--        <el-button type="primary" v-auth="['demo:algorithmTaskTrack:export']" icon="Download" plain @click="downloadFile"> 导出-->
        <!--        </el-button>-->
        <el-button
          type="danger"
          v-auth="['demo:algorithmTaskTrack:remove']"
          icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link icon="View" v-auth="['demo:algorithmTaskTrack:query']" @click="openViewDialog(scope.row)"> 查看 </el-button>
        <!--        <el-button-->
        <!--          type="primary"-->
        <!--          link-->
        <!--          icon="EditPen"-->
        <!--          v-auth="['demo:algorithmTaskTrack:edit']"-->
        <!--          @click="openDialog(2, '可辨识性分析总任务编辑', scope.row)"-->
        <!--        >-->
        <!--          编辑-->
        <!--        </el-button>-->
        <el-button type="primary" link icon="Delete" v-auth="['demo:algorithmTaskTrack:remove']" @click="deleteAlgorithmTaskTrack(scope.row)">
          删除
        </el-button>
      </template>
    </ProTable>
    <FormDialog ref="formDialogRef" />
    <ImportExcel ref="dialogRef" />
    <el-dialog v-model="dialogVisibleAddTask" title="可辨识性分析总任务新增" width="700" @open="handleOpenAddTask()" :before-close="handleClose">
      <el-form ref="formAddTaskRef" :model="formAddTask" :rules="rulesAddTask" label-width="auto" style="max-width: 600px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="formAddTask.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="是否转红外" prop="ifToInfrared">
          <el-checkbox v-model="formAddTask.ifToInfrared" @click="setIfToInfrared()" />
        </el-form-item>
        <el-form-item label="选择转红外算法" v-show="formAddTask.ifToInfrared" prop="toInfraredAlgorithmId">
          <div class="form-item1">
            <el-select v-model="formAddTask.toInfraredAlgorithmId" placeholder="请选择转红外算法" clearable>
              <el-option v-for="item in enumsAlgorithmConfigTrack_toInfrared" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button
              @click="setAlgorithmParams(formAddTask.toInfraredAlgorithmId, 'toInfraredAlgorithmParams')"
              style="margin-left: 10px"
              :disabled="formAddTask.toInfraredAlgorithmId == undefined || formAddTask.toInfraredAlgorithmId == ''"
            >
              <SvgIcon :name="'Setting'" style="margin-right: 5px" />
              设置算法参数
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="选择可见光转红外模型" v-show="formAddTask.ifToInfrared" prop="toInfraredModelId">
          <el-select v-model="formAddTask.toInfraredModelId" placeholder="请选择可见光转红外模型" clearable>
            <el-option v-for="item in toInfraredModelList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择数据集" prop="inputDatasetOssId">
          <el-select v-model="formAddTask.inputDatasetOssId" placeholder="请选择数据集" clearable>
            <el-option v-for="item in datasetList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传数据集" prop="inputDatasetOssId">
          <File ref="fileUploadRef" :file-type="['zip']" :file-size="4096" @update:model-value="fileUploadDatasetChange" />
        </el-form-item>
        <el-form-item label="选择视觉算法" prop="trackSequenceAlgorithmId">
          <div class="form-item1">
            <el-select v-model="formAddTask.trackSequenceAlgorithmId" placeholder="请选择视觉算法" clearable>
              <el-option v-for="item in visionAlgorithmList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button
              @click="setAlgorithmParams(formAddTask.trackSequenceAlgorithmId, 'trackSequenceAlgorithmParams')"
              style="margin-left: 10px"
              :disabled="formAddTask.trackSequenceAlgorithmId == undefined || formAddTask.trackSequenceAlgorithmId == ''"
            >
              <SvgIcon :name="'Setting'" style="margin-right: 5px" />
              设置算法参数
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="选择目标检测模型" prop="TD_modelId">
          <el-select v-model="formAddTask.TD_modelId" placeholder="请选择目标检测模型" clearable>
            <el-option v-for="item in targetDetectionModelList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择视觉算法模型" prop="trackSequenceModelId">
          <el-select v-model="formAddTask.trackSequenceModelId" placeholder="请选择视觉算法模型" clearable>
            <el-option v-for="item in visionAlgorithmModelList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否评估" prop="ifEvaluate">
          <el-checkbox v-model="formAddTask.ifEvaluate" />
        </el-form-item>
        <el-form-item label="上传真实标签" prop="inputEvaluateLabelOssId" v-show="formAddTask.ifEvaluate">
          <File ref="fileUploadEvaluateLabelRef" :file-type="['txt']" :file-size="4096" @update:model-value="fileUploadChangeEvaluateLabel" />
        </el-form-item>
        <el-form-item label="选择视觉评估算法" prop="trackSequenceEvaluateAlgorithmId" v-show="formAddTask.ifEvaluate">
          <div class="form-item1">
            <el-select v-model="formAddTask.trackSequenceEvaluateAlgorithmId" placeholder="请选择视觉评估算法" clearable>
              <el-option v-for="item in visionEvaluateAlgorithmList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button
              @click="setAlgorithmParams(formAddTask.trackSequenceEvaluateAlgorithmId, 'trackSequenceEvaluateAlgorithmParams')"
              style="margin-left: 10px"
              :disabled="formAddTask.trackSequenceEvaluateAlgorithmId == undefined || formAddTask.trackSequenceEvaluateAlgorithmId == ''"
            >
              <SvgIcon :name="'Setting'" style="margin-right: 5px" />
              设置算法参数
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="formAddTask.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisibleAddTask = false">取消</el-button>
        <el-button type="primary" @click="addAlgorithmTaskTrack"> 确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisibleView" @open="handleOpenView()" title="可辨识性分析总任务查看" width="90%">
      <div style="width: 100%; height: auto; overflow: auto">
        <el-table :data="viewData" border height="500px">
          <el-table-column prop="id" label="主键ID" width="180" />
          <el-table-column prop="name" label="任务名称" width="150">
            <template #default="scope">
              <el-tooltip :content="scope.row.name" raw-content placement="top-start" v-if="scope.row.name">
                <span>{{ scope.row.name && scope.row.name.length > 15 ? scope.row.name.substring(0, 15) + '...' : scope.row.name }} </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="任务状态" width="150">
            <template #default="scope">
              <el-tag type="success">
                {{ Status__[scope.row.status] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="120">
            <template #default="scope">
              <el-tag type="success">
                {{ AlgorithmType[scope.row.type] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="subsystem" label="分系统" width="200">
            <template #default="scope">
              <el-tag type="success">
                {{ SubSystem[scope.row.subsystem] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="algorithmName" label="算法名称" width="200" />
          <el-table-column prop="modelName" label="模型名称" width="200" />
          <el-table-column prop="algorithmParameters" label="算法参数" width="150">
            <template #default="scope">
              <el-tooltip :content="scope.row.algorithmParameters" raw-content placement="top-start" v-if="scope.row.algorithmParameters">
                <span
                  >{{
                    scope.row.outputPath && scope.row.algorithmParameters.length > 15
                      ? scope.row.algorithmParameters.substring(0, 15) + '...'
                      : scope.row.algorithmParameters
                  }}
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="180" />
          <el-table-column prop="endTime" label="结束时间" width="180" />
          <el-table-column prop="costSecond" label="耗时" width="120" />
          <el-table-column prop="log" label="日志" width="120">
            <template #default="scope">
              <el-tooltip :content="scope.row.log" raw-content placement="top-start" v-if="scope.row.log">
                <span>{{ scope.row.outputPath && scope.row.log.length > 15 ? scope.row.log.substring(0, 15) + '...' : scope.row.log }} </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="outputPath" label="输出路径" width="120">
            <template #default="scope">
              <el-tooltip :content="scope.row.outputPath" raw-content placement="top-start" v-if="scope.row.outputPath">
                <span
                  >{{
                    scope.row.outputPath && scope.row.outputPath.length > 15 ? scope.row.outputPath.substring(0, 15) + '...' : scope.row.outputPath
                  }}
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注" width="120" />
          <el-table-column prop="operation" label="操作" width="300" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                icon="View"
                v-if="scope.row.status == '0' || scope.row.status == '3' || scope.row.status == '4'"
                @click="startSubTask(scope.row)"
              >
                开始
              </el-button>
              <el-popconfirm title="确定终止此任务吗?" @confirm="stopSubTask(scope.row)" v-if="scope.row.status == '1'">
                <template #reference>
                  <el-button type="primary" link icon="Delete"> 终止</el-button>
                </template>
              </el-popconfirm>
              <el-button type="primary" link icon="View" @click="openLogSubTask(scope.row)" v-if="scope.row.status != '0'"> 日志 </el-button>
              <el-button
                type="primary"
                link
                icon="View"
                v-if="scope.row.status == '2' && scope.row.type == AlgorithmType2['预测/推理']"
                @click="previewSubTask(scope.row)"
              >
                预览
              </el-button>
              <el-button
                type="primary"
                link
                icon="View"
                v-if="scope.row.status == '2' && scope.row.type == AlgorithmType2['预测/推理']"
                @click="showStatisticResultSubTask(scope.row)"
              >
                结果
              </el-button>
              <el-button
                type="primary"
                link
                icon="View"
                v-if="scope.row.status == '2' && scope.row.type == AlgorithmType2['测试']"
                @click="showEvaluateResultSubTask(scope.row.id)"
              >
                结果
              </el-button>
              <el-button
                type="primary"
                link
                icon="View"
                v-if="scope.row.status == '2' && scope.row.type === AlgorithmType2['预测/推理']"
                @click="showEvaluateSubTask(scope.row)"
              >
                评估
              </el-button>
              <el-button type="primary" link icon="View" @click="openSubTaskViewDialog(3, '子任务查看', scope.row)"> 查看 </el-button>
              <el-button type="primary" link icon="EditPen" @click="openSubTaskViewDialog(2, '子任务编辑', scope.row)"> 编辑 </el-button>
              <el-button type="danger" link icon="Delete" @click="deletSubTaskAlgorithmTaskTrack(scope.row)"> 删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="AlgorithmTaskTrack">
import { ref, reactive } from 'vue'
import { useHandleData } from '@/hooks/useHandleData'
import { useDownload } from '@/hooks/useDownload'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProTable from '@/components/ProTable/index.vue'
import ImportExcel from '@/components/ImportExcel/index.vue'
import FormDialog from '@/components/FormDialog/index.vue'
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
import {
  listAlgorithmTaskTrackApi,
  delAlgorithmTaskTrackApi,
  addAlgorithmTaskTrackApi,
  updateAlgorithmTaskTrackApi,
  importTemplateApi,
  importAlgorithmTaskTrackDataApi,
  exportAlgorithmTaskTrackApi,
  getAlgorithmTaskTrackApi,
  listSubTaskAlgorithmTaskTrackApi
} from '@/api/modules/demo/algorithmTaskTrack'
import { AlgorithmType, AlgorithmType2, enumsAlgorithmType, enumsSubSystem, Status__, SubSystem, SubSystem__ } from '@/views/demo/utils'
import { enumAlgorithmConfigTrackApi, getAlgorithmConfigTrackApi } from '@/api/modules/demo/AlgorithmConfigTrack'
import SvgIcon from '@/components/SvgIcon/index.vue'
import { listDataSeqApi } from '@/api/modules/demo/DataSeq'
import File from '@/components/Upload/File.vue'
import { enumAlgorithmModelTrackApi } from '@/api/modules/demo/AlgorithmModelTrack'
import statusEnums from '@/utils/status'
import {
  addTrackSequenceApi,
  delTrackSequenceApi,
  getTrackSequenceApi,
  startTrackSequenceApi,
  stopTrackSequenceApi,
  updateTrackSequenceApi
} from '@/api/modules/demo/trackSequence'
import { delToInfraredApi, getToInfraredApi, startToInfraredApi, stopToInfraredApi, updateToInfraredApi } from '@/api/modules/demo/toInfrared'
import { getTargetDetectionApi, startTargetDetectionApi, stopTargetDetectionApi, updateTargetDetectionApi } from '@/api/modules/demo/TargetDetection'
import { delDataAugmentationApi } from '@/api/modules/demo/dataAugmentation'

const startSubTask = async (row: any) => {
  let res: any = null
  if (row.subsystem === SubSystem__['可见光转红外']) {
    res = await startToInfraredApi(row.id)
  } else if (row.subsystem === SubSystem__['目标检测']) {
    res = await startTargetDetectionApi(row.id)
  } else if (row.subsystem === SubSystem__['注释轨迹序列']) {
    res = await startTrackSequenceApi(row.id)
  } else {
    ElMessage.error('暂不支持该子任务类型')
    return
  }
  if (res.code === 200) {
    ElMessage.success('任务已开始，请等待完成！')
  } else {
    ElMessage.error('任务开始失败，请检查！')
  }
  handleOpenView()
}
const stopSubTask = async (row: any) => {
  let res: any = null
  if (row.subsystem === SubSystem__['可见光转红外']) {
    res = await stopToInfraredApi(row.id)
  } else if (row.subsystem === SubSystem__['目标检测']) {
    res = await stopTargetDetectionApi(row.id)
  } else if (row.subsystem === SubSystem__['注释轨迹序列']) {
    res = await stopTrackSequenceApi(row.id)
  } else {
    ElMessage.error('暂不支持该子任务类型')
    return
  }
  if (res.code === 200) {
    ElMessage.success('终止任务成功！')
  } else {
    ElMessage.error('终止任务失败，请检查！')
  }
  handleOpenView()
}
const openLogSubTask = async (row: any) => {}
const previewSubTask = async (row: any) => {}
const showStatisticResultSubTask = async (row: any) => {}
const showEvaluateResultSubTask = async (row: any) => {}
const showEvaluateSubTask = async (row: any) => {}

const deletSubTask = async (row: any) => {
  if (row.subsystem === SubSystem__['可见光转红外']) {
    await useHandleData(delToInfraredApi, row.id, '删除【' + row.name + '】可见光转红外')
  } else if (row.subsystem === SubSystem__['目标检测']) {
    await useHandleData(delDataAugmentationApi, row.id, '删除任务【' + row.name + '】目标检测')
  } else if (row.subsystem === SubSystem__['注释轨迹序列']) {
    await useHandleData(delTrackSequenceApi, row.id, '删除【' + row.name + '】注视轨迹序列')
  } else {
    ElMessage.error('暂不支持该子任务类型')
  }
  handleOpenView()
}

const loadSomeData = async (row?: any) => {
  datasetList.value = await getDatasetList()
  if (row.subsystem === SubSystem__['可见光转红外']) {
    enumsAlgorithmConfigTrack_toInfrared.value = await getEnumsAlgorithmConfigTrack('可见光转红外', ['预测/推理'])
    await getToInfraredModelList()
  } else if (row.subsystem === SubSystem__['目标检测']) {
  } else if (row.subsystem === SubSystem__['注释轨迹序列']) {
    enumsAlgorithmConfigTrack_trackSequence.value = await getEnumsAlgorithmConfigTrack('注释轨迹序列', [AlgorithmType[row.type]])
    enumsAlgorithmModelTrack.value = await getEnumsAlgorithmModelTrack('注释轨迹序列')
    enumsAlgorithmModelTrack_TD.value = await getEnumsAlgorithmModelTrack('目标检测')
  }
}

const openSubTaskViewDialog = async (type: number, title: string, row?: any) => {
  let res = { data: {} }
  let api: any = null
  if (row?.id) {
    console.log(row)
    if (row.subsystem === SubSystem__['可见光转红外']) {
      console.log('可见光转红外')
      res = await getToInfraredApi(row.id || null)
      api = updateToInfraredApi

      // 重置表单
      setItemsOptions_ToInfrared()
    } else if (row.subsystem === SubSystem__['目标检测']) {
      console.log('目标检测')
      res = await getTargetDetectionApi(row.id || null)
      api = updateTargetDetectionApi
    } else if (row.subsystem === SubSystem__['注释轨迹序列']) {
      console.log('注释轨迹序列')
      res = await getTrackSequenceApi(row.id || null)
      api = updateTrackSequenceApi

      // 重置表单
      setItemsOptions_TrackSequence()
    } else {
      console.log('其他')
      ElMessage.error('暂不支持该子任务类型')
      return
    }
    const params = JSON.parse(res.data['algorithmParameters'])
    if (params.otherParams) {
      res.data = { ...res.data, ...params.otherParams }
    }
  }

  if (row?.id) {
    itemsOptions = await updateItemsOptions(row.algorithmId)
  }
  await loadSomeData(row)
  const params = {
    title: title,
    width: 600,
    isEdit: type !== 3,
    itemsOptions: itemsOptions,
    model: res.data,
    api: api,
    getTableList: handleOpenView
  }
  formDialogRef.value?.openDialog(params)
}

const remove_unnecessary_parameters = (itemsOptions: ProForm.ItemsOptions[]): ProForm.ItemsOptions[] => {
  try {
    const endIndex = itemsOptions.findIndex(option => option['label'] === '备注')
    if (endIndex !== -1) {
      itemsOptions = itemsOptions.slice(0, endIndex + 1)
    }
    return itemsOptions
  } catch (error) {
    console.error('移除不必要的参数时出错:', error)
    // ElMessage.error('移除不必要的参数时出错，请检查！');
    return itemsOptions // 返回原始选项，避免进一步的问题
  }
}

const updateItemsOptions = async (algorithmId: any) => {
  try {
    const result = await getAlgorithmConfigTrackApi(algorithmId)
    if (result.code === 200) {
      // 处理结果
      const parameters = JSON.parse(result.data['parameters'])
      // console.log('parameters: ', parameters)

      const itemsOptions_new = remove_unnecessary_parameters(itemsOptions)
      for (const item of parameters) {
        // 添加新的表单项选项
        itemsOptions_new.push({
          label: item['name'],
          prop: item['agName'],
          rules: [{ required: item['required'], message: item['agName'] + '不能为空', trigger: 'blur' }],
          tooltip: item['prompt'],
          compOptions: {
            elTagName: 'input',
            placeholder: item['defaultValue']
            // value: item['defaultValue']
          }
        })
      }
      formDialogRef.value?.updateItemOptions(itemsOptions_new)
      return itemsOptions_new
    } else {
      return itemsOptions // 返回原始选项，避免进一步的问题
    }
  } catch (err) {
    console.log(err)
    ElMessage.error('获取算法配置失败，请检查！')
    return itemsOptions // 返回原始选项，避免进一步的问题
  }
}

const setItemsOptions_ToInfrared = () => {
  itemsOptions = [
    {
      label: '任务名称',
      prop: 'name',
      rules: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'input',
        placeholder: '请输入任务名称'
      }
    },
    {
      label: '选择数据集',
      prop: 'inputOssId',
      rules: [{ required: false, message: '数据集不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'select',
        placeholder: '请选择或者上传数据集',
        enum: datasetList,
        clearable: true
      }
    },
    {
      label: '上传数据集',
      prop: 'inputOssId',
      rules: [{ required: false, message: '数据集不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'file-upload',
        fileSize: 4096,
        fileType: ['zip'],
        placeholder: '请上传数据集'
      }
    },
    {
      label: '选择算法',
      prop: 'algorithmId',
      rules: [{ required: true, message: '算法不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'select',
        placeholder: '请选择算法',
        enum: enumsAlgorithmConfigTrack_toInfrared,
        clearable: true,
        onChange: async (value: any) => {
          if (value != undefined && value != null && value != '') {
            await updateItemsOptions(value)
          }
        }
      }
    },
    {
      label: '任务类型',
      prop: 'type',
      rules: [{ required: true, message: '任务类型不能为空', trigger: 'blur' }],
      compOptions: {
        disabled: true,
        elTagName: 'select',
        placeholder: '请选择任务类型',
        enum: enumsAlgorithmType,
        clearable: true,
        value: ''
      },
      show: params => {
        if (params.value.algorithmId != undefined) {
          for (let i = 0; i < enumsAlgorithmConfigTrack_toInfrared.value.length; i++) {
            if (enumsAlgorithmConfigTrack_toInfrared.value[i]['value'] === params.value.algorithmId) {
              params.value.type = enumsAlgorithmConfigTrack_toInfrared.value[i]['type']
              return true
            }
          }
        }
        return false
      }
    },
    {
      label: '选择模型',
      prop: 'algorithmModelId',
      rules: [{ required: true, message: '模型不能为空', trigger: 'blur' }],
      show: params => {
        if (params.value.type == AlgorithmType2['预测/推理']) {
          return true
        }
        return false
      },
      compOptions: {
        elTagName: 'select',
        placeholder: '请选择模型',
        enum: toInfraredModelList,
        clearable: true
      }
    },
    {
      label: '备注',
      prop: 'remarks',
      rules: [],
      compOptions: {
        elTagName: 'input',
        placeholder: '请输入备注'
      }
    }
  ]
}
const enumsAlgorithmConfigTrack_trackSequence = ref<any[]>([])
const enumsAlgorithmModelTrack = ref<any[]>([])
const enumsAlgorithmModelTrack_TD = ref<any[]>([])
const setItemsOptions_TrackSequence = () => {
  itemsOptions = [
    {
      label: '任务名称',
      prop: 'name',
      rules: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入任务名称'
      }
    },
    {
      label: '选择数据集',
      prop: 'inputOssId',
      rules: [{ required: false, message: '数据集不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'select',
        placeholder: '请选择或者上传数据集',
        enum: datasetList,
        clearable: true
      }
    },
    {
      label: '上传数据集',
      prop: 'inputOssId',
      rules: [{ required: false, message: '数据集不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'file-upload',
        fileSize: 4096,
        fileType: ['zip'],
        placeholder: '请上传数据集'
      }
    },
    {
      label: '选择算法',
      prop: 'algorithmId',
      rules: [{ required: true, message: '算法不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'select',
        placeholder: '请选择算法',
        enum: enumsAlgorithmConfigTrack_trackSequence,
        clearable: true,
        onChange: async (value: any) => {
          if (value != undefined && value != null && value != '') {
            await updateItemsOptions(value)
          }
        }
      }
    },
    {
      label: '任务类型',
      prop: 'type',
      rules: [{ required: true, message: '任务类型不能为空', trigger: 'blur' }],
      compOptions: {
        disabled: true,
        elTagName: 'select',
        placeholder: '请选择任务类型',
        enum: enumsAlgorithmType,
        clearable: true,
        value: ''
      },
      show: params => {
        if (params.value.algorithmId != undefined) {
          for (let i = 0; i < enumsAlgorithmConfigTrack_trackSequence.value.length; i++) {
            if (enumsAlgorithmConfigTrack_trackSequence.value[i]['value'] === params.value.algorithmId) {
              params.value.type = enumsAlgorithmConfigTrack_trackSequence.value[i]['type']
              return true
            }
          }
        }
        return false
      }
    },
    {
      label: '选择模型',
      prop: 'algorithmModelId',
      rules: [{ required: true, message: '模型不能为空', trigger: 'blur' }],
      show: params => {
        if (params.value.type == AlgorithmType2['预测/推理']) {
          return true
        }
        params.value.algorithmModelId = ''
        return false
      },
      compOptions: {
        elTagName: 'select',
        placeholder: '请选择模型',
        enum: enumsAlgorithmModelTrack,
        clearable: true
      }
    },
    {
      label: '选择目标检测模型',
      prop: 'algorithmModelTargetDetectionId',
      rules: [{ required: false, message: '目标检测模型不能为空', trigger: 'blur' }],
      show: params => {
        if (params.value.type == AlgorithmType2['预测/推理']) {
          return true
        }
        params.value.algorithmModelTargetDetectionId = ''
        return false
      },
      compOptions: {
        elTagName: 'select',
        placeholder: '请选择目标检测模型',
        enum: enumsAlgorithmModelTrack_TD,
        clearable: true
      }
    },
    {
      label: '上传标签',
      prop: 'inputLabelOssId',
      rules: [{ required: true, message: '标签不能为空', trigger: 'blur' }],
      show: params => {
        if (params.value.type == AlgorithmType2['测试']) {
          return true
        }
        return false
      },
      compOptions: {
        elTagName: 'file-upload',
        fileSize: 4096,
        fileType: ['txt'],
        placeholder: '请上传标签'
      }
    },
    {
      label: '备注',
      prop: 'remarks',
      rules: [],
      compOptions: {
        placeholder: '请输入备注'
      }
    }
  ]
}

const dialogVisibleView = ref(false)
const viewData = ref<any[]>([])
const subTaskAlgorithmTaskTrack_id = ref<any>(null)
const openViewDialog = async (row: any) => {
  dialogVisibleView.value = true
  subTaskAlgorithmTaskTrack_id.value = row.id
}
const handleOpenView = async () => {
  const res = await listSubTaskAlgorithmTaskTrackApi(subTaskAlgorithmTaskTrack_id.value)
  if (res.code === 200) {
    viewData.value = res.data
  } else {
    ElMessage.error('获取子任务失败')
  }
}

const fileUploadRef = ref()
const fileUploadDatasetChange = (value: any) => {
  console.log('fileUploadChange: ', value)
  formAddTask.value['inputDatasetOssId'] = value
}
const fileUploadEvaluateLabelRef = ref()
const fileUploadChangeEvaluateLabel = (value: any) => {
  console.log('fileUploadChangeEvaluateLabel: ', value)
  formAddTask.value['inputEvaluateLabelOssId'] = value
}

const getEnumsAlgorithmModelTrack = async (subSystem: string) => {
  const result: any = await enumAlgorithmModelTrackApi()
  const res_list: any[] = []
  const tmp_data: any = result['data']
  for (const item of tmp_data) {
    if (SubSystem[item['subsystem']] === subSystem) {
      const tmp_item = { ...item }
      tmp_item['label'] = item['label'] + '-' + SubSystem[item['subsystem']] + '-' + AlgorithmType[item['type']] + '-' + item['algorithmName']
      res_list.push(tmp_item)
    }
  }
  return res_list
}

const getEnumsAlgorithmConfigTrack = async (subSystem: string, type_list_: string[]) => {
  const result = await enumAlgorithmConfigTrackApi()
  const res_list: any[] = []
  const tmp_data: any = result['data']

  const type_list: any[] = type_list_.map(item => parseInt(AlgorithmType2[item]))

  for (const item of tmp_data) {
    if (parseInt(item.subsystem) === parseInt(SubSystem__[subSystem])) {
      if (type_list !== undefined && type_list.length > 0) {
        if (type_list.includes(parseInt(item.type))) {
          const tmp_item = { ...item }
          tmp_item['label'] = item['label'] + '-' + SubSystem[item['subsystem']] + '-' + AlgorithmType[item['type']]
          res_list.push(tmp_item)
        }
      } else {
        const tmp_item = { ...item }
        tmp_item['label'] = item['label'] + '-' + SubSystem[item['subsystem']] + '-' + AlgorithmType[item['type']]
        res_list.push(tmp_item)
      }
    }
  }
  return res_list
}

const dialogVisibleAddTask = ref(false)
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定关闭吗？')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
const formAddTask = ref({ ifEvaluate: false, ifToInfrared: false })
const formAddTaskRef = ref()
const addAlgorithmTaskTrack = async () => {
  formAddTaskRef.value
    .validate()
    .then(async () => {
      console.log('formAddTask: ', formAddTask.value)
      console.log(fileUploadRef.value.uploadFileListExport)
      const res = await addAlgorithmTaskTrackApi(formAddTask.value)
      if (res.code === 200) {
        ElMessage.success('新增可辨识性分析总任务成功')
        dialogVisibleAddTask.value = false
        proTable.value?.getTableList()
      } else {
        ElMessage.error('新增可辨识性分析总任务失败')
      }
    })
    .catch(() => {
      console.log('error')
      ElMessage.error('请检查表单')
    })
}

const rulesAddTask = {
  // todo: 校验规则
  name: [{ required: true, message: '可见光转红外算法不能为空', trigger: 'blur' }],
  ifToInfrared: [{ required: false, message: '是否转红外不能为空', trigger: 'blur' }],
  toInfraredAlgorithmId: [{ required: false, message: '可见光转红外算法不能为空', trigger: 'blur' }],
  inputDatasetOssId: [{ required: true, message: '数据集不能为空', trigger: 'blur' }],
  targetDetectionModelList: [{ required: true, message: '目标模型不能为空', trigger: 'blur' }],
  inputEvaluateLabelOssId: [{ required: false, message: '评估标签不能为空', trigger: 'blur' }],
  remarks: [{ required: false, message: '备注不能为空', trigger: 'blur' }]
}

const enumsAlgorithmConfigTrack_toInfrared = ref<any[]>([])
const setIfToInfrared = async () => {
  formAddTask.value.toInfraredAlgorithmId = ''
  if (formAddTask.value?.ifToInfrared === true) {
    enumsAlgorithmConfigTrack_toInfrared.value = await getEnumsAlgorithmConfigTrack('可见光转红外', ['预测/推理'])
  }
}

const getItemsOptions = async (algorithmId: any) => {
  try {
    const result = await getAlgorithmConfigTrackApi(algorithmId)
    if (result.code === 200) {
      // 处理结果
      const parameters = JSON.parse(result.data['parameters'])
      // console.log('parameters: ', parameters)

      let itemsOptions_new: any[] = []
      for (const item of parameters) {
        // 添加新的表单项选项
        itemsOptions_new.push({
          label: item['name'],
          prop: item['agName'],
          rules: [{ required: item['required'], message: item['agName'] + '不能为空', trigger: 'blur' }],
          tooltip: item['prompt'],
          compOptions: {
            elTagName: 'input',
            placeholder: item['defaultValue']
            // value: item['defaultValue']
          }
        })
      }
      return itemsOptions_new
    }
  } catch (err) {
    console.log(err)
    ElMessage.error('获取算法配置失败，请检查！')
    return []
  }
}

const setAlgorithmParams = async (id: string | number, paramsName: string) => {
  const itemsOptions__ = await getItemsOptions(id)
  const params = {
    title: '设置算法参数',
    width: 580,
    isEdit: true,
    itemsOptions: itemsOptions__,
    model: formAddTask,
    api: async params => {
      console.log('itemsOptions__: ', itemsOptions__)
      let params_new = {}
      if (itemsOptions__ && itemsOptions__.length > 0) {
        for (const item of itemsOptions__) {
          params_new[item['prop']] = params[item['prop']]
        }
        formAddTask.value[paramsName] = params_new
        console.log('params: ', params)
        console.log('params_new: ', params_new)
        console.log('formAddTask: ', formAddTask.value)
      }
      return { code: 200, message: 'success' }
    },
    getTableList: proTable.value?.getTableList
  }
  formDialogRef.value?.openDialog(params)
}

const datasetList = ref<any[]>([])

const getDatasetList = async (subSystem: string) => {
  const qyery = {
    subsystem: subSystem ? SubSystem__[subSystem] : undefined,
    pageNum: 1,
    pageSize: 1000
  }
  const result: any = await listDataSeqApi(qyery)
  const data = result['data']['list']
  let res_list: any[] = []
  for (const item of data) {
    res_list.push({
      value: item['inputOssId'],
      label: item['name'] + '-' + SubSystem[item['subsystem']]
    })
  }
  return res_list
}

const getDatasetList__ = async () => {
  datasetList.value = await getDatasetList('')
}

const toInfraredModelList = ref<any[]>([])
const getToInfraredModelList = async () => {
  toInfraredModelList.value = await getEnumsAlgorithmModelTrack('可见光转红外')
}

const visionAlgorithmList = ref<any[]>([])
const getVisionAlgorithmList = async () => {
  visionAlgorithmList.value = await getEnumsAlgorithmConfigTrack('注释轨迹序列', ['预测/推理'])
}

const targetDetectionModelList = ref<any[]>([])
const getTargetDetectionModelList = async () => {
  targetDetectionModelList.value = await getEnumsAlgorithmModelTrack('目标检测')
}

const visionAlgorithmModelList = ref<any[]>([])
const getVisionAlgorithmModelList = async () => {
  visionAlgorithmModelList.value = await getEnumsAlgorithmModelTrack('注释轨迹序列')
}

const visionEvaluateAlgorithmList = ref<any[]>([])
const getVisionEvaluateAlgorithmList = async () => {
  visionEvaluateAlgorithmList.value = await getEnumsAlgorithmConfigTrack('注释轨迹序列', ['测试'])
}

const handleOpenAddTask = async () => {
  formAddTask.value = { ifEvaluate: false, ifToInfrared: false }
  await getDatasetList__()
  await getToInfraredModelList()
  await getVisionAlgorithmList()
  await getTargetDetectionModelList()
  await getVisionAlgorithmModelList()
  await getVisionEvaluateAlgorithmList()
}

// ProTable 实例
const proTable = ref<ProTableInstance>()

// 删除可辨识性分析总任务信息
const deleteAlgorithmTaskTrack = async (params: any) => {
  await useHandleData(delAlgorithmTaskTrackApi, params.id, '删除【' + params.id + '】可辨识性分析总任务')
  proTable.value?.getTableList()
}

// 批量删除可辨识性分析总任务信息
const batchDelete = async (ids: string[]) => {
  await useHandleData(delAlgorithmTaskTrackApi, ids, '删除所选可辨识性分析总任务信息')
  proTable.value?.clearSelection()
  proTable.value?.getTableList()
}

// 导出可辨识性分析总任务列表
const downloadFile = async () => {
  ElMessageBox.confirm('确认导出可辨识性分析总任务数据?', '温馨提示', { type: 'warning' }).then(() =>
    useDownload(exportAlgorithmTaskTrackApi, '可辨识性分析总任务列表', proTable.value?.searchParam)
  )
}

// 批量添加可辨识性分析总任务
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null)
const batchAdd = () => {
  const params = {
    title: '可辨识性分析总任务',
    tempApi: importTemplateApi,
    importApi: importAlgorithmTaskTrackDataApi,
    getTableList: proTable.value?.getTableList
  }
  dialogRef.value?.acceptParams(params)
}

const formDialogRef = ref<InstanceType<typeof FormDialog> | null>(null)
// 打开弹框的功能
const openDialog = async (type: number, title: string, row?: any) => {
  let res = { data: {} }
  if (row?.id) {
    res = await getAlgorithmTaskTrackApi(row?.id || null)
  }
  // 重置表单
  setItemsOptions()
  const params = {
    title,
    width: 580,
    isEdit: type !== 3,
    itemsOptions: itemsOptions,
    model: type == 1 ? {} : res.data,
    api: type == 1 ? addAlgorithmTaskTrackApi : updateAlgorithmTaskTrackApi,
    getTableList: proTable.value?.getTableList
  }
  formDialogRef.value?.openDialog(params)
}

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  { type: 'selection', fixed: 'left', width: 70 },
  { prop: 'id', label: '主键ID' },
  {
    prop: 'name',
    label: '任务名称',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'status',
    label: '任务状态',
    search: {
      el: 'select'
    },
    tag: true,
    enum: statusEnums,
    width: 150
  },
  {
    prop: 'startTime',
    label: '开始时间',
    search: {
      el: 'date-picker',
      props: { type: 'datetimerange', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
    },
    width: 120
  },
  {
    prop: 'endTime',
    label: '结束时间',
    search: {
      el: 'date-picker',
      props: { type: 'datetimerange', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
    },
    width: 120
  },
  {
    prop: 'costSecond',
    label: '耗时',
    search: {
      el: 'input'
    },
    width: 120
  },
  {
    prop: 'log',
    label: '日志',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'remarks',
    label: '备注',
    search: {
      el: 'input'
    }
  },
  // {
  //   prop: 'system',
  //   label: '系统',
  //   search: {
  //     el: 'input'
  //   },
  //   width: 120
  // },
  { prop: 'operation', label: '操作', width: 230, fixed: 'right' }
])
// 表单配置项
let itemsOptions: ProForm.ItemsOptions[] = []
const setItemsOptions = () => {
  itemsOptions = [
    {
      label: '任务名称',
      prop: 'name',
      rules: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入任务名称'
      }
    }
  ]
}
</script>

<style lang="scss" scoped>
.form-item1 {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
}
</style>
