<!--
文件: drawerListener.vue
功能: 流程监听器配置抽屉，用于新增/编辑监听器配置
主要逻辑:
- 暴露 `open` 方法供父组件调用，接收操作类型（`ACTION.ADD` 或 `ACTION.EDIT`）及可选记录数据，用以打开抽屉并初始化表单。
- 根据 `form.value.type` 动态计算可选的 `eventOptions`（任务监听器与执行监听器的事件不同），并根据 `valueType` 计算表单中 `value` 字段的标签 `valueLabel`。
- 使用 `a-form` 管理表单字段（`name`、`status`、`type`、`event`、`valueType`、`value`）并通过 `rules` 做前端校验。
- 新增时初始化默认表单值；编辑时将传入记录填充到表单中。
- 提交时根据当前操作类型选择 `postBpmProcessListenerCreate` 或 `postBpmProcessListenerUpdate` 接口，调用成功后提示、关闭抽屉并通过 `submit` 事件通知父组件刷新列表。
- 使用 `useToggle` 管理抽屉打开/关闭及 `loading` 状态，使用 `formRef` 驱动表单校验与提交流程。
-->

<script setup lang="ts">
import type { Rule } from 'ant-design-vue/es/form';
import type { FormExpose } from 'ant-design-vue/es/form/Form';
import { useToggle } from '@vueuse/core';
import { message } from 'ant-design-vue';
import { postBpmProcessListenerCreate, postBpmProcessListenerUpdate } from '@/api/modules/bpmDefinition/bpMliuchengjiantingqibiaokongzhiqi';
import { ACTION, executionOptions, taskEventOptions, typeOptions } from '../enum';

defineOptions({
  name: 'DrawerListener',
});

const emit = defineEmits(['submit']);

const form = ref<API.BpmProcessListenerSaveReqVO | any>();
const eventOptions = computed(() => {
  if (form.value.type === 'task') {
    return taskEventOptions;
  }
  else if (form.value.type === 'execution') {
    return executionOptions;
  }
  return [];
});
const valueTypeOptions = [
  { label: '表达式', value: 'expression' },
  { label: '代理表达式', value: 'delegateExpression' },
  { label: 'Java类', value: 'class' },
];

const valueLabel = computed(() => {
  if (form.value.valueType === 'expression') {
    return '表达式';
  }
  else if (form.value.valueType === 'delegateExpression') {
    return '代理表达式';
  }
  else if (form.value.valueType === 'class') {
    return 'Java类';
  }
  return '值';
});
const rules: Record<string, Rule[]> = {
  name: [{ required: true, message: '请输入名字', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  event: [{ required: true, message: '请选择事件', trigger: ['blur', 'change'] }],
  valueType: [{ required: true, message: '请选择值类型', trigger: ['blur', 'change'] }],
  value: [{ required: true, message: '请输入值', trigger: 'blur' }],
};

const [open, setOpen] = useToggle(false);
const formRef = ref<FormExpose>();

const state = reactive({
  type: '',
});
async function onOpen(key: ACTION, record?: any) {
  state.type = key;
  setOpen(true);
  if (key === ACTION.ADD) {
    form.value = { name: '', status: 0, type: 'execution', valueType: undefined, event: undefined, value: '' };
  }
  else if (key === ACTION.EDIT && record) {
    form.value = { ...record };
  }
}

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

function onSubmit() {
  formRef.value?.validate().then(() => {
    setLoading(true);
    const params: any = { ...form.value };
    const request = state.type === ACTION.ADD ? postBpmProcessListenerCreate : postBpmProcessListenerUpdate;
    request(params).then((res: API.ResponseDataString) => {
      if (res.success) {
        message.success('操作成功！');
        setOpen(false);
        emit('submit');
      }
    }).finally(() => {
      setLoading(false);
    });
  });
}

function close() {
  setOpen(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
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 5 }"
    >
      <a-form-item label="名称" name="name">
        <a-input v-model:value="form.name" :maxlength="30" />
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="0">
            开启
          </a-radio>
          <a-radio :value="1">
            关闭
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="类型" name="type">
        <a-select v-model:value="form.type" placeholder="请选择类型" :options="typeOptions" @change="form.event = undefined" />
      </a-form-item>
      <a-form-item label="事件" name="event">
        <a-select v-model:value="form.event" :options="eventOptions" placeholder="请选择事件" />
      </a-form-item>
      <a-form-item label="值类型" name="valueType">
        <a-select v-model:value="form.valueType" :options="valueTypeOptions" placeholder="请选择值类型" />
      </a-form-item>
      <a-form-item :label="valueLabel" name="value">
        <a-input v-model:value="form.value" :maxlength="1000" />
      </a-form-item>
    </a-form>
    <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>
