PhysicalModelTsl.vue 2.85 KB
<template>
  <BasicModal
    title="物模型TSL"
    :maskClosable="false"
    destroyOnClose
    v-bind="$attrs"
    width="55rem"
    :okButtonProps="{ loading }"
    @register="register"
    @ok="handleSubmit"
    okText="导出物模型"
    @cancel="handleCancel"
  >
    <TslContent :record="record" ref="TslConRef" />
    <template #centerFooter>
      <Button type="primary" :loading="loading" @click="handleExportAll">导出全部</Button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import TslContent from './cpns/TslContent.vue';
  import { DeviceRecord } from '/@/api/device/model/deviceModel';
  import { Button } from 'ant-design-vue';
  import { getModelTsl } from '/@/api/device/modelOfMatter';
  import { FunctionType } from './cpns/config';

  defineEmits(['register']);

  const props = defineProps<{
    record: DeviceRecord;
  }>();

  const TslConRef = ref<InstanceType<typeof TslContent>>();
  const isUpdate = ref(false);

  const loading = ref(false);

  const [register, { closeModal, setModalProps }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: true });
    isUpdate.value = data.isUpdate;
    setModalProps({ confirmLoading: false });
    // const jsCode = TslConRef?.value.aceEditor.getValue();
    // TslConRef?.value.aceEditor.setValue(jsCode);
  });

  const handleCancel = () => {
    TslConRef.value?.resetFormData();
    closeModal();
  };

  const exportJSONFile = (value: Recordable) => {
    const blob = new Blob([JSON.stringify(value, null, 2)], { type: 'text/json' });
    const objectURL = URL.createObjectURL(blob);
    const element = document.createElement('a');
    element.href = objectURL;
    element.download = `${props.record.name}-model.json`;
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    element.remove();
    URL.revokeObjectURL(objectURL);
  };

  const handleSubmit = () => {
    const value = TslConRef.value?.getFormData();
    if (!value) return;
    exportJSONFile(value);
  };

  const getAllModel = () => {
    const { id: deviceProfileId } = props.record;
    return Promise.all([
      getModelTsl({ deviceProfileId, functionType: FunctionType.EVENTS }),
      getModelTsl({ deviceProfileId, functionType: FunctionType.PROPERTIES }),
      getModelTsl({ deviceProfileId, functionType: FunctionType.SERVICE }),
    ]);
  };

  const handleExportAll = async () => {
    loading.value = true;
    try {
      const [events, properties, services] = await getAllModel();
      const value = { properties, services, events };
      exportJSONFile(value);
    } catch (error) {
      throw error;
    } finally {
      loading.value = false;
    }
  };
</script>

<style lang="less" scope>
  #jsoneditor {
    width: 100%;
    height: 450px;
  }
</style>