<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  createOaChat,
  updateOaChat,
} from '#/views/system/oa-chat/api';
import { modalFormProps } from '#/views/system/oa-chat/config/form';
import { getOaPlatformList } from '#/views/system/oa-platform/api';

/**
 * OA 群聊新增/编辑弹窗
 *
 * 关键交互：
 * - 打开弹窗时动态拉取平台选项注入 platform_code 单选按钮组
 * - 已禁用平台在 label 上加后缀标记并禁用选择（保持与机器人弹窗一致）
 * - external_id / sort / status 为选填字段，留空时由后端取默认值
 */

const isUpdate = ref(false);
const gridApi = ref();

const [Form, formApi] = useVbenForm(modalFormProps);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = isUpdate.value ? updateOaChat : createOaChat;
        submitApi(values)
          .then(() => {
            message.success('保存成功');
            gridApi.value?.reload();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen) {
      const { values, update } = modalApi.getData<Record<string, any>>();
      if (values) {
        isUpdate.value = update;
        formApi.setValues(values);
      }
      // 每次打开都重新拉取平台列表，保证平台启用状态最新
      loadPlatformOptions();
    }
  },
});

/**
 * 拉取平台列表并注入到表单的 platform_code 单选按钮组
 * - 显示全部平台（含已禁用的，便于历史数据回显）
 * - 已禁用平台在 label 上加后缀标记并禁用选择
 */
async function loadPlatformOptions() {
  try {
    const list = await getOaPlatformList();
    const rows: any[] = Array.isArray(list) ? list : list?.data || [];
    const options = rows.map((item) => ({
      label: item.enabled === 1 ? item.name : `${item.name}（已禁用）`,
      value: item.platform_code,
      disabled: item.enabled !== 1,
    }));
    formApi.updateSchema([
      {
        fieldName: 'platform_code',
        componentProps: { options },
      },
    ]);
  } catch (e) {
    console.error('加载平台列表失败', e);
  }
}
</script>

<template>
  <Modal :title="`${isUpdate === true ? '编辑' : '新增'}群聊`" class="w-[40%]">
    <Form />
  </Modal>
</template>
