<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          icon="plus"
          plain
          size="small"
          type="primary"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="upload"
          plain
          size="small"
          type="success"
          @click="handleImport"
          >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="refresh"
          plain
          size="small"
          type="warning"
          @click="getList"
          >刷新
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="view"
          plain
          size="small"
          type="info"
          @click="handleOpenThingsModel"
          >预览
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="download"
          plain
          size="small"
          type="success"
          @click="handleExport"
          >导出
        </el-button>
      </el-col>
    </el-row>
    <el-table :data="modelList" border size="small">
      <el-table-column align="center" label="名称" prop="modelName" />
      <el-table-column align="center" label="标识符" prop="identifier" />

      <!--      <el-table-column align="center" label="首页显示" prop="isTop">-->
      <!--        <template #default="{row}">-->
      <!--          {{ isTopMap.get(row.isTop) ?? "未知" }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column align="center" label="实时监测" prop="isMonitor">-->
      <!--        <template #default="{row}">-->
      <!--          {{ isMonitor.get(row.isMonitor) ?? "未知" }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column align="center" label="物模型类别" prop="type">
        <template #default="{ row }">
          <dict-tag
            :options="modelTypeDict"
            :value="[row.type]"
            effect="dark"
            size="small"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="数据类型" prop="datatype">
        <template #default="{ row }">
          <dict-tag
            :options="dataTypeDict"
            :value="[row.datatype]"
            effect="plain"
            size="small"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="只读数据" prop="isOnlyRead">
        <template #default="{ row }">
          <dict-tag
            :options="isOnlyReadDict"
            :value="[row.isOnlyRead]"
            effect="dark"
            size="small"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="left"
        class-name="specsColor"
        header-align="center"
        label="数据定义"
        min-width="150"
        prop="specs"
      >
        <template #default="{ row }">
          <div v-html="formatSpecsDisplay(row.specs)"></div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="物模型类别" prop="isMonitor">
        <template #default="{ row }">
          <el-button
            icon="Edit"
            link
            size="small"
            type="warning"
            @click="handleUpdate(row)"
            >修改
          </el-button>
          <el-button
            icon="delete"
            link
            size="small"
            type="danger"
            @click="handleDelete(row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改物模型对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模型名称" prop="modelName">
          <el-input
            v-model="form.modelName"
            placeholder="请输入物模型名称，例如：温度"
            style="width: 385px"
          />
        </el-form-item>
        <el-form-item label="标识符" prop="identifier">
          <el-input
            v-model="form.identifier"
            placeholder="请输入标识符，例如：temperature"
            style="width: 385px"
          />
        </el-form-item>
        <el-form-item label="模型类别" prop="type">
          <el-radio-group
            v-model="form.type"
            class="ios-style-radio"
            @change="typeChange(form.type)"
          >
            <el-radio-button :label="1">属性</el-radio-button>
            <el-radio-button :label="2">功能</el-radio-button>
            <el-radio-button :label="3">事件</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="只读数据" prop="isOnlyRead">
          <el-switch
            v-model="form.isOnlyRead"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            active-text=""
            inactive-text=""
          >
          </el-switch>
        </el-form-item>
        <!--        <el-form-item v-show="form.type !== 3" label="首页显示" prop="isTop">-->
        <!--          <el-switch v-model="form.isTop" :active-value="1" :inactive-value="0" active-color="#13ce66" active-text=""-->
        <!--                     inactive-text="">-->
        <!--          </el-switch>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item v-show="form.type === 1" label="实时监测" prop="isMonitor">-->
        <!--          <el-switch v-model="form.isMonitor" :active-value="1" :inactive-value="0" active-color="#13ce66"-->
        <!--                     active-text=""-->
        <!--                     inactive-text=""-->
        <!--                     @change="changeMonitor(form.isMonitor)"-->
        <!--          >-->
        <!--          </el-switch>-->
        <!--        </el-form-item>-->
        <el-divider></el-divider>
        <el-form-item label="数据类型" prop="datatype">
          <el-select
            v-model="form.datatype"
            placeholder="请选择数据类型"
            style="width: 175px"
            @change="dataTypeChange"
          >
            <el-option key="integer" label="整数" value="integer"></el-option>
            <el-option key="decimal" label="小数" value="decimal"></el-option>
            <el-option key="bool" label="布尔" value="bool"></el-option>
            <el-option key="enum" label="枚举" value="enum"></el-option>
            <el-option key="string" label="字符串" value="string"></el-option>
            <el-option key="array" label="数组" value="array"></el-option>
          </el-select>
        </el-form-item>

        <div v-if="form.datatype === 'integer' || form.datatype === 'decimal'">
          <el-form-item label="取值范围">
            <el-row>
              <el-col :span="9">
                <el-input
                  v-model="form.specs.min"
                  placeholder="最小值"
                  type="number"
                />
              </el-col>
              <el-col :span="2" align="center">到</el-col>
              <el-col :span="9">
                <el-input
                  v-model="form.specs.max"
                  placeholder="最大值"
                  type="number"
                />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="单位">
            <el-input
              v-model="form.specs.unit"
              placeholder="请输入单位，例如：℃"
              style="width: 385px"
            />
          </el-form-item>
          <el-form-item label="步长">
            <!--            oninput="value=value.replace(/[^0-9.]/,'')"-->
            <!--              :formatter="formatInput"-->
            <!--              oninput="value=value.replace(/[^0-9.]/g, '')"-->
            <el-input
              v-model="form.specs.step"
              :step="form.datatype === 'decimal' ? 0.1 : 1"
              placeholder="请输入步长，例如：1"
              style="width: 385px"
              type="number"
            />
          </el-form-item>
        </div>

        <div v-if="form.datatype === 'bool'">
          <el-form-item label="布尔值" prop="">
            <el-row style="margin-bottom: 10px">
              <el-col :span="9">
                <el-input
                  v-model="form.specs.falseText"
                  placeholder="例如：关闭"
                />
              </el-col>
              <el-col :offset="1" :span="10"> （0 值对应文本）</el-col>
            </el-row>
            <el-row>
              <el-col :span="9">
                <el-input
                  v-model="form.specs.trueText"
                  placeholder="例如：打开"
                />
              </el-col>
              <el-col :offset="1" :span="10"> （1 值对应文本）</el-col>
            </el-row>
          </el-form-item>
        </div>

        <div v-if="form.datatype === 'enum'">
          <el-form-item label="枚举项" prop="">
            <el-row
              v-for="(item, index) in form.specs.enumList"
              :key="`enum${index}`"
              style="margin-bottom: 10px"
            >
              <el-col :span="9">
                <el-input
                  v-model="item.value"
                  placeholder="参数值，例如：0"
                  type="number"
                />
              </el-col>
              <el-col :offset="1" :span="11">
                <el-input
                  v-model="item.text"
                  placeholder="参数描述，例如：中速档位"
                />
              </el-col>
              <el-col v-if="index !== 0" :offset="1" :span="2"
                ><a style="color: #f56c6c" @click="removeEnumItem(index)"
                  >删除</a
                ></el-col
              >
            </el-row>
            <div>
              + <a style="color: #409eff" @click="addEnumItem()">添加枚举项</a>
            </div>
          </el-form-item>
        </div>

        <div v-if="form.datatype === 'string'">
          <el-form-item label="最大长度" prop="">
            <el-row>
              <el-col :span="9">
                <el-input
                  v-model="form.specs.maxLength"
                  placeholder="例如：1024"
                  type="number"
                />
              </el-col>
              <el-col :offset="1" :span="14">（字符串的最大长度）</el-col>
            </el-row>
          </el-form-item>
        </div>

        <div v-if="form.datatype === 'array'">
          <el-form-item label="数组类型" prop="">
            <el-radio-group v-model="form.specs.arrayType">
              <el-radio label="int">int（整数）</el-radio>
              <el-radio label="double">double（小数）</el-radio>
              <el-radio label="string">string（字符串）</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="openJsonViewer"
      :title="title"
      append-to-body
      width="600px"
    >
      <div
        :style="{
          height: '60vh',
          overflowY: 'scroll',
          overflowX: 'hidden',
        }"
      >
        <json-viewer :expandDepth="4" :value="thingsModel" copyable expanded>
          <template #copy>复制</template>
        </json-viewer>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      v-model="upload.open"
      :title="upload.title"
      append-to-body
      width="400px"
    >
      <el-upload
        ref="uploadRef"
        :action="upload.url"
        :auto-upload="false"
        :disabled="upload.isUploading"
        :headers="upload.headers"
        :limit="1"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        accept=".json"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <!--            <div class="el-upload__tip">-->
            <!--              <el-checkbox-->
            <!--                v-model="upload.updateSupport"-->
            <!--              />-->
            <!--              是否更新已经存在的用户数据-->
            <!--            </div>-->
            <!--            <span>仅允许导入xls、xlsx格式文件。</span>-->
            <!--            <el-link-->
            <!--              :underline="false"-->
            <!--              style="font-size: 12px; vertical-align: baseline"-->
            <!--              type="primary"-->
            <!--              @click="importTemplate"-->
            <!--            >下载模板-->
            <!--            </el-link-->
            <!--            >-->
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useRoute } from "vue-router";
import { reactive, ref, toRefs, watch } from "vue";
import "vue3-json-viewer/dist/index.css";
import { JsonViewer } from "vue3-json-viewer";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addModel,
  delModel,
  getModel,
  listModel,
  updateModel,
} from "@/api/thingsmodel/model";
import { getToken } from "@/utils/auth";
import DictTag from "@/components/DictTag/index.vue";
import { dataTypeDict, isOnlyReadDict, modelTypeDict } from "@/constant/dict";

