<template>
  <div class="createTask-bigBox">
    <dv-border-box1 ref="borderRef" style="width: 80%; height: calc(100% - 20px); margin: 0 auto">
      <div class="createTask-container">
        <h3 class="title" style="margin-top: 0">{{ title }}</h3>
        <!-- <h4 class="title2" v-if="pageIndex === 4">训练算法</h4> -->
        <div v-for="(item, index) in formItems" :key="index" class="createTask-main">
          <ProForm ref="proFormRef" :items-options="item.items" :form-options="_options" :model="item.model" class="proform">
            <template #selectTask>
              <el-tree
                style="max-width: 600px"
                ref="selectTaskTreeRef"
                :default-checked-keys="formItem.selectTask"
                :default-expanded-keys="formItem.selectTask"
                :props="defaultProps"
                :check-on-click-node="true"
                :data="data1"
                node-key="id"
                show-checkbox
                @check="
                  (click, checked) => {
                    changeTree(click, checked)
                  }
                "
              />
            </template>
            <template #proTable="{}">
              <el-tabs
                tab-position="left"
                v-model="activeName"
                style="min-height: 450px"
                class="demo-tabs"
                :before-leave="beforeTabLeave"
                @tab-click="handleClick"
              >
                <el-tab-pane label="数据" name="one">
                  <div class="table-box">
                    <ProTable
                      ref="proTable"
                      row-key="id"
                      :columns="dataColumns"
                      :request-api="listDataApi"
                      :tool-button="false"
                      :init-param="initParam1"
                      height="45vh"
                    >
                    </ProTable>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </template>
            <template #operation="{}">
              <div class="footBtn">
                <el-button class="btn back" v-if="pageIndex === 1" @click="onReturn()"> 返回 </el-button>
                <el-button class="btn back" v-else @click="onBack()"> 上一步 </el-button>
                <el-button
                  class="btn add"
                  type="primary"
                  v-if="(pageIndex === 2 || pageIndex === 6 || pageIndex === 10) && model.taskType === '1'"
                  style="margin-left: -15px"
                  @click="addNewData()"
                >
                  增加新一组数据
                </el-button>
                <el-button
                  class="btn add"
                  style="margin-left: -15px"
                  v-if="(pageIndex === 5 || pageIndex === 9 || pageIndex === 13) && model.taskType === '2'"
                  @click="onAdd(pageIndex)"
                >
                  增加算法
                </el-button>
                <el-button class="btn next" type="success" @click="nextBtnText === '提交' ? onSubmit() : onNext()">
                  {{ nextBtnText }}
                </el-button>
              </div>
            </template>
          </ProForm>
        </div>
      </div>
    </dv-border-box1>
  </div>
</template>
<script setup lang="tsx" name="createTask">
import { ref, ComputedRef, computed, watch, reactive } from 'vue'
import ProForm from '@/components/ProForm/index.vue'
import { useRouter } from 'vue-router'
import { getModelApi, getAlgorithmApi, createTaskApi } from '@/api/modules/taais/task'
import ProTable from '@/components/ProTable/index.vue'
import { ColumnProps, ProTableInstance } from '@/components/ProTable/interface'
import { listDataApi } from '@/api/modules/demo/data'
import { ElMessage, ElTree } from 'element-plus'
import type { TabsPaneContext } from 'element-plus'
const activeName = ref('one')
let tabTwo = ref(true)
let tabThree = ref(true)
let tabFour = ref(true)
let initParam1 = reactive({ type: 1 })
let initParam2 = reactive({ type: 2 })
let initParam3 = reactive({ type: 3 })
let initParam4 = reactive({ type: 4 })
const proTable = ref<ProTableInstance>()
let model = ref({
  taskType: '2'
})

