<template>
  <BasicModal
    title="物模型TSL"
    :maskClosable="false"
    destroyOnClose
    v-bind="$attrs"
    width="55rem"
    @register="register"
    @ok="handleSubmit"
    okText="导出物模型"
    @cancel="handleCancel"
  >
    <TslContent :record="$props.record" ref="TslConRef" />
  </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';

  defineEmits(['register']);

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

  const TslConRef = ref<InstanceType<typeof TslContent>>();
  const isUpdate = 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 handleSubmit = () => {
    const value = TslConRef.value?.getFormData();
    if (!value) return;

    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);
  };
</script>

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