<script lang="ts" setup>
/**
 * 创建企微应用群聊弹窗
 * 调 appchat/create，成功后回写本地 xk_oa_chat（chat_kind=应用群，source=接口创建）
 */
import { ref } from 'vue';

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

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

import { useVbenForm } from '#/adapter/form';

import { createOaAppChat } from '../api';

const gridApi = ref();

const [Form, formApi] = useVbenForm({
  wrapperClass: 'grid-cols-12',
  commonConfig: {
    formItemClass: 'col-span-12',
    componentProps: { class: 'w-full' },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'VbenInput',
      fieldName: 'name',
      label: '群名称',
      rules: 'required',
      componentProps: { placeholder: '应用群聊名称' },
    },
    {
      component: 'VbenInput',
      fieldName: 'owner',
      label: '群主 userid',
      rules: 'required',
      componentProps: { placeholder: '企微成员 userid' },
    },
    {
      component: 'Select',
      fieldName: 'userlist',
      label: '成员 userid',
      rules: 'selectRequired',
      help: '至少 2 人（含群主）；可输入后回车添加',
      componentProps: {
        mode: 'tags',
        placeholder: '输入 userid 后回车',
        tokenSeparators: [',', ' '],
      },
    },
    {
      component: 'VbenInput',
      fieldName: 'chatid',
      label: '指定 chatid',
      help: '选填；不填则由企微自动生成',
      componentProps: { placeholder: '选填' },
    },
  ],
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const e = await formApi.validate();
    if (!e.valid) return;
    const values = await formApi.getValues();
    const userlist = Array.isArray(values.userlist)
      ? values.userlist
      : String(values.userlist || '')
          .split(/[,，\s]+/)
          .filter(Boolean);
    modalApi.setState({ loading: true, confirmLoading: true });
    try {
      await createOaAppChat({
        platform_code: 'work_wechat_app',
        name: values.name,
        owner: values.owner,
        userlist,
        chatid: values.chatid || '',
      });
      message.success('应用群创建成功');
      gridApi.value?.reload?.() ?? gridApi.value?.query?.();
      modalApi.close();
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen) {
      formApi.resetForm();
    }
  },
});
</script>

<template>
  <Modal title="创建应用群聊" class="w-[40%]">
    <Form />
  </Modal>
</template>