const emits = defineEmits(["model-updated"]);

const props = defineProps({
  product: {
    type: Object,
    required: true,
  },
  productId: {
    type: Number,
    required: true,
  },
  modelJson: {
    type: String,
  },
});
const { product, modelJson, productId } = toRefs(props);
const formRef = ref();
const uploadRef = ref();
const route = useRoute();
/**
 * 检查标识符唯一性
 */
const checkIdIsUnique = (rule, value, callback) => {
  if (
    modelList.value.findIndex(
      (el) => el.identifier === value && el.modelId !== form.value.modelId
    ) > -1
  ) {
    callback(new Error("同一产品下,标识符必须唯一"));
  }
  callback();
};

function formatInput(value) {
  const regex = /^[0-9.]*$/; // 只允许数字和小数点
  const lastChar = value.charAt(value.length - 1);
  if (!regex.test(lastChar)) {
    return value.slice(0, -1); // 将最后一个非法字符删除
  }
  return value;
}

function handleStepInput(value) {
  form.value.specs.step = form.value.specs.step.replace(/[^0-9.]/g, "");
}

const data = reactive({
  // 物模型
  thingsModel: {},
  queryParams: {
    // pageNum: 1,
    // pageSize: 100,
    modelName: null,
    productId: null,
    tenantId: null,
    identifier: null,
    type: null,
    datatype: null,
    specs: null,
    isTop: null,
    isMonitor: null,
  },
  form: {},
  rules: {
    // TODO: 标识符 id 不可重复
    modelName: [
      {
        required: true,
        message: "物模型名称不能为空",
        trigger: "blur",
      },
    ],
    identifier: [
      {
        required: true,
        message: "标识符，产品下唯一不能为空",
        trigger: "blur",
      },
      {
        validator: checkIdIsUnique,
        trigger: "change",
      },
      {
        validator: checkIdIsUnique,
        trigger: "blur",
      },
    ],
    datatype: [
      {
        required: true,
        message: "数据类型不能为空",
        trigger: "change",
      },
    ],
    specs: [
      {
        required: true,
        message: "数据定义不能为空",
        trigger: "blur",
      },
    ],
  },
});
const modelList = ref([]);
const { form, rules, queryParams, thingsModel } = toRefs(data);

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url:
    import.meta.env.VITE_APP_BASE_API +
    "/thingsmodel/model/importData/" +
    productId.value,
});

