<!-- 用户管理 -->
<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="baseFormRef" :model="baseForm" :rules="baseRules" label-width="100px">
        <el-row>
          <el-col :lg="12" :xs="12">
            <el-form-item label="工具链名称" prop="tool_name">
              <el-input
                v-model="baseForm.tool_name"
                placeholder="请输入工具链名称"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xs="12">
            <el-form-item label="厂商名称" prop="manufacturer">
              <el-input
                v-model="baseForm.manufacturer"
                disabled
                placeholder="请输入厂商名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :lg="12" :xs="12">
            <el-form-item label="工具链类型" prop="tool_type">
              <el-select
                v-model="baseForm.tool_type"
                disabled
                placeholder="请选择工具链类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in listOpt.typeList"
                  :key="item.type"
                  :label="item.name"
                  :value="item.type"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xs="12">
            <el-form-item label="ID编号" prop="user_id">
              <el-input v-model="baseForm.user_id" disabled placeholder="请输入ID编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :lg="12" :xs="12">
            <el-form-item label="工具链版本" prop="tool_version">
              <el-input
                v-model="baseForm.tool_version"
                disabled
                placeholder="请输入工具链版本"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xs="12">
            <el-form-item label="硬件类型" prop="cmpt_hardware_type">
              <el-input
                v-model="baseForm.cmpt_hardware_type"
                disabled
                placeholder="请输入硬件类型"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :lg="12" :xs="12">
            <el-form-item label="工具链描述" prop="tool_desc">
              <el-input
                v-model="baseForm.tool_desc"
                :rows="2"
                type="textarea"
                placeholder="请输入工具链描述"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12" :xs="12"></el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-row style="padding: 10px 15px">
      <el-col :lg="24" :xs="24">
        <el-button type="primary" @click="handlePushParams"
          ><i-ep-plus />添加运行参数</el-button
        >
      </el-col>
    </el-row>
    <el-card v-loading="loading">
      <template #header
        ><svg-icon
          icon-class="pause"
          style="width: 20px; height: 20px"
        />工具链运行参数信息</template
      >
      <el-table :data="pageData" style="width: 100%" stripe v-loading="queryLoading">
        <el-table-column prop="params_name" label="运行参数名称" align="left" />
        <el-table-column prop="params_desc" label="运行参数描述" align="left" />
        <el-table-column prop="params_desc1" label="匹配模型网络名称" align="left" />
        <el-table-column prop="user_name" label="创建用户" align="left" />
        <el-table-column prop="create_time" label="创建时间" align="left" />
        <el-table-column label="操作" fixed="right" align="center">
          <template #default="scope">
            <el-button text type="primary" size="small" @click="handleDetail(scope.row)"
              ><i-ep-view />查看</el-button
            >
            <el-button text type="primary" size="small" @click="handleDelete(scope.row)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.page_num"
        v-model:limit="queryParams.page_size"
        @pagination="handleQuery"
      />
    </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>
    <el-dialog
      v-model="dialogFormVisible"
      title="添加工具链运行参数"
      width="880"
      v-loading="formLoading"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="108px">
        <el-form-item label="运行参数名称" prop="params_name">
          <el-input v-model="form.params_name" placeholder="请输入运行参数名称" />
        </el-form-item>
        <el-form-item label="运行参数描述" prop="params_desc">
          <el-input
            v-model="form.params_desc"
            :rows="3"
            type="textarea"
            placeholder="请输入运行参数描述"
          />
        </el-form-item>
        <el-form-item label="运行参数文件" prop="params_content">
          <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-form-item v-if="fileStatus">
          <el-input
            v-model="form.params_content_v2"
            :rows="10"
            type="textarea"
            disabled
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false"><i-ep-close />取消</el-button>
          <el-button type="primary" @click="handleSubmitFile">
            <i-ep-check />确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogInfoVisible"
      title="查看工具链运行参数"
      width="880"
      v-loading="infoLoading"
    >
      <el-form label-width="108px">
        <el-form-item label="运行参数名称">
          <el-input v-model="dataInfo.params_name" disabled placeholder="请输入运行参数名称" />
        </el-form-item>
        <el-form-item label="运行参数描述">
          <el-input
            v-model="dataInfo.params_desc"
            :rows="3"
            type="textarea"
            disabled
            placeholder="请输入运行参数描述"
          />
        </el-form-item>
        <el-form-item label="运行参数文件" prop="params_content">
          <el-input
            v-model="form.params_content_v2"
            :rows="10"
            type="textarea"
            disabled
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogInfoVisible = false"><i-ep-close />取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import ToolChainshApi from "@/api/tool";

