<!-- 用户管理 -->
<template>
  <div class="app-container model-detail">
    <!-- 用户新增/编辑表单 -->
    <el-card v-loading="loading">
      <template #header><svg-icon icon-class="pause" style="width: 20px; height: 20px" />数据集基本信息
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :lg="12" :xs="24">
            <el-form-item label="数据集名称" prop="dataset_name">
              <el-input v-model="form.dataset_name" placeholder="请输入数据集名称" />
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xs="24">
            <el-form-item label="数据集版本" prop="dataset_version">
              <el-input v-model="form.dataset_version" type="number" placeholder="请输入数据集版本" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :lg="12" :xs="24">
            <el-form-item label="适合模型类型" prop="modl_sub_type">
              <el-select v-model="form.modl_sub_type" placeholder="请选择适合模型类型">
                <el-option v-for="item in listOpt.modlSubTypeList" :key="item.modl_sub_type"
                  :label="item.modl_sub_type_name" :value="item.modl_sub_type" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xs="24">
            <el-form-item label="数据集格式" prop="dats_dataset_format">
              <el-select v-model="form.dats_dataset_format" placeholder="请选择数据集格式">
                <el-option v-for="item in listOpt.datasetFormatList" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :lg="12" :xs="24">
            <el-form-item label="标注类型" prop="dats_label_type">
              <el-select v-model="form.dats_label_type" placeholder="请选择标注类型">
                <el-option v-for="item in listOpt.labelTypeList" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xs="24">
            <el-form-item label="图像分辨率" prop="image_height">
              <el-row style="width: 100%">
                <el-col :lg="11">
                  <el-input v-model="form.image_width" type="number" placeholder="请输入分辨率宽度">
                    <template #prepend> 宽 </template>
                  </el-input>
                </el-col>
                <el-col :lg="2" class="font-center"><el-icon>
                    <Rank />
                  </el-icon></el-col>
                <el-col :lg="11">
                  <el-input v-model="form.image_height" type="number" placeholder="请输入分辨率高度">
                    <template #prepend> 高 </template>
                  </el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :lg="12" :xs="24">
            <el-form-item label="数据集描述" prop="dataset_desc">
              <el-input v-model="form.dataset_desc" placeholder="请输入数据集描述" :rows="2" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xs="24"> </el-col>
        </el-row>
        <el-row>
          <el-col :lg="12" :xs="24">
            <el-form-item label="数据集参数文件" prop="dataset_parameters">
              <el-upload ref="uploadRef" class="upload-demo" :on-change="handleFileChange" :on-remove="handleFileRemove"
                :on-exceed="handleFileExceed" :auto-upload="false" :limit="1" accept="application/json">
                <el-button type="primary"><el-icon class="el-icon--upload"> <i-ep-upload-filled />
                  </el-icon>选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传大小不超过 <strong style="color: red">10M</strong>，格式为
                    <strong style="color: red">json</strong> 的文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xs="24">
            <div style="padding-left: 35px" v-if="fileStatus">
              <el-divider content-position="left"><strong style="color: #409eff">数据集参数文件预览</strong></el-divider>
              <el-input v-model="codeHtml" placeholder="请输入数据集参数JSON" :rows="10" disabled type="textarea" />
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="card-footer">
      <el-button type="primary" @click="handleSubmit"><i-ep-check />确 定</el-button>
      <el-button @click="closeBack"><i-ep-close />取 消</el-button>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import ConstApi from "@/api/const";
import DataSetApi from "@/api/dataSet";

const router = useRouter();

const form = ref({}); // 基础表单
const formRef = ref(ElForm); // 表单
const loading = ref(false); //  加载状态
const dialogOpen = ref(false); //  加载状态
const fileStatus = ref(false); //  文件状态
const codeHtml = ref(""); //  文件信息

// 上传组件
const uploadRef = ref<UploadInstance>();

// 基础数据列表
let listOpt = reactive({
  labelTypeList: [],
  modlSubTypeList: [],
  datasetFormatList: [],
});

