index.vue 2.17 KB
<script lang="ts" setup>
  import { ComponentPropsConfigType, DataFetchUpdateFn } from '/@/views/visual/packages/index.type';
  import { option } from './config';
  import { useDataFetch } from '/@/views/visual/packages/hook/useSocket';
  import { SvgIcon } from '/@/components/Icon';
  import { Switch } from 'ant-design-vue';
  import { computed, ref } from 'vue';
  import { useComponentScale } from '../../../hook/useComponentScale';
  import { useSendCommand } from '../../../hook/useSendCommand';
  import { unref } from 'vue';

  const props = defineProps<{
    config: ComponentPropsConfigType<typeof option>;
  }>();

  const checked = ref(false);

  const getDesign = computed(() => {
    const { option, persetOption } = props.config;
    const { componentInfo, attribute, attributeRename } = option;
    const { icon: presetIcon, iconColor: presetIconColor } = persetOption || {};
    const { icon, iconColor } = componentInfo || {};
    return {
      icon: icon ?? presetIcon,
      iconColor: iconColor || presetIconColor,
      attribute: attributeRename || attribute,
    };
  });

  const { sendCommand, loading } = useSendCommand();
  const handleChange = async () => {
    const flag = await sendCommand(props.config.option, unref(checked));
    if (!flag) checked.value = !unref(checked);
  };

  const updateFn: DataFetchUpdateFn = (message, attribute) => {
    const { data = {} } = message;
    const [latest] = data[attribute] || [];
    const [_, value] = latest;
    checked.value = isNaN(value as unknown as number) ? false : !!Number(value);
  };

  useDataFetch(props, updateFn);
  const { getScale } = useComponentScale(props);
</script>

<template>
  <main class="w-full h-full flex justify-center items-center" :style="getScale">
    <div class="flex flex-col justify-center items-center mr-20">
      <SvgIcon
        :name="getDesign.icon"
        prefix="iconfont"
        :style="{ color: getDesign.iconColor }"
        :size="50"
      />
      <span class="mt-3 truncate text-gray-500 text-xs text-center">
        {{ getDesign.attribute || '属性' }}
      </span>
    </div>
    <Switch v-model:checked="checked" :loading="loading" @change="handleChange" />
  </main>
</template>