<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="训练名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入训练名称" />
      </el-form-item>
      <el-form-item label="数据集" prop="dataId">
        <el-select v-model="formData.dataId" placeholder="请选择数据集" style="width: 100%">
          <el-option
            v-for="project in projectList"
            :key="project.id"
            :label="project.name"
            :value="project.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据集分配" prop="ratios">
        <div class="ratio-slider-container">
          <div class="ratio-labels">
            <span>训练集: {{ formData.train }}%</span>
            <span>验证集: {{ formData.val }}%</span>
            <span>测试集: {{ formData.test }}%</span>
          </div>
          <el-slider 
            v-model="ratioRange" 
            range 
            :min="0" 
            :max="100" 
            @change="handleRatioChange"
            :marks="marks"
            :format-tooltip="formatTooltip"
          />
        </div>
      </el-form-item>
      <el-form-item label="轮次" prop="round">
        <el-input-number v-model="formData.round" :min="1" :max="1000" placeholder="请输入轮次" />
      </el-form-item>
      <el-form-item label="批次大小" prop="size">
        <el-input-number v-model="formData.size" :min="1" :max="128" placeholder="请输入批次大小" />
      </el-form-item>
      <el-form-item label="图片大小" prop="imageSize">
        <el-input-number 
          v-model="formData.imageSize" 
          :min="32" 
          :max="16384" 
          :step="32"
          placeholder="请输入图片大小" 
        />
        <div class="form-tip">正方形尺寸，非正方形图片将自动填充黑色背景，必须为32的倍数</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { TrainApi, TrainVO } from '@/api/annotation/train'
import { MarkApi, DataVO } from '@/api/annotation/mark'

/** 训练 表单 */
defineOptions({ name: 'TrainForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const projectList = ref<DataVO[]>([]) // 项目列表

const formData = ref({
  id: undefined,
  name: undefined,
  dataId: undefined,
  train: 70,
  val: 20,
  test: 10,
  round: 4,
  size: 50,
  imageSize: 640,
})

// 滑块范围值 [训练集结束点, 训练集+验证集结束点]
const ratioRange = ref([70, 90])

// 滑块标记点
const marks = {
  0: '0%',
  25: '25%',
  50: '50%',
  75: '75%',
  100: '100%'
}

const formRules = reactive({
  name: [{ required: true, message: '训练名称不能为空', trigger: 'blur' }],
  dataId: [{ required: true, message: '数据集不能为空', trigger: 'change' }],
  round: [{ required: true, message: '轮次不能为空', trigger: 'blur' }],
  size: [{ required: true, message: '批次大小不能为空', trigger: 'blur' }],
  imageSize: [
    { required: true, message: '图片大小不能为空', trigger: 'blur' },
    { 
      validator: (rule: any, value: number, callback: Function) => {
        if (value && value % 32 !== 0) {
          callback(new Error('图片大小必须是32的倍数'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
})

const formRef = ref() // 表单 Ref

// 获取项目列表
const getProjectList = async () => {
  try {
    const response = await MarkApi.getProjectList()
    projectList.value = response
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 范围滑块变化处理函数
const handleRatioChange = (value: [number, number]) => {
  const [trainEnd, valEnd] = value
  formData.value.train = trainEnd
  formData.value.val = valEnd - trainEnd
  formData.value.test = 100 - valEnd
  
  // 确保比例为整数且总和为100
  formData.value.train = Math.round(formData.value.train)
  formData.value.val = Math.round(formData.value.val)
  formData.value.test = Math.round(formData.value.test)
  
  // 更新滑块值
  ratioRange.value = [formData.value.train, formData.value.train + formData.value.val]
}

// 格式化提示信息
const formatTooltip = (value: number) => {
  const [trainEnd, valEnd] = ratioRange.value
  if (value === trainEnd) {
    return `训练集: ${formData.value.train}%`
  } else if (value === valEnd) {
    return `验证集结束: ${valEnd}%`
  }
  return `${value}%`
}

// 初始化滑块值
const initRatioRange = () => {
  ratioRange.value = [formData.value.train, formData.value.train + formData.value.val]
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获取项目列表
  await getProjectList()
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TrainApi.getTrain(id)
      initRatioRange()
    } finally {
      formLoading.value = false
    }
  } else {
    initRatioRange()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TrainVO
    if (formType.value === 'create') {
      await TrainApi.createTrain(data)
      message.success(t('common.createSuccess'))
    } else {
      await TrainApi.updateTrain(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    dataId: undefined,
    train: 70,
    val: 20,
    test: 10,
    round: 4,
    size: 50,
    imageSize: 640,
  }
  initRatioRange()
  formRef.value?.resetFields()
}
</script>

<style scoped>
.ratio-slider-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.ratio-labels {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 8px;
}

.ratio-labels span {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>