<script setup lang="ts">
import type { TableProps } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import type { ExecutionListenerDetail, Field } from '../../../ts/flow.d';
import { useToggle } from '@vueuse/core';
import DrawerField from './two-level/drawerField.vue';

defineOptions({
  name: 'DrawerListener',
});
const emit = defineEmits(['submit']);

const drawerFieldRef = ref<InstanceType<typeof DrawerField>>();

const [open, setOpen] = useToggle(false);
const [loading, setLoading] = useToggle(false);

const taskEventOptions = [
  { label: '创建', value: 'create' },
  { label: '指派', value: 'assignment' },
  { label: '完成', value: 'complete' },
  { label: '删除', value: 'delete' },
  { label: '更新', value: 'update' },
  { label: '超时', value: 'timeout' },
];

const executionOptions = [
  { label: 'start', value: 'start' },
  { label: 'end', value: 'end' },
];

const eventOptions = ref<any[]>([]);

const lTypeOptions = [
  { label: 'Java类', value: 'class' },
  { label: '表达式', value: 'expression' },
  { label: '代理表达式', value: 'delegateExpression' },
  { label: '脚本', value: 'scriptFormat' },
];
const scriptTypeOptions = [
  { label: '内联脚本', value: 'inline' },
  { label: '外部脚本', value: 'external' },
];
const form = ref<ExecutionListenerDetail>({ field: [] });
const rules: Record<string, Rule[]> = {
  event: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  id: [{ required: true, message: '请输入监听器ID', trigger: ['blur'] }],
  lType: [{ required: true, message: '请输入监听器类型', trigger: 'blur' }],
  value: [{ required: true, message: '请输入', trigger: ['blur'] }],
  scriptFormat: [{ required: true, message: '请输入脚本格式', trigger: ['blur'] }],
  scriptType: [{ required: true, message: '请选择脚本类型', trigger: 'change' }],
  scriptContent: [{ required: true, message: '请输入脚本内容', trigger: ['blur'] }],
  resource: [{ required: true, message: '请输入资源地址', trigger: ['blur'] }],
};

const columns: TableProps['columns'] = [
  {
    title: '序号',
    key: 'index',
    customRender: (obj: { text: string, record: any, index: number }) => `${obj.index + 1}`,
  },
  {
    title: '字段名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '字段类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '字段值',
    dataIndex: 'value',
    key: 'value',
  },
  {
    title: '操作',
    key: 'action',
    dataIndex: 'action',
    width: 90,
    fixed: 'right',
  },
];

const listenerType = ref<string>('');
async function onOpen(type: string, optType: string, record?: ExecutionListenerDetail, index?: number) {
  listenerType.value = type;
  eventOptions.value = type === 'task' ? taskEventOptions : executionOptions;
  setOpen(true);
  if (optType === 'add') {
    form.value = { field: [] };
  }
  else if (optType === 'edit' && record) {
    form.value = { ...record };
    form.value.index = index;
  }
}

function handleListenerTypeChange(value: any) {
  form.value.lType = value;
}

function onAction(action: string, record?: any, index?: number) {
  if (action === 'add') {
    drawerFieldRef.value?.open('add');
  }
  else if (action === 'edit') {
    drawerFieldRef.value?.open('edit', record, index);
  }
  else if (action === 'delete') {
    if (index !== undefined && index >= 0) {
      form.value.field?.splice(index, 1);
    }
  }
}

function onSubmit() {
  // console.log('listener form:', form.value);
  setLoading(true);
  emit('submit', form.value);
  setLoading(false);
  setOpen(false);
}

function close() {
  setOpen(false);
}

// 第二层
const childrenDrawer = ref(false);
function onFieldSubmit(params: Field) {
  // console.log('field submit:', params, params.index);
  // 如果已经存在则更新，没有则添加
  const index = params.index !== undefined ? params.index : -1;
  if (index < 0) {
    form.value.field?.push({
      name: params.name,
      type: params.type,
      value: params.value,
    });
  }
  else {
    form.value.field![index] = {
      name: params.name,
      type: params.type,
      value: params.value,
    };
  }

  childrenDrawer.value = false;
}

defineExpose({
  open: onOpen,
});
</script>

<template>
  <a-drawer
    v-model:open="open"
    title="执行监听器"
    placement="right"
    :width="520"
    destroy-on-close
    :footer-style="{ textAlign: 'right' }"
    @close="close"
  >
    <a-form
      :model="form"
      :rules="rules"
      :label-col="{ span: 5 }"
    >
      <a-form-item label="事件类型" name="event">
        <a-select
          v-model:value="form.event"
          style="width: 100%;"
          placeholder="请选择事件类型"
          :options="eventOptions"
        />
      </a-form-item>
      <a-form-item v-if="listenerType === 'task'" label="监听器ID" name="id">
        <a-input v-model:value="form.id" :maxlength="30" />
      </a-form-item>
      <a-form-item label="监听器类型" name="lType">
        <a-select
          v-model:value="form.lType"
          style="width: 100%;"
          placeholder="监听器类型"
          :options="lTypeOptions"
          @change="handleListenerTypeChange"
        />
      </a-form-item>
      <a-form-item v-if="form.lType === 'class'" label="Java类" name="value">
        <a-input v-model:value="form.value" :maxlength="1000" />
      </a-form-item>
      <a-form-item v-if="form.lType === 'expression'" label="表达式" name="value">
        <a-input v-model:value="form.value" :maxlength="1000" />
      </a-form-item>
      <a-form-item v-if="form.lType === 'delegateExpression'" label="代理表达式" name="value">
        <a-input v-model:value="form.value" :maxlength="1000" />
      </a-form-item>
      <a-form-item v-if="form.lType === 'scriptFormat'" label="脚本格式" name="scriptFormat">
        <a-input v-model:value="form.scriptFormat" :maxlength="1000" />
      </a-form-item>
      <a-form-item v-if="form.lType === 'scriptFormat'" label="脚本类型" name="scriptType">
        <a-select
          v-model:value="form.scriptType"
          style="width: 100%;"
          placeholder="脚本类型"
          :options="scriptTypeOptions"
        />
      </a-form-item>
      <a-form-item v-if="form.scriptType === 'inline'" label="脚本内容" name="scriptContent">
        <a-input v-model:value="form.scriptContent" :maxlength="1000" />
      </a-form-item>
      <a-form-item v-if="form.scriptType === 'external'" label="资源地址" name="resource">
        <a-input v-model:value="form.resource" :maxlength="1000" />
      </a-form-item>
    </a-form>
    <a-divider />
    <div flex items-center justify-between>
      <div>注入字段</div>
      <a-button type="primary" size="small" @click="onAction('add')">
        添加字段
      </a-button>
    </div>
    <a-table
      :columns="columns"
      :data-source="form.field"
      size="small"
      :pagination="false"
      row-key="key"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'action'">
          <a @click="onAction('edit', record, index)">编辑</a>
          <a style=" margin-left: 8px;color: red;" @click="onAction('delete', record, index)">删除</a>
        </template>
      </template>
    </a-table>
    <DrawerField ref="drawerFieldRef" @submit="onFieldSubmit" />
    <template #footer>
      <a-space>
        <a-button @click="close">
          取消
        </a-button>
        <a-button type="primary" :loading="loading" @click="onSubmit">
          提交
        </a-button>
      </a-space>
    </template>
  </a-drawer>
</template>
