<script lang="ts" setup>
import type { TableColumnType } from 'ant-design-vue';
import type { ExecutionListenerDetail } from '../../ts/flow.d';
import { useElementsInfoStore } from '../../stores/elementsInfo.ts';
import { useSelectedInfoStore } from '../../stores/selectedInfo.ts';

import DrawerListener from './drawer/drawerListener.vue';
import DrawerTaskListenerTable from './drawer/drawerListenerTable.vue';

defineOptions({ name: 'TaskListener' });

const lf: any = inject('lf');

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

const taskListenerList = ref<ExecutionListenerDetail[]>([]);

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

watch(elementInfo, (val: any) => {
  taskListenerList.value = val.taskListener || [];
}, { immediate: true });

const drawerListenerRef = ref<InstanceType<typeof DrawerListener>>();
const drawerListenerTableRef = ref<InstanceType<typeof DrawerTaskListenerTable>>();

const taskEventOptions = [
  { label: '创建', value: 'create' },
  { label: '指派', value: 'assignment' },
  { label: '完成', value: 'complete' },
  { label: '删除', value: 'delete' },
  { label: '更新', value: 'update' },
  { label: '超时', value: 'timeout' },
];
const columns: TableColumnType[] = [{
  title: '序号',
  key: 'index',
  customRender: (obj: { text: string, record: any, index: number }) => `${obj.index + 1}`,
}, {
  title: '事件类型',
  dataIndex: 'event',
  key: 'event',
  customRender: (obj: { text: string, record: any, index: number }) => {
    const eventLabel = taskEventOptions.find(item => item.value === obj.text)?.label;
    return eventLabel || obj.text;
  },
}, {
  title: '事件ID',
  dataIndex: 'id',
  key: 'id',
}, {
  title: '监听器类型',
  dataIndex: 'lType',
  key: 'lType',
  customRender: (obj: { text: string, record: any, index: number }) => {
    return obj.text === 'class'
      ? 'Java类'
      : obj.text === 'expression'
        ? '表达式'
        : obj.text === 'delegateExpression'
          ? '代理表达式'
          : obj.text === 'scriptFormat' ? '脚本' : obj.text;
  },
}, {
  title: '操作',
  key: 'action',
  width: 90,
}];

function onAction(type: string, record?: ExecutionListenerDetail, index?: number) {
  if (type === 'add') {
    drawerListenerRef.value?.open('task', 'add');
  }
  else if (type === 'edit') {
    drawerListenerRef.value?.open('task', 'edit', record, index);
  }
  else if (type === 'delete') {
    // 删除操作
    // console.log('删除监听器');
    if (index !== undefined && index >= 0) {
      taskListenerList.value.splice(index, 1);
    }
  }
}

function onListenerSubmit(params: ExecutionListenerDetail) {
  const index = params.index !== undefined ? params.index : -1;
  if (index < 0) {
    taskListenerList.value.push({
      ...params,
    });
  }
  else {
    taskListenerList.value[index] = {
      ...params,
    };
  }
}

function onListenerChoose(listener: any) {
  const params = {
    event: listener.event,
    lType: listener.valueType,
    value: listener.value,
    field: [],
  };
  taskListenerList.value.push(params);
}

watch(() => taskListenerList.value, (newVal: any) => {
  // console.log('监听器列表更新：', newVal);
  elementsInfoStore.updateElement(selectedInfoStore.selectId, {
    taskListener: newVal,
  });
  lf.value.setProperties(selectedInfoStore.selectId, {
    taskListener: newVal,
  });
}, { deep: true });
</script>

<template>
  <div>
    <a-space mb-10px>
      <a-button size="small" type="primary" @click="onAction('add')">
        添加监听器
      </a-button>
      <a-button size="small" type="primary" @click="drawerListenerTableRef?.open('task')">
        选择监听器
      </a-button>
    </a-space>
    <a-table
      size="small"
      :columns="columns"
      :data-source="taskListenerList"
      :pagination="false"
      row-key="key"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="onAction('edit', record, index)">编辑</a>
            <a style=" margin-left: 8px;color: red;" @click="onAction('delete', record, index)">删除</a>
          </a-space>
        </template>
      </template>
    </a-table>
    <DrawerListener ref="drawerListenerRef" @submit="onListenerSubmit" />
    <DrawerTaskListenerTable ref="drawerListenerTableRef" @submit="onListenerChoose" />
  </div>
</template>