let formItem = reactive({
  taskName: '',
  selectTask: [2, 5] as any,
  trainDataSelect: [] as any[],
  trainDataEnhancement: {
    algorithmId: null,
    params: []
  },
  trainDataExpansion: {
    algorithmId: null,
    modelId: null,
    params: []
  },
  train: [{}],
  testDataSelect: [] as any[],
  testDataEnhancement: {
    algorithmId: null,
    modelId: null,
    params: []
  },
  testDataExpansion: {
    algorithmId: null,
    modelId: null,
    params: []
  },
  test: [{}],
  reasoningDataSelect: [] as any[],
  reasoningDataEnhancement: {
    algorithmId: null,
    modelId: null,
    params: []
  },
  reasoningDataExpansion: {
    algorithmId: null,
    modelId: null,
    params: []
  },
  reasoning: [{}]
})
let prevTreeData = ref([3])
const router = useRouter()
let subSystem, selectTrainAgloId, selectTestAgloId, selectReasoningAgloId
const trainActiveTab = ref()
const testActiveTab = ref()
const reasoningActiveTab = ref()
let pageIndex = ref<number>(1)
const selectTaskTreeRef = ref<InstanceType<typeof ElTree>>()

let title = ref('数据扩增任务')
let nextBtnText = ref('下一步')
const data1 = [
  {
    id: 98,
    label: '训练',
    disabled: true,
    children: [
      {
        id: 2,
        label: '训练数据选择',
        children: []
      },
      {
        id: 3,
        label: '训练数据增广',
        children: []
      },
      {
        id: 5,
        label: '训练',
        children: []
      }
    ]
  },
  {
    id: 99,
    label: '验证',
    disabled: true,
    children: [
      {
        id: 6,
        label: '验证数据选择',
        children: []
      },
      {
        id: 9,
        label: '验证',
        children: []
      }
    ]
  },
  {
    id: 100,
    label: '测试',
    disabled: true,
    children: [
      {
        id: 10,
        label: '测试数据选择',
        children: []
      },
      {
        id: 13,
        label: '测试',
        children: []
      }
    ]
  }
]

const dataColumns = reactive<ColumnProps<any>[]>([
  { type: 'selection', fixed: 'left', width: 70 },
  {
    prop: 'name',
    label: '名称',
    width: 120
  },
  {
    prop: 'dataType',
    label: '数据类型',
    width: 120
  },
  {
    prop: 'fileType',
    label: '文件类型',
    width: 120
  },
  {
    prop: 'batchNum',
    label: '批次号',
    search: {
      el: 'input',
      defaultValue: ''
    },
    width: 120
  },
  {
    prop: 'objectType',
    label: '目标类型',
    search: {
      el: 'input',
      defaultValue: ''
    },
    width: 120
  },
  {
    prop: 'objectSubtype',
    label: '目标子类型',
    search: {
      el: 'input',
      defaultValue: ''
    },
    width: 120
  },

  {
    prop: 'scene',
    label: '场景',
    width: 120
  },
  {
    prop: 'dataSource',
    label: '数据源',
    width: 120
  },
  {
    prop: 'gatherTime',
    label: '采集时间',
    width: 120
  },
  {
    prop: 'gatherSpot',
    label: '采集地点',
    width: 120
  },
  {
    prop: 'increment',
    label: '扩增方式',
    width: 120
  }
])
const defaultProps = {
  children: 'children',
  label: 'label'
}
const _options: ComputedRef<ProForm.FormOptions> = computed(() => {
  const form = {
    labelWidth: 120,
    hasFooter: true,
    disabled: false,
    showSubmitButton: false
  }
  return Object.assign(form)
})