/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "system/user/importTemplate",
    {},
    `user_template_${new Date().getTime()}.xlsx`
  );
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value.handleRemove(file);
  if (response.code === 200) {
    ElMessageBox.alert(
      "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
      "导入结果",
      { dangerouslyUseHTMLString: true }
    );
    getList();
  } else {
    ElMessage.error(response.msg ?? "导入失败");
  }
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value.submit();
}

const open = ref(false); // 是否显示编辑对话框
const openJsonViewer = ref(false);
const title = ref("");

// watch(modelJson, (value) => {
//   if (value) {
//     try {
//       const { functions, events, properties } = JSON.parse(value);
//       modelList.value = [
//         ...properties.map((el) => ({
//           ...el,
//           modelType: "properties",
//           type: 1
//         })),
//         ...functions.map((el) => ({
//           ...el,
//           modelType: "functions",
//           type: 2
//         })),
//         ...events.map((el) => ({
//           ...el,
//           modelType: "events",
//           type: 3
//         }))
//       ];
//       modelList.value = modelList.value.sort(
//         (a, b) => b.createTime - a.createTime
//       );
//     } catch (e) {
//       console.log(e);
//     }
//   }
// });

const getList = () => {
  listModel(queryParams.value).then((response) => {
    modelList.value = response.rows;
  });
};

