GenModbusCommandModal.vue 2.49 KB
<script lang="ts" setup>
  import { Button, Spin } from 'ant-design-vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { formSchemas, FormFieldsEnum } from './config';
  import { ref } from 'vue';
  import { unref } from 'vue';
  import { composeModbusModalData } from './util';
  import { ModbusCommandValueType } from './type';
  import { genModbusCommand } from '/@/api/task';
  import { isNullOrUnDef } from '/@/utils/is';

  const emit = defineEmits(['update:value']);

  const [registerModal] = useModal();

  const [registerForm, { getFieldsValue, validate }] = useForm({
    schemas: formSchemas,
    showActionButtonGroup: false,
    rowProps: { gutter: 10 },
    baseColProps: { span: 12 },
  });

  const commandValue = ref('');

  const loading = ref(false);
  const handleGetValue = async () => {
    try {
      await validate();
      const value = getFieldsValue();
      const record = composeModbusModalData(value as ModbusCommandValueType);

      if (record[FormFieldsEnum.REGISTER_VALUES]?.some((item) => isNullOrUnDef(item))) return;

      loading.value = true;
      const result = await genModbusCommand(record);
      commandValue.value = result;
    } catch (error) {
    } finally {
      loading.value = false;
    }
  };

  const formatCommand = (command: string, subNumber: number) => {
    const list = command.split('');
    let index = 0;
    const arr: string[][] = [];
    while (index <= list.length) {
      arr.push(list.slice(index, (index += subNumber)));
    }
    return arr.reduce((prev, next) => `${prev} ${next.join('')}`, '');
  };

  const handleOk = async () => {
    emit('update:value', unref(commandValue));
  };
</script>

<template>
  <BasicModal
    @register="registerModal"
    :okButtonProps="{ loading }"
    title="配置操作"
    @ok="handleOk"
  >
    <BasicForm @register="registerForm" class="create-tcp-command-form" />
    <section>
      <Button @click="handleGetValue" type="link" class="!px-0">生成预览</Button>
      <div>
        <div class="text-gray-400">Modbus 指令预览</div>
        <Spin :spinning="loading" size="small">
          <div class="bg-dark-50 text-light-50 p-1 w-full block mt-1 min-h-8">{{
            formatCommand(commandValue, 2)
          }}</div>
        </Spin>
      </div>
    </section>
  </BasicModal>
</template>

<style lang="less" scoped>
  .create-tcp-command-form {
    :deep(.ant-input-number) {
      width: 100%;
      min-width: 0;
    }
  }
</style>