const route = useRoute();
const router = useRouter();

const ID = ref(""); // 编号
const queryLoading = ref(false); //  加载状态
const total = ref(0); // 数据总数
const pageData = ref([]); // 分页数据
const queryParams = reactive({
  page_num: 1,
  page_size: 10,
  tool_id: null,
});

// 基础表单
const baseForm = ref({});
const baseFormRef = ref(ElForm); // 表单
const loading = ref(false); //  加载状态
// 校验规则
const baseRules = reactive({
  tool_name: [{ required: true, message: "工具链名称不能为空", trigger: "blur" }],
  tool_desc: [{ required: true, message: "工具链描述不能为空", trigger: "blur" }],
});

// 表单数据
const form = reactive({});
const formRef = ref(ElForm); // 表单
const fileStatus = ref(false); //  文件状态
const formLoading = ref(false); //  表单加载状态
const dialogFormVisible = ref(false); //  弹窗加载状态
// 校验规则
const rules = reactive({
  params_name: [{ required: true, message: "运行参数名称不能为空", trigger: "blur" }],
  params_desc: [{ required: true, message: "运行参数描述不能为空", trigger: "blur" }],
  params_content: [{ required: true, message: "运行参数文件不能为空", trigger: "blur" }],
});

// 基础数据列表
let listOpt = reactive({
  typeList: [
    {
      type: "quantizer",
      name: "量化工具",
    },
    {
      type: "compiler",
      name: "编译工具",
    },
    {
      type: "label",
      name: "标注工具",
    },
    {
      type: "other",
      name: "其他工具",
    },
  ],
});

// 参数详情查看
const dataInfo = ref({});
const infoLoading = ref(false); //  表单加载状态
const dialogInfoVisible = ref(false); //  弹窗加载状态

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  baseFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      ToolChainshApi.editTool(baseForm.tool_id,baseForm)
        .then((res) => {
          if (res.data.code == 0) {
            ElMessage.success("修改成功");
            closeBack();
          }
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}, 3000);

/** 表单提交 */
const handleSubmitFile = useThrottleFn(() => {
  formRef.value.validate((valid: any) => {
    if (valid) {
      ElMessage.error("缺少接口");
      // formLoading.value = true;
      // ToolChainshApi.editTool(baseForm.tool_id,baseForm)
      //   .then((res) => {
      //     if (res.data.code == 0) {
      //       ElMessage.success("修改成功");
      //       closeBack();
      //     }
      //   })
      //   .finally(() => {
      //     formLoading.value = false;
      //   });
    }
  });
}, 3000);

/** 添加运行参数 */
function handlePushParams() {
  form.value = {};
  dialogFormVisible.value = true;
}

// 文件上传
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.params_content = jsonStr;
      form.params_content_v2 = res;
      formRef.value.validateField("params_content");
      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.params_content = "";
    form.params_content_v2 = "{}";
    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.params_content = "";
  form.params_content_v2 = "{}";
  fileStatus.value = false;
}

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

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

/** 查看运行参数详情 */
function handleDetail(row: { [key: string]: any }) {
  infoLoading.value = true;
  ToolChainshApi.paramsInfo(row.params_id)
    .then((res) => {
      //JSON转换
      res.data.data.params_content_v2 = JSON.stringify(res.data.data.params_content);
      dataInfo.value = res.data.data;
      dialogInfoVisible.value = true;
    })
    .finally(() => {
      infoLoading.value = false;
    });
}

/** 删除运行参数数据 */
function handleDelete(row: { [key: string]: any }) {
  ElMessageBox.confirm("确认删除运行参数信息?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    ToolChainshApi.deleteTool(row.tool_id).then((res) => {
      ElMessage.error("缺少接口");
      handleQuery();
    });
  });
}

/** 初始化数据 */
function initData() {
  let id = route.query.id;
  ID.value = id;
  loading.value = true;
  ToolChainshApi.toolChains(id)
    .then((res) => {
      baseForm.value = res.data.data;
    })
    .finally(() => {
      loading.value = false;
    });
    handleQuery();
}

/** 查询运行参数列表 */
function handleQuery() {
  queryLoading.value = true;
  queryParams.tool_id = ID;
  ToolChainshApi.paramsList(queryParams)
    .then((res) => {
      pageData.value = res.data.data.ParamsList;
      total.value = res.data.data.total;
    })
    .finally(() => {
      queryLoading.value = false;
    });
}

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;
    }
  }
}
</style>