watch(
  productId,
  (value) => {
    if (!value) {
      return;
    }
    queryParams.value.productId = value;
    getList();
  },
  {
    immediate: true,
  }
);
const reset = () => {
  form.value = {
    templateId: null,
    templateName: null,
    userId: null,
    userName: null,
    tenantId: null,
    tenantName: null,
    identifier: null,
    type: 1,
    datatype: "integer",
    isSys: null,
    isTop: null,
    isMonitor: null,
    isOnlyRead: 0,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    specs: {
      enumList: [
        {
          value: "",
          text: "",
        },
      ],
      arrayType: "int",
    },
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const cancel = () => {
  open.value = false;
  reset();
};
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "新增物模型";
};

const handleUpdate = (row) => {
  reset();
  getModel(row.modelId).then((response) => {
    let tempForm = response.data;
    open.value = true;
    title.value = "修改物模型";
    // Json转对象
    tempForm.specs = JSON.parse(tempForm.specs);
    if (!tempForm.specs.enumList) {
      tempForm.specs.enumList = [
        {
          value: "",
          text: "",
        },
      ];
    }
    if (!tempForm.specs.arrayType) {
      tempForm.specs.arrayType = "int";
    }
    form.value = tempForm;
  });
};

/**
 * 导出物模型json
 */
const handleExport = () => {
  ElMessageBox.confirm(`是否确认导出物模型json?`)
    .then(() => {
      makeThingsModelObject();
      const jsonBlob = new Blob([JSON.stringify(thingsModel.value)], {
        type: "text/plain;charset=utf-8",
      });
      saveAs(jsonBlob, `things-model-${productId.value}.json`);
    })
    .catch(() => {});
};

/**
 * 删除
 * @param row
 */
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除`)
    .then(() => {
      // const _model = JSON.parse(modelJson.value);
      // const modelType = modelTypeMap.get(row.type);
      // _model[modelType] = _model[modelType].filter(
      //   (el) => el.modelId !== row.modelId
      // );
      return delModel(row.modelId);
    })
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    });
};
// 类型改变
const typeChange = (label) => {
  // if (label === 2 || label === 3) {
  //   form.value.isMonitor = 0;
  // }
  if (
    label === 1 &&
    form.value.datatype !== "integer" &&
    form.value.datatype !== "decimal"
  ) {
    form.value.datatype = "integer";
  }
};

const dataTypeChange = () => {};

// 实时监测改变
const changeMonitor = (isMonitor) => {
  if (
    isMonitor === 1 &&
    form.value.datatype !== "integer" &&
    form.value.datatype !== "decimal"
  ) {
    form.value.datatype = "integer";
  }
};

/**
 * 生成物模型json对象
 */
const makeThingsModelObject = () => {
  // 生成物模型
  thingsModel.value = {
    properties: [],
    functions: [],
    events: [],
  };
  for (let i = 0; i < modelList.value.length; i++) {
    let thingsItem = {};
    thingsItem.id = modelList.value[i].identifier;
    thingsItem.name = modelList.value[i].modelName;

    thingsItem.isTop = modelList.value[i].isTop;
    thingsItem.isMonitor = modelList.value[i].isMonitor;
    thingsItem.isOnlyRead = modelList.value[i].isOnlyRead;
    thingsItem.datatype = JSON.parse(modelList.value[i].specs);
    if (modelList.value[i].type === 1) {
      //属性
      // thingsItem.isTop = modelList.value[i].isTop;
      // thingsItem.isMonitor = modelList.value[i].isMonitor;
      // thingsItem.isOnlyRead = modelList.value[i].isOnlyRead;
      // thingsItem.datatype = JSON.parse(modelList.value[i].specs);
      thingsModel.value.properties.push(thingsItem);
    } else if (modelList.value[i].type === 2) {
      // 功能
      // thingsItem.isTop = modelList.value[i].isTop;
      // thingsItem.isMonitor = modelList.value[i].isMonitor;
      // thingsItem.isOnlyRead = modelList.value[i].isOnlyRead;
      // thingsItem.datatype = JSON.parse(modelList.value[i].specs);
      thingsModel.value.functions.push(thingsItem);
    } else if (modelList.value[i].type === 3) {
      // 事件
      // thingsItem.isTop = modelList.value[i].isTop;
      // thingsItem.isMonitor = modelList.value[i].isMonitor;
      // thingsItem.isOnlyRead = modelList.value[i].isOnlyRead;
      // thingsItem.datatype = JSON.parse(modelList.value[i].specs);
      thingsModel.value.events.push(thingsItem);
    }
  }
};

/**查看物模型 */
const handleOpenThingsModel = () => {
  makeThingsModelObject();
  title.value = "物模型";
  openJsonViewer.value = true;
};

/** 添加枚举项 */
const addEnumItem = () => {
  form.value.specs.enumList.push({
    value: "",
    text: "",
  });
};

/** 删除枚举项 */
const removeEnumItem = (index) => {
  form.value.specs.enumList.splice(index, 1);
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.value.modelId != null) {
        // 格式化specs
        // this.form.specs = this.formatThingsSpecs();
        form.value.specs = formatThingsSpecs();
        form.value.productId = product.value.productId;
        form.value.productName = product.value.productName;
        form.value.tenantId = product.value.tenantId;
        // form.value.updateTime = Date.now();
        // const _modelJson = JSON.parse(modelJson.value);
        // const modelType = modelTypeMap.get(form.value.type);
        // _modelJson[modelType].forEach((el, index) => {
        //   if (el.modelId === form.value.modelId) {
        //     _modelJson[modelType][index] = form.value;
        //   }
        // });
        // updateProduct({
        //   productId: product.value.productId,
        //   thingsModelsJson: JSON.stringify(_modelJson)
        // }).then((resp) => {
        //   ElMessage.success("修改成功");
        //   open.value = false;
        //   emits("model-updated");
        // });
        // if (this.form.type == 2) {
        //   this.form.isMonitor = 0;
        // } else if (this.form.type == 3) {
        //   this.form.isMonitor = 0;
        //   this.form.isTop = 0;
        // }
        updateModel(form.value).then((response) => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 格式化specs
        // form.value.modelId = uuidv4();
        form.value.specs = formatThingsSpecs();
        // form.value.createTime = Date.now();
        form.value.productId = product.value.productId;
        form.value.productName = product.value.productName;
        form.value.tenantId = product.value.tenantId;
        // if (form.value.type === 2) {
        //   form.value.isMonitor = 0;
        // } else if (form.value.type === 3) {
        //   form.value.isMonitor = 0;
        //   form.value.isTop = 0;
        // }
        addModel(form.value).then((response) => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
        // const _modelJson = JSON.parse(modelJson.value);
        // _modelJson.properties.forEach((el, idx) => {
        //   _modelJson.properties[idx] = {
        //     ...el, modelId: uuidv4()
        //   };
        // });
        // _modelJson.events.forEach((el, idx) => {
        //   _modelJson.events[idx] = {
        //     ...el, modelId: uuidv4()
        //   };
        // });
        // _modelJson.functions.forEach((el, idx) => {
        //   _modelJson.functions[idx] = {
        //     ...el, modelId: uuidv4()
        //   };
        // });
        // if (form.value.type === 1) {
        //   _modelJson.properties.push(form.value);
        // } else if (form.value.type === 2) {
        //   _modelJson.functions.push(form.value);
        // } else if (form.value.type === 3) {
        //   _modelJson.events.push(form.value);
        // } else {
        //   return;
        // }
        // updateProduct({
        //   productId: product.value.productId,
        //   thingsModelsJson: JSON.stringify(_modelJson)
        // }).then((resp) => {
        //   emits("model-updated");
        //   ElMessage.success("新增成功");
        //   open.value = false;
        // });
      }
    }
  });
};

/** 格式化显示数据定义 */
const formatSpecsDisplay = (json) => {
  let specs = JSON.parse(json);
  if (!specs) {
    return;
  }
  if (specs.type === "integer" || specs.type === "decimal") {
    return (
      "<span style='width:50%;display:inline-block;'>最大值：<span style=\"color:#F56C6C\">" +
      specs.max +
      '</span></span>最小值：<span style="color:#F56C6C">' +
      specs.min +
      "</span><br /><span style='width:50%;display:inline-block;'>步长：<span style=\"color:#F56C6C\">" +
      specs.step +
      '</span></span>单位：<span style="color:#F56C6C">' +
      specs.unit
    );
  } else if (specs.type === "string") {
    return (
      '最大长度：<span style="color:#F56C6C">' + specs.maxLength + "</span>"
    );
  } else if (specs.type === "array") {
    return (
      '数组类型：<span style="color:#F56C6C">' + specs.arrayType + "</span>"
    );
  } else if (specs.type === "enum") {
    let items = "";
    for (let i = 0; i < specs.enumList.length; i++) {
      items =
        items +
        "<span style='width:50%;display:inline-block;'>" +
        specs.enumList[i].value +
        "：<span style='color:#F56C6C'>" +
        specs.enumList[i].text +
        "</span></span>";
      if (i > 0 && i % 2 !== 0) {
        items = items + "<br />";
      }
    }
    return items;
  } else if (specs.type === "bool") {
    return (
      "<span style='width:50%;display:inline-block;'>0：<span style=\"color:#F56C6C\">" +
      specs.falseText +
      '</span></span>1：<span style="color:#F56C6C">' +
      specs.trueText
    );
  }
};

// 格式化物模型
const formatThingsSpecs = () => {
  let _data = {};
  _data.type = form.value.datatype;
  if (form.value.datatype === "integer" || form.value.datatype === "decimal") {
    _data.min = Number(form.value.specs.min);
    _data.max = Number(form.value.specs.max);
    _data.unit = form.value.specs.unit;
    _data.step = Number(form.value.specs.step);
  } else if (form.value.datatype === "string") {
    _data.maxLength = Number(form.value.specs.maxLength);
  } else if (form.value.datatype === "bool") {
    _data.falseText = form.value.specs.falseText;
    _data.trueText = form.value.specs.trueText;
  } else if (form.value.datatype === "array") {
    _data.arrayType = form.value.specs.arrayType;
  } else if (form.value.datatype === "enum") {
    _data.enumList = form.value.specs.enumList;
  }
  console.log(_data);
  return JSON.stringify(_data);
  // return _data;
};

function getModelData() {}

// getList();
</script>

<style scoped></style>