let items = reactive<ProForm.ItemsOptions[]>([
  // 1
  {
    label: '任务名称',
    prop: 'taskName',
    span: 12,
    rules: [{ required: true, message: '请输入任务名称' }],
    show: () => {
      return pageIndex.value === 1 ? true : false
    },
    compOptions: {
      elTagName: 'input',
      clearable: true,
      placeholder: '请输入任务名称',
      onChange: val => {
        formItem.taskName = val
      }
    }
  },
  // 2  6  10
  {
    label: '',
    hideLabelSuffix: true,
    labelWidth: '0px',
    prop: 'proTable',
    show: () => {
      return pageIndex.value === 2 || pageIndex.value === 6 || pageIndex.value === 10 ? true : false
    },
    compOptions: {
      elTagName: 'slot'
    }
  },
  // 3
  {
    label: '选择增广算法',
    prop: 'trainEnhanceAlgo',
    span: 14,
    rules: [{ required: true, message: '选择增广算法' }],
    show: () => {
      return pageIndex.value === 3 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'algorithmName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        formItem.trainDataEnhancement.algorithmId = val
        // agloChange('trainEnhanceModel', val)
        // getAgloParams(4, 'trainDataEnhancement', 3, val)
        getAlgorithmApi(4, subSystem).then(res => {
          res.data.forEach(item => {
            if (item.id === val) {
              const params = eval('(' + item.parameterConfig + ')')
              formItem['trainDataEnhancement'].params = params
              addForm(params, 3, 'trainDataEnhancement')
            }
          })
        })
      }
    }
  },
  // {
  //   label: '选择增广模型',
  //   prop: 'trainEnhanceModel',
  //   span: 14,
  //   rules: [{ required: true, message: '选择增广模型' }],
  //   show: () => {
  //     return pageIndex.value === 3 ? true : false
  //   },
  //   compOptions: {
  //     elTagName: 'select',
  //     labelKey: 'modelName',
  //     valueKey: 'id',
  //     enum: null,
  //     onChange: val => {
  //       getAgloParams(4, 'trainDataEnhancement', 3, val)
  //     }
  //   }
  // },
  // 4
  {
    label: '选择扩充算法',
    prop: 'trainExpansionAlgo',
    span: 14,
    rules: [{ required: true, message: '选择扩充算法' }],
    show: () => {
      return pageIndex.value === 4 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'algorithmName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        formItem.trainDataExpansion.algorithmId = val
        agloChange('trainExpansionModel', val, false)
      }
    }
  },
  {
    label: '选择扩充模型',
    prop: 'trainExpansionModel',
    span: 14,
    rules: [{ required: true, message: '选择扩充模型' }],
    show: () => {
      return pageIndex.value === 4 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'modelName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        getAgloParams(5, 'trainDataExpansion', 4, val)
      }
    }
  },
  // 5
  {
    label: '选择训练算法',
    prop: 'trainAlgo',
    span: 14,
    rules: [{ required: true, message: '请选择训练算法' }],
    show: () => {
      return pageIndex.value === 5 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'algorithmName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        selectTrainAgloId = val
        formItem.train[0]['algorithmId'] = val
        agloChange('trainModel', val, false)
      }
    }
  },
  {
    label: '选择训练模型',
    prop: 'trainModel',
    span: 14,
    rules: [{ required: true, message: '请选择训练模型' }],
    show: () => {
      return pageIndex.value === 5 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'modelName',
      valueKey: 'id',
      // enum: () => getModelApi(1),
      enum: null,
      onChange: val => {
        getAlgorithmApi(1, subSystem).then(res => {
          res.data.forEach(item => {
            if (item.id === selectTrainAgloId) {
              const params = eval('(' + item.parameterConfig + ')')
              formItem.train[0]['modelId'] = val
              formItem.train[0]['params'] = params
              // (参数信息，第几页，数组名称)
              addForm(params, 5, 'train[0]')
            }
          })
        })
      }
    }
  },
  // 7
  {
    label: '选择增强算法',
    prop: 'testEnhanceAlgo',
    span: 14,
    rules: [{ required: true, message: '选择增强算法' }],
    show: () => {
      return pageIndex.value === 7 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'algorithmName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        formItem.testDataEnhancement['algorithmId'] = val
        agloChange('testEnhanceModel', val, false)
      }
    }
  },
  {
    label: '选择增强模型',
    prop: 'testEnhanceModel',
    span: 14,
    rules: [{ required: true, message: '选择增强模型' }],
    show: () => {
      return pageIndex.value === 7 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'modelName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        if (val === 1) {
          return
        } else {
          getAgloParams(4, 'testDataEnhancement', 7, val)
        }
      }
    }
  },
  // 8
  {
    label: '选择扩充算法',
    prop: 'testExpansionAlgo',
    span: 14,
    rules: [{ required: true, message: '选择扩充算法' }],
    show: () => {
      return pageIndex.value === 8 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'algorithmName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        formItem.testDataExpansion['algorithmId'] = val
        agloChange('testExpansionModel', val, false)
      }
    }
  },
  {
    label: '选择扩充模型',
    prop: 'testExpansionModel',
    span: 14,
    rules: [{ required: true, message: '选择扩充模型' }],
    show: () => {
      return pageIndex.value === 8 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'modelName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        if (val === 1) {
          return
        } else {
          getAgloParams(5, 'testDataExpansion', 8, val)
        }
      }
    }
  },
  // 9
  {
    label: '选择验证算法',
    prop: 'testAlgo',
    span: 14,
    rules: [{ required: true, message: '请选择验证算法' }],
    show: () => {
      return pageIndex.value === 9 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'algorithmName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        selectTestAgloId = val
        formItem.test[0]['algorithmId'] = val
        agloChange('testModel', val, true)
      }
    }
  },
  {
    label: '选择验证模型',
    prop: 'testModel',
    span: 14,
    rules: [{ required: true, message: '请选择验证模型' }],
    show: () => {
      return pageIndex.value === 9 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'modelName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        // getAgloParams(1, 'test[0]', 9, val, 0)
        getAlgorithmApi(2, subSystem).then(res => {
          res.data.forEach(item => {
            if (item.id === selectTestAgloId) {
              const params = eval('(' + item.parameterConfig + ')')
              formItem.test[0]['modelId'] = val
              formItem.test[0]['params'] = params
              // (参数信息，第几页，数组名称)
              addForm(params, 9, 'test[0]')
            }
          })
        })
      }
    }
  },
  // 11
  {
    label: '选择增强算法',
    prop: 'reasoningEnhanceAlgo',
    span: 14,
    rules: [{ required: true, message: '选择增强算法' }],
    show: () => {
      return pageIndex.value === 11 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'algorithmName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        formItem.reasoningDataEnhancement['algorithmId'] = val
        agloChange('reasoningEnhanceModel', val, false)
      }
    }
  },
  {
    label: '选择增强模型',
    prop: 'reasoningEnhanceModel',
    span: 14,
    rules: [{ required: true, message: '选择增强模型' }],
    show: () => {
      return pageIndex.value === 11 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'modelName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        if (val === 1) {
          return
        } else {
          getAgloParams(4, 'reasoningDataEnhancement', 11, val)
        }
      }
    }
  },
  // 12
  {
    label: '选择扩充算法',
    prop: 'reasoningExpansionAlgo',
    span: 14,
    rules: [{ required: true, message: '选择扩充算法' }],
    show: () => {
      return pageIndex.value === 12 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'algorithmName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        formItem.reasoningDataExpansion['algorithmId'] = val
        agloChange('reasoningExpansionModel', val, false)
      }
    }
  },
  {
    label: '选择扩充模型',
    prop: 'reasoningExpansionModel',
    rules: [{ required: true, message: '选择扩充模型' }],
    span: 14,
    show: () => {
      return pageIndex.value === 12 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'modelName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        if (val === 1) {
          return
        } else {
          getAgloParams(5, 'reasoningDataExpansion', 12, val)
        }
      }
    }
  },
  // 13
  {
    label: '选择测试算法',
    prop: 'reasoningAlgo',
    span: 14,
    rules: [{ required: true, message: '请选择测试算法' }],
    show: () => {
      return pageIndex.value === 13 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'algorithmName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        selectReasoningAgloId = val
        formItem.reasoning[0]['algorithmId'] = val
        agloChange('reasoningModel', val, true)
      }
    }
  },
  {
    label: '选择测试模型',
    prop: 'reasoningModel',
    span: 14,
    rules: [{ required: true, message: '请选择测试模型' }],
    show: () => {
      return pageIndex.value === 13 ? true : false
    },
    compOptions: {
      elTagName: 'select',
      labelKey: 'modelName',
      valueKey: 'id',
      enum: null,
      onChange: val => {
        getAlgorithmApi(3, subSystem).then(res => {
          res.data.forEach(item => {
            if (item.id === selectReasoningAgloId) {
              const params = eval('(' + item.parameterConfig + ')')
              formItem.reasoning[0]['modelId'] = val
              formItem.reasoning[0]['params'] = params
              // (参数信息，第几页，数组名称)
              addForm(params, 13, 'reasoning[0]')
            }
          })
        })
      }
    }
  }
])
// let formItemsTemp2 = ref([
//   {
//     items,
//     model: model.value
//   }
// ])
// let formItemsTemp7 = ref([
//   {
//     items,
//     model: model.value
//   }
// ])
let formItems = ref([
  {
    items,
    model: model.value
  }
])
let addTrainAgloIndex = 1
let addTestAgloIndex = 1
let addReasoningAgloIndex = 1
const proFormRef = ref<InstanceType<typeof ProForm> | null>(null)
// 增加训练算法
const onAdd = pageNum => {
  let arrayName, agloIndex, type, name
  switch (pageNum) {
    case 5:
      arrayName = 'train'
      agloIndex = addTrainAgloIndex
      type = 1
      name = '训练'
      break
    case 9:
      arrayName = 'test'
      agloIndex = addTestAgloIndex
      type = 2
      name = '验证'
      break
    case 13:
      arrayName = 'reasoning'
      agloIndex = addReasoningAgloIndex
      type = 3
      name = '测试'
      break
    default:
      break
  }
  const formEl = proFormRef.value![0].proFormRef
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      if (agloIndex >= 4) {
        ElMessage.warning('最多选择四种算法,已选择了四种')
        return
      }
      getAlgorithmApi(type, subSystem).then(res1 => {
        formItems.value[0].items.push({
          label: `选择${name}算法`,
          prop: `${arrayName}Aglo${agloIndex}`,
          span: 14,
          rules: [{ required: true, message: `请选择${name}算法` }],
          show: () => {
            return pageIndex.value === pageNum ? true : false
          },
          compOptions: {
            elTagName: 'select',
            labelKey: 'algorithmName',
            valueKey: 'id',
            enum: res1.data,
            onChange: agloId => {
              formItem[`${arrayName}`].push({})
              if (!formItem[`${arrayName}`][`${agloIndex}`]['algorithmId']) {
                formItem[`${arrayName}`][`${agloIndex}`]['algorithmId'] = agloId
                getModelApi(agloId).then(res2 => {
                  if (type === 2 || type === 3) {
                    res2.data.unshift({
                      algorithmId: null,
                      id: 1,
                      modelAddress: null,
                      modelName: '基于训练生成的模型'
                    })
                  }
                  formItems.value[0].items.push({
                    label: `选择${name}模型`,
                    prop: `${arrayName}Model${agloIndex}`,
                    span: 14,
                    rules: [{ required: true, message: `请选择${name}模型` }],
                    show: () => {
                      return pageIndex.value === pageNum ? true : false
                    },
                    compOptions: {
                      elTagName: 'select',
                      labelKey: 'modelName',
                      valueKey: 'id',
                      enum: res2.data,
                      onChange: modelId => {
                        res1.data.forEach(agloItem => {
                          if (agloItem.id === agloId) {
                            const params = eval('(' + agloItem.parameterConfig + ')')
                            formItem[`${arrayName}`][`${agloIndex}`]['modelId'] = modelId
                            formItem[`${arrayName}`][`${agloIndex}`]['params'] = params
                            addForm(params, pageNum, `${arrayName}[${agloIndex}]`)
                          }
                        })
                      }
                    }
                  })
                })
              } else {
                formItem[`${arrayName}`].splice(-1, 1)
                formItem[`${arrayName}`][`${agloIndex}`]['algorithmId'] = agloId
                const column = formItems.value[0].items.find(column => column.prop === `${arrayName}Model${agloIndex}`)
                if (column) {
                  getModelApi(agloId).then(newRes => {
                    column.compOptions.enum = newRes.data
                  })
                }
              }
            }
          }
        })
      })
      if (pageNum === 5) addTrainAgloIndex++
      if (pageNum === 9) addTestAgloIndex++
      if (pageNum === 13) addReasoningAgloIndex++
    }
  })
}
// 增加新数据
const addNewData = () => {
  switch (activeName.value) {
    case 'one':
      const table0Ref = proTable.value![0]
      if (table0Ref.tableData.length === 0) {
        ElMessage.warning('请正确选择该组数据')
      } else {
        tabTwo.value = false
        activeName.value = 'two'
      }
      break
    case 'two':
      const table1Ref = proTable.value![1]
      if (table1Ref.tableData.length === 0) {
        ElMessage.warning('请正确选择该组数据')
      } else {
        tabThree.value = false
        activeName.value = 'three'
      }
      break
    case 'three':
      const table2Ref = proTable.value![2]
      if (table2Ref.tableData.length === 0) {
        ElMessage.warning('请正确选择该组数据')
      } else {
        tabFour.value = false
        activeName.value = 'four'
      }
      break
    default:
      break
  }
}
// 增加表单事件
const addForm = (params, index, arrayName) => {
  params.forEach(item => {
    let i = formItems.value[0].items.length
    formItems.value[0].items.push({
      label: item.name,
      prop: `task${i}`,
      span: 12,
      rules: [
        { required: item.required, message: `${item.name}不能为空` },
        { pattern: new RegExp(`${item.validate}`), message: item.prompt }
      ],
      show: () => {
        return pageIndex.value === index ? true : false
      },
      compOptions: {
        elTagName: 'input',
        clearable: true,
        placeholder: item.prompt,
        onChange: val1 => {
          let label = item.name
          if (arrayName.includes(']')) {
            // 截取数组和下标
            let array = arrayName.slice(0, -3)
            let index = arrayName.slice(-2, -1)
            const item = formItem[`${array}`][`${index}`]['params'].find(item => item.name === label)
            if (item) {
              item.value = val1
            }
          } else {
            const item1 = formItem[`${arrayName}`]['params'].find(item => item.name === label)
            if (item1) {
              item1.value = val1
            }
          }
        }
      }
    })
    formItems.value[0].model[`task${i}`] = item.defaultValue
  })
}
const agloChange = (propName, agloId, flag) => {
  const Column = formItems.value[0].items.find(column => column.prop === propName)
  if (Column) {
    getModelApi(agloId).then(res => {
      Column.compOptions.enum = res.data as any[]
      if (flag) {
        Column.compOptions.enum.unshift({
          algorithmId: null,
          id: 1,
          modelAddress: null,
          modelName: '基于训练生成的模型'
        })
      }
    })
  }
}
const getAlgo = (propName, type) => {
  const column = formItems.value[0].items.find(column => column.prop === propName)
  if (column) {
    getAlgorithmApi(type, subSystem).then(res => {
      column.compOptions.enum = res.data as any[]
    })
  }
}
// 算法类型:1-5、算法类型名称:如训练数据增强、页码、模型Id、模型的参数下标
const getAgloParams = (agloType, agloTypeName, page, modelId) => {
  const algoId = formItem[agloTypeName].algorithmId
  getAlgorithmApi(agloType, subSystem).then(res => {
    res.data.forEach(item => {
      if (item.id === algoId) {
        const params = eval('(' + item.parameterConfig + ')')
        formItem[agloTypeName].modelId = modelId
        formItem[agloTypeName].params = params
        // (参数信息，第几页，数组名称)
        addForm(params, page, agloTypeName)
      }
    })
  })
}
// 返回按钮
const onReturn = () => {
  router.push(`/index`)
}
let flag = ref<number>(0) //跳转到日志页面的flag,0为训练日志、1为推理日志
// 下一步
const onNext = () => {
  const formEl = proFormRef.value![0].proFormRef
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      if (formItem.selectTask.length === 0 && pageIndex.value === 1) {
        ElMessage.warning('请选择任务')
        return
      }
      if (pageIndex.value === 2 || pageIndex.value === 6 || pageIndex.value === 10) {
        let dataName, flag
        if (pageIndex.value === 2) dataName = 'trainDataSelect'
        else if (pageIndex.value === 6) dataName = 'testDataSelect'
        else if (pageIndex.value === 10) dataName = 'reasoningDataSelect'
        switch (activeName.value) {
          case 'one':
            flag = 0
            break
          case 'two':
            flag = 1
            break
          case 'three':
            flag = 2
            break
          case 'false':
            flag = 3
            break
          default:
            break
        }
        formItem[dataName] = []
        for (let i = 0; i <= flag; i++) {
          if (proTable.value![i].tableData.length === 0) {
            ElMessage.warning('数据存在空集，请正确选择数据')
            return
          }
          let obj = proTable.value![i].searchParam
          for (let key in obj) {
            if (obj.hasOwnProperty(key) && obj[key] === '') {
              delete obj[key]
            }
          }
          formItem[dataName].push({
            conditionSelected: true,
            condition: proTable.value![i].searchParam
          })
        }
        activeName.value = 'one'
        tabTwo.value = true
        tabThree.value = true
        tabFour.value = true
      }
      if (pageIndex.value === formItem.selectTask[formItem.selectTask.length - 2]) {
        nextBtnText.value = '提交'
      }
      if (pageIndex.value === formItem.selectTask[formItem.selectTask.length - 1]) {
        console.log('flag.value', flag.value)
        return
        // router.push({ path: `/logPage/${flag.value}`, query: { type: 1 } })
      }

      pageIndex.value = formItem.selectTask[formItem.selectTask.findIndex(page => page === pageIndex.value) + 1]
    }
  })
}
// 上一步
const onBack = () => {
  nextBtnText.value = '下一步'
  if (pageIndex.value === formItem.selectTask[0]) {
    pageIndex.value = 1
    return
  }
  pageIndex.value = formItem.selectTask[formItem.selectTask.findIndex(page => page === pageIndex.value) - 1]
}
const changeTree = (newVal, allVal) => {
  const newId = newVal.id
  const dependencyMap = new Map([
    [
      [3, 4, 2, 5],
      [2, 5]
    ], // 如果包含3或4，则添加2和5
    [
      [7, 8, 6, 9],
      [6, 9]
    ],
    [
      [11, 12, 10, 13],
      [10, 13]
    ]
  ])
  const updateCheckedKeys = keysSet => {
    prevTreeData.value = Array.from(keysSet)
    selectTaskTreeRef.value![0].setCheckedKeys(Array.from(keysSet), false)
  }

  if (!allVal.checkedKeys.includes(newId)) {
    if (newId === 2 || newId === 5) {
      const data = delNumber(2, 5, allVal.checkedKeys)
      updateCheckedKeys(new Set(data))
    } else if (newId === 6 || newId === 9) {
      const data = delNumber(6, 9, allVal.checkedKeys)
      updateCheckedKeys(new Set(data))
    } else if (newId === 10 || newId === 13) {
      const data = delNumber(10, 13, allVal.checkedKeys)
      updateCheckedKeys(new Set(data))
    }
  } else {
    for (const [keysToCheck, keysToAdd] of dependencyMap.entries()) {
      if (keysToCheck.includes(newId)) {
        const keysSet = new Set([...allVal.checkedKeys, ...keysToAdd])
        updateCheckedKeys(keysSet)
        break
      }
    }
  }

  formItem.selectTask = selectTaskTreeRef.value![0].getCheckedKeys().filter(item => item < 90)
}
// 树组件去除节点函数
const delNumber = (start, end, dataList) => {
  return dataList.filter(number => !(number >= start && number <= end)).sort((a, b) => a - b)
}
const onSubmit = () => {
  findParams(formItem)
  createTaskApi(formItem).then(res => {
    console.log('createTask', res)
    // const taskId=res
    router.push({ path: `/task/subtask/`, query: { id: res.data } })
  })
}
const findParams = obj => {
  for (const key in obj) {
    if (obj[key] !== null && typeof obj[key] === 'object') {
      // 如果值是数组，则遍历数组中的每个元素
      if (Array.isArray(obj[key])) {
        obj[key].forEach(item => {
          if (item.params) {
            item.params.forEach(paramItem => {
              if (!paramItem.value) {
                paramItem.value = paramItem.defaultValue
              }
            })
            item.params = JSON.stringify(item.params)
          }
          if (item.condition) {
            item.condition = JSON.stringify(item.condition)
          }
        })
      } else {
        // 如果值是对象
        if (obj[key]['params']) {
          obj[key]['params'].forEach(paramItem => {
            if (!paramItem.value) {
              paramItem.value = paramItem.defaultValue
            }
          })
          obj[key]['params'] = JSON.stringify(obj[key]['params'])
        }
        if (obj[key]['condition']) {
          obj[key]['condition'] = JSON.stringify(obj[key]['condition'])
        }
      }
    }
  }
}
const beforeTabLeave = (activeName, oldActiveName) => {
  let dataSelect1
  if (pageIndex.value === 2) {
    dataSelect1 = 'trainDataSelect'
  } else if (pageIndex.value === 6) {
    dataSelect1 = 'testDataSelect'
  } else if (pageIndex.value === 10) {
    dataSelect1 = 'reasoningDataSelect'
  }

  switch (oldActiveName) {
    case 'one':
      Object.assign(initParam1, formItem[dataSelect1]?.[0]?.condition)
      break
    case 'two':
      Object.assign(initParam2, formItem[dataSelect1]?.[1]?.condition)
      break
    case 'three':
      Object.assign(initParam3, formItem[dataSelect1]?.[2]?.condition)
      break
    case 'four':
      Object.assign(initParam4, formItem[dataSelect1]?.[3]?.condition)
      break
    default:
      break
  }
}
const handleClick = (tab: TabsPaneContext) => {
  let dataSelect
  if (pageIndex.value === 2) {
    dataSelect = 'trainDataSelect'
    trainActiveTab.value = tab
  } else if (pageIndex.value === 6) {
    dataSelect = 'testDataSelect'
    testActiveTab.value = tab
  } else if (pageIndex.value === 10) {
    dataSelect = 'reasoningDataSelect'
    reasoningActiveTab.value = tab
  }
  const tabName = tab.paneName
  switch (tabName) {
    case 'one':
      const data1 = formItem[dataSelect]?.[0]?.condition
      console.log('data1', data1)
      updateDefaultValue(data1?.objectType, data1?.objectSubtype, data1?.batchNum)
      break
    case 'two':
      const data2 = formItem[dataSelect]?.[1]?.condition
      console.log('data2', data2)
      updateDefaultValue(data2?.objectType, data2?.objectSubtype, data2?.batchNum)
      break
    case 'three':
      const data3 = formItem[dataSelect]?.[2]?.condition
      console.log('data3', data3)
      updateDefaultValue(data3?.objectType, data3?.objectSubtype, data3?.batchNum)
      break
    case 'four':
      const data4 = formItem[dataSelect]?.[3]?.condition
      updateDefaultValue(data4?.objectType, data4?.objectSubtype, data4?.batchNum)
      break
    default:
      break
  }
}
const updateDefaultValue = (objectType, objectSubtype, batchNum) => {
  dataColumns.map(column => {
    if (column.prop === 'objectType') {
      column.search!.defaultValue = objectType
    } else if (column.prop === 'objectSubtype') {
      column.search!.defaultValue = objectSubtype
    } else if (column.prop === 'batchNum') {
      column.search!.defaultValue = batchNum
    }
  })
}
watch(
  () => pageIndex.value,
  value => {
    switch (value) {
      case 1:
        title.value = '数据扩增：添加任务名称'
        nextBtnText.value = '下一步'
        break
      case 2:
        title.value = '训练数据选择'
        if (trainActiveTab.value) {
          handleClick(trainActiveTab.value)
        }
        break
      case 3:
        title.value = '训练数据增广'
        getAlgo('trainEnhanceAlgo', 4)
        break
      case 4:
        title.value = '训练数据扩充'
        getAlgo('trainExpansionAlgo', 5)
        break
      case 5:
        title.value = '训练算法选择'
        getAlgo('trainAlgo', 1)
        break
      case 6:
        title.value = '验证数据选择'
        if (testActiveTab.value) {
          handleClick(testActiveTab.value)
        }
        break
      case 7:
        title.value = '测试数据增强'
        getAlgo('testEnhanceAlgo', 4)
        break
      case 8:
        title.value = '测试数据扩充'
        getAlgo('testExpansionAlgo', 5)
        break
      case 9:
        title.value = '验证算法选择'
        getAlgo('testAlgo', 2)
        break
      case 10:
        title.value = '测试数据选择'
        if (reasoningActiveTab.value) {
          handleClick(reasoningActiveTab.value)
        }
        break
      case 11:
        title.value = '推理数据增强'
        getAlgo('reasoningEnhanceAlgo', 4)
        break
      case 12:
        title.value = '推理数据扩充'
        getAlgo('reasoningExpansionAlgo', 5)
        nextBtnText.value = '下一步'
        break
      case 13:
        title.value = '测试算法选择'
        getAlgo('reasoningAlgo', 3)
        break
      default:
        break
    }
  }
)
</script>
<style scoped lang="scss">
@import './index.scss';
</style>
