<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "TaskFormModal",
});
</script>

<script setup lang="ts">
import Icon from "@/components/Module/Icon/index.vue";
import Modal from "@/components/Module/Modal/index.vue";
import TrainForm from "@/views/modelTraining/index/components/Form/Train.vue";
import { ref, computed, unref } from "vue";
import { FormInstance, Button, Space, message } from "ant-design-vue";

interface PropsType {
  task: Record<string, any>;
  options: Record<string, any>;
}

const props = withDefaults(defineProps<PropsType>(), {
  task: () => {
    return {};
  },
  options: () => {
    return {};
  },
});

const emits = defineEmits(["onSuccess"]);

// 表单实例
const formRef = ref();

// 获取表单实例
const formInit = (e: FormInstance) => {
  console.log("formInit", e);
  formRef.value = e;
};

// 表单
const formData = ref<Record<string, any>>({
  modelId: null, // 模型
  trainDataId: null, // 训练集
  testDataId: null, // 测试集
  frameworkId: "PYTORCH", // 训练框架
  // learningRate: "", // 学习率
  batch: "", // 批次大小
  round: "", // 训练轮次
  // optimizerId: "", // 优化器
  exportType: ["ONNX", "PT", "PTH"], // 导出格式
  code: "", // 执行代码
  description: "",
  config: "", // 配置文件
  weight: "", // 权重
  // savePath: "", // 保存路径
});

const exportOptions = props.options.state.exportOptions;

const showOptions = computed(() => {
  const models = props.options.state.models.value.map((item: Record<string, any>) => {
    return {
      ...item,
      label: item.name,
      value: item.id,
    };
  });

  // 训练集
  const trainData = props.options.state.trainDataset.value.map((item: Record<string, any>) => {
    return {
      label: item.name,
      value: item.id,
    };
  });

  // 测试集
  const testData = props.options.state.testDataset.value.map((item: Record<string, any>) => {
    return {
      label: item.name,
      value: item.id,
    };
  });

  const plateForm: any[] = [];
  plateForm.push({
    label: "PYTORCH",
    value: "pytorch",
  });
  // if (props.options.state.platform.value?.platform) {
  //   plateForm.push({
  //     label: props.options.state.platform.value?.platform,
  //     value: props.options.state.platform.value?.platform,
  //   });
  // }

  let weightOptions: any[] = [];
  let configOptions: any[] = [];

  if (formData.value.modelId) {
    // 如果选了模型，选项跟随变化
    const modelId = formData.value.modelId;
    const model = props.options.state.models.value.find(
      (item: Record<string, any>) => item.id == modelId,
    );
    if (model) {
      configOptions = model.config_files
        .split(",")
        .filter((opt: string) => !!opt.trim())
        .map((opt: string) => {
          return {
            label: opt,
            value: opt,
          };
        });
      weightOptions = model.pretrained_weights
        .split(",")
        .filter((opt: string) => !!opt.trim())
        .map((opt: string) => {
          return {
            label: opt,
            value: opt,
          };
        });
    }
  }

  return {
    modelOptions: models, // 模型
    trainDataOptions: trainData, // 训练数据集
    testDataOptions: testData, // 测试数据集
    frameworkOptions: plateForm, // 框架集合
    // optimizerOptions: [], // 优化器选项
    exportTypeOptions: exportOptions, // 导出选项
    weightOptions: weightOptions, // 权重选项
    configOptions: configOptions, // 配置选项
  };
});

// 选项集合
// const optionsGroup = {
//   modelOptions: props.options.models, // 模型
//   trainDataOptions: [], // 训练数据集
//   testDataOptions: [], // 测试数据集
//   frameworkOptions: [
//     {
//       label: "TensorFlow",
//       value: "tensorflow",
//     },
//     {
//       label: "PyTorch",
//       value: "pytorch",
//     },
//   ], // 框架集合
//   optimizerOptions: [], // 优化器选项
//   exportTypeOptions: [
//     {
//       label: "ONNX",
//       value: "ONNX",
//     },
//     {
//       label: "PT",
//       value: "PT",
//     },
//     {
//       label: "PTH",
//       value: "PTH",
//     },
//   ], // 导出格式集合
// };

// 上传
const onUpload = () => {};

let open = ref<boolean>(false);

// 重置
const reset = () => {
  formData.value = {
    modelId: null, // 模型
    trainDataId: null, // 训练集
    testDataId: null, // 测试集
    frameworkId: "", // 训练框架
    // learningRate: "", // 学习率
    batch: "", // 批次大小
    round: "", // 训练轮次
    // optimizerId: "", // 优化器
    exportType: ["ONNX", "PT", "PTH"], // 导出格式
    code: "", // 执行代码
    description: "", //任务描述
    config: "", // 配置文件
    weight: "", // 权重
    // savePath: "", // 保存路径
  };
};

// 打开
const onOpen = () => {
  reset();
  open.value = true;
};

// 关闭
const onClose = () => {
  open.value = false;
};

defineExpose({ onOpen, onClose });

const loading = computed(() => {
  return props.task.requestMap.createTaskRequest.loading.value;
});

// 提交
const onSubmit = async () => {
  console.log("onSubmit", formRef);
  await formRef.value.validate();
  const raw = unref(formData);
  const params = {
    model_id: raw.modelId,
    train_dataset_id: raw.trainDataId,
    test_dataset_id: raw.testDataId,
    batch_size: raw.batch,
    epoch: raw.round,
    export_formats: raw.exportType,
    // script_command: raw.code,
    task_description: raw.description,
    config_file_path: raw.config,
    pretrained_weight_path: raw.weight,
  };
  console.log("submit", params);
  const res = await props.task.api.createTask(params);
  if (res?.code == 200) {
    emits("onSuccess");
    onClose();
  } else {
    // message.error(res?.msg || "创建失败");
  }
  return res;
};
</script>

<template>
  <Modal
    v-model:open="open"
    title="新建训练任务"
    width="700px"
    style="top: 20px"
    :loading="loading"
    :onConfirm="onSubmit"
  >
    <TrainForm
      v-if="open"
      :optionsGroup="showOptions"
      v-model:formData="formData"
      @init="formInit"
      v-bind="props"
    />
  </Modal>
</template>

<style scoped lang="scss">
.grid-box {
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  :deep(.ant-form-item) {
    margin-bottom: 0;
  }
}
.grey-text {
  color: #8c8c8c;
}
.upload-row {
  .ant-upload-wrapper {
    display: block;
    :deep(.ant-upload) {
      width: 100%;
    }
  }
  .ant-upload-select {
    width: 100%;
    .upload-box {
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      font-size: 16px;
      color: #8a8a8a;
      width: 100%;
      aspect-ratio: 537 / 91;
      border-radius: 6px 6px 6px 6px;
      border: 1px solid #d9d9d9;
      background: rgba(200, 200, 200, 0.2);
      &-icon {
      }
      &-title {
      }
    }
  }
  .upload-desc {
    font-family:
      Source Han Sans,
      Source Han Sans;
    font-weight: 400;
    font-size: 12px;
    color: #c8c8c8;
    line-height: 26px;
    text-align: justify;
    font-style: normal;
    text-transform: none;
  }
}

.upload-footer {
  padding: 12px 16px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: end;
  gap: 20px;
}
</style>
