<script lang="ts" setup>
import { useElementsInfoStore } from '../../stores/elementsInfo.ts';
import { useSelectedInfoStore } from '../../stores/selectedInfo.ts';

import DrawerMessage from './drawer/drawerMessage.vue';
import DrawerSignal from './drawer/drawerSignal.vue';

defineOptions({ name: 'ExecutionListener' });

const elementsInfoStore = useElementsInfoStore();
const selectedInfoStore = useSelectedInfoStore();

const elementInfo = computed(() => {
  return elementsInfoStore.getElementById(selectedInfoStore.selectId) || {};
});

const messageColumns = [{
  title: '序号',
  key: 'index',
  customRender: (obj: { text: string, record: any, index: number }) => `${obj.index + 1}`,
}, {
  title: '消息ID',
  dataIndex: 'messageId',
  key: 'messageId',
}, {
  title: '消息名称',
  dataIndex: 'messageName',
  key: 'messageName',
}];

const signalColumns = [{
  title: '序号',
  key: 'index',
  customRender: (obj: { text: string, record: any, index: number }) => `${obj.index + 1}`,
}, {
  title: '信号ID',
  dataIndex: 'signalId',
  key: 'signalId',
}, {
  title: '信号名称',
  dataIndex: 'signalName',
  key: 'signalName',
}];

const messageData = ref<any[]>(elementInfo.value.messageList ?? []);
const signalData = ref<any[]>(elementInfo.value.signalList ?? []);

const drawerMessageRef = ref<InstanceType<typeof DrawerMessage>>();
const drawerSignalRef = ref<InstanceType<typeof DrawerSignal>>();

function addMessage() {
  drawerMessageRef.value?.open();
}

function addSignal() {
  drawerSignalRef.value?.open();
}

watch(() => messageData.value, () => {
  elementsInfoStore.updateElement(elementInfo.value.id, {
    messageList: messageData.value,
  });
}, { deep: true });
watch(() => signalData.value, () => {
  elementsInfoStore.updateElement(elementInfo.value.id, {
    signalList: signalData.value,
  });
}, { deep: true });

function reloadMessageData(item: any) {
  messageData.value.push(item);
}

function reloadSignalData(item: any) {
  signalData.value.push(item);
}
</script>

<template>
  <div>
    <div mb-10px flex justify-between items-center>
      <div>消息列表</div>
      <a-button size="small" type="primary" @click="addMessage">
        创建新消息
      </a-button>
    </div>
    <a-table
      size="small"
      :columns="messageColumns"
      :data-source="messageData"
      :pagination="false"
      row-key="key"
    />
    <div my-10px flex justify-between items-center>
      <div>信号列表</div>
      <a-button size="small" type="primary" @click="addSignal">
        创建新信号
      </a-button>
    </div>
    <a-table
      size="small"
      :columns="signalColumns"
      :data-source="signalData"
      :pagination="false"
      row-key="key"
    />
    <DrawerMessage ref="drawerMessageRef" @submit="reloadMessageData" />
    <DrawerSignal ref="drawerSignalRef" @submit="reloadSignalData" />
  </div>
</template>
