<template>
  <section class="kf-panels">
    <span :title="label" class="kf-p-label">{{ label }}</span>
    <div class="kf-p-body flex-row-start-center">
      <el-switch v-model="value" @change="switchChange" inline-prompt :active-text="activeText" :inactive-text="inactiveText"></el-switch>
    </div>
  </section>
</template>

<script setup>
import dataModel from '@/components/ui/model/data';
import { computed, ref, toRefs, watch } from 'vue';

const props = defineProps(['config', 'confData', 'label']);
const { config, confData, label } = toRefs(props);

const switchChange = (value, device, property) => {
  const props = {
    props: { deviceId: confData.value.deviceId },
  };
  dataModel.doControl(props, confData.value.model, null, value, config.value.name);
};

const getRealValue = () => {
  const incomingValue = config.value.value;
  let realValue;

  if (incomingValue == undefined) {
    realValue = false;
  } else if (typeof incomingValue === 'boolean') {
    realValue = incomingValue;
  } else {
    realValue = incomingValue == 'true';
  }
  return realValue;
};

const value = ref(getRealValue());

watch(props, () => {
  value.value = getRealValue();
}, { deep: true });

// 处理enums
const options = computed(() => {
  let ops = [];
  if (config.value.enumItems) {
    ops = config.value.enumItems.map(it => {
      return { label: it.label.zhCN, value: it.value };
    });
  }
  return ops;
});

const activeText = computed(() => {
  return options.value[0]?.label || '';
});

const inactiveText = computed(() => {
  return options.value[1]?.label || '';
});
</script>

<style lang="scss" scoped></style>