// 校验规则
const rules = reactive({
  dataset_name: [{ required: true, message: "数据集名称不能为空", trigger: "blur" }],
  dataset_version: [{ required: true, message: "数据集版本不能为空", trigger: "blur" }],
  modl_sub_type: [{ required: true, message: "适合模型类型不能为空", trigger: "change" }],
  dats_dataset_format: [
    { required: true, message: "数据集格式不能为空", trigger: "change" },
  ],
  dats_label_type: [{ required: true, message: "标注类型不能为空", trigger: "change" }],
  image_width: [{ required: true, message: "分辨率宽高不能为空", trigger: "blur" }],
  image_height: [{ required: true, message: "分辨率宽高不能为空", trigger: "blur" }],
  dataset_desc: [{ required: false, message: "数据集描述不能为空", trigger: "blur" }],
  dataset_parameters: [
    { required: true, message: "数据集参数文件不能为空", trigger: "blur" },
  ],
});

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  formRef.value.validate((valid: any) => {
    if (valid) {
      if (!form.value.image_width) {
        ElMessage.error("请输入图片分辨率宽度！");
        return false;
      }
      loading.value = true;
      DataSetApi.add(form.value)
        .then((res) => {
          if (res.data.code == 0) {
            ElMessage.success("保存成功");
            closeBack();
          }
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}, 3000);

// 文件上传
function handleFileChange(file) {
  //先创建一个读文件的对象 FileReader
  let reader = new FileReader();
  //判断浏览器是否支持 FileReader
  if (typeof FileReader === "undefined") {
    this.$message({
      type: "info",
      message: "您的浏览器不支持文件读取。",
    });
    return;
  }
  uploadFile(file).then((res) => {
    if (isJSON(res)) {
      //let jsonStr = JSON.stringify(res);
      form.value.dataset_parameters = JSON.parse(res);
      formRef.value.validateField("dataset_parameters");
      codeHtml.value = res;
      fileStatus.value = true;
    }
  });
}

/** 解析json */
function isJSON(str) {
  try {
    // 尝试解析输入的字符串
    JSON.parse(str);
    ElMessage.success("JSON文件解析成功");
    return true;
    // 成功解析
  } catch (error) {
    // 解析失败
    ElMessage.error("JSON文件解析失败");
    uploadRef.value.clearFiles();
    fileStatus.value = false;
    form.value.dataset_parameters = "";
    return false;
  }
}

// 文件读取
function uploadFile(file) {
  return new Promise(function (resolve, reject) {
    let reader = new FileReader();
    reader.readAsArrayBuffer(file.raw);
    reader.onload = function (e) {
      var ints = new Uint8Array(e.target.result); //要使用读取的内容，所以将读取内容转化成Uint8Array
      let snippets = new TextDecoder("UTF-8").decode(ints); //二进制缓存区内容转化成中文（即也就是读取到的内容）
      resolve(snippets);
    };
  });
}

// 文件删除
function handleFileRemove() {
  form.value.dataset_parameters = "";
  codeHtml.value = "";
  fileStatus.value = false;
}

// 超出限制，清空文件列表
function handleFileExceed() {
  uploadRef.value.clearFiles();
  ElMessage.warning("已清空文件列表,请重新上传！");
  handleFileRemove();
}

/** 返回默认页面 */
function closeBack() {
  router.push({ path: "/dataMgr/datas" });
}

// 初始化选项列表
const initData = () => {
  ConstApi.modlSubType().then((res) => {
    if (res.data.code == 0) {
      listOpt.modlSubTypeList = res.data.data.modl_sub_type_list || [];
    }
  });
  ConstApi.datasetFormatType().then((res) => {
    if (res.data.code == 0) {
      listOpt.datasetFormatList = res.data.data.dats_dataset_format_list || [];
    }
  });
  ConstApi.datsLabelType().then((res) => {
    if (res.data.code == 0) {
      listOpt.labelTypeList = res.data.data.dats_label_type_list || [];
    }
  });
};

onMounted(() => {
  initData();
});
</script>
<style scoped lang="scss">
.model-detail {
  :deep(.el-card__header) {
    padding: 8px 4px;
    display: flex;
    align-items: center;
  }
}

.sp-file {
  color: #29d;
}

.tb-base-info {
  line-height: 30px;
}

:deep(.svg-icon) {
  margin-right: 8px;
}

.card-footer {
  position: fixed;
  width: calc(100% - 215px);
  bottom: 0px;

  :deep(.el-card__body) {
    padding: 10px;

    .el-pagination {
      justify-content: end;
    }
  }
}

.font-center {
  text-align: center;
  color: #cccccc;
}
</style>
