123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484 |
- import { ChatContext } from '@/app/chat-context';
- import {
- apiInterceptors,
- delApp,
- getAppAdmins,
- getAppList,
- newDialogue,
- publishApp,
- unPublishApp,
- updateAppAdmins,
- } from '@/client/api';
- import BlurredCard, { ChatButton, InnerDropdown } from '@/new-components/common/blurredCard';
- import ConstructLayout from '@/new-components/layout/Construct';
- import { IApp } from '@/types/app';
- import { BulbOutlined, DingdingOutlined, PlusOutlined, SearchOutlined, WarningOutlined } from '@ant-design/icons';
- import { useDebounceFn, useRequest } from 'ahooks';
- import { App, Avatar, Button, Input, Modal, Pagination, Popover, Segmented, SegmentedProps, Select, Spin, Tag } from 'antd';
- import copy from 'copy-to-clipboard';
- import moment from 'moment';
- import { useRouter } from 'next/router';
- import { useCallback, useContext, useEffect, useRef, useState } from 'react';
- import { useTranslation } from 'react-i18next';
- import CreateAppModal from './components/create-app-modal';
- type TabKey = 'all' | 'published' | 'unpublished';
- type ModalType = 'edit' | 'add';
- export default function AppContent() {
- const { t } = useTranslation();
- const [open, setOpen] = useState<boolean>(false);
- const [spinning, setSpinning] = useState<boolean>(false);
- const [activeKey, setActiveKey] = useState<TabKey>('all');
- const [apps, setApps] = useState<IApp[]>([]);
- const [modalType, setModalType] = useState<ModalType>('add');
- const { model, setAgent: setAgentToChat, setCurrentDialogInfo } = useContext(ChatContext);
- const router = useRouter();
- const { openModal = '' } = router.query;
- const [filterValue, setFilterValue] = useState('');
- const [curApp] = useState<IApp>();
- const [adminOpen, setAdminOpen] = useState<boolean>(false);
- const [admins, setAdmins] = useState<string[]>([]);
- // 分页信息
- const totalRef = useRef<{
- current_page: number;
- total_count: number;
- total_page: number;
- }>();
- // 区分是单击还是双击
- const [clickTimeout, setClickTimeout] = useState(null);
- const { message } = App.useApp();
- const handleCreate = () => {
- setModalType('add');
- setOpen(true);
- localStorage.removeItem('new_app_info');
- };
- const handleEdit = (app: any) => {
- localStorage.setItem('new_app_info', JSON.stringify({ ...app, isEdit: true }));
- router.push(`/construct/app/extra`);
- };
- const getListFiltered = useCallback(() => {
- let published = undefined;
- if (activeKey === 'published') {
- published = 'true';
- }
- if (activeKey === 'unpublished') {
- published = 'false';
- }
- initData({ app_name: filterValue, published });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [activeKey, filterValue]);
- const handleTabChange = (activeKey: string) => {
- setActiveKey(activeKey as TabKey);
- };
- // 发布或取消发布应用
- const { run: operate } = useRequest(
- async (app: IApp) => {
- if (app.published === 'true') {
- return await apiInterceptors(unPublishApp(app.app_code));
- } else {
- return await apiInterceptors(publishApp(app.app_code));
- }
- },
- {
- manual: true,
- onSuccess: data => {
- if (data[2]?.success) {
- message.success('操作成功');
- }
- getListFiltered();
- },
- },
- );
- const initData = useDebounceFn(
- async params => {
- setSpinning(true);
- const obj: any = {
- page: 1,
- page_size: 12,
- ...params,
- };
- const [error, data] = await apiInterceptors(getAppList(obj));
- if (error) {
- setSpinning(false);
- return;
- }
- if (!data) return;
- console.log(data?.app_list);
-
- setApps(data?.app_list || []);
- totalRef.current = {
- current_page: data?.current_page || 1,
- total_count: data?.total_count || 0,
- total_page: data?.total_page || 0,
- };
- setSpinning(false);
- },
- {
- wait: 500,
- },
- ).run;
- const showDeleteConfirm = (app: IApp) => {
- Modal.confirm({
- title: t('Tips'),
- icon: <WarningOutlined />,
- content: `do you want delete the application?`,
- okText: 'Yes',
- okType: 'danger',
- cancelText: 'No',
- async onOk() {
- await apiInterceptors(delApp({ app_code: app.app_code }));
- getListFiltered();
- },
- });
- };
- useEffect(() => {
- if (openModal) {
- setModalType('add');
- setOpen(true);
- }
- }, [openModal]);
- const languageMap = {
- en: t('English'),
- zh: t('Chinese'),
- };
- const handleChat = async (app: IApp) => {
- // 原生应用跳转
- if (app.team_mode === 'native_app') {
- const { chat_scene = '' } = app.team_context;
- const [, res] = await apiInterceptors(newDialogue({ chat_mode: chat_scene }));
- if (res) {
- setCurrentDialogInfo?.({
- chat_scene: res.chat_mode,
- app_code: app.app_code,
- });
- localStorage.setItem(
- 'cur_dialog_info',
- JSON.stringify({
- chat_scene: res.chat_mode,
- app_code: app.app_code,
- }),
- );
- router.push(`/chat?scene=${chat_scene}&id=${res.conv_uid}${model ? `&model=${model}` : ''}`);
- }
- } else {
- // 自定义应用
- const [, res] = await apiInterceptors(newDialogue({ chat_mode: 'chat_agent' }));
- if (res) {
- setCurrentDialogInfo?.({
- chat_scene: res.chat_mode,
- app_code: app.app_code,
- });
- localStorage.setItem(
- 'cur_dialog_info',
- JSON.stringify({
- chat_scene: res.chat_mode,
- app_code: app.app_code,
- }),
- );
- setAgentToChat?.(app.app_code);
- router.push(`/chat/?scene=chat_agent&id=${res.conv_uid}${model ? `&model=${model}` : ''}`);
- }
- }
- };
- const items: SegmentedProps['options'] = [
- {
- value: 'all',
- label: t('apps'),
- },
- {
- value: 'published',
- label: t('published'),
- },
- {
- value: 'unpublished',
- label: t('unpublished'),
- },
- ];
- const onSearch = async (e: any) => {
- const v = e.target.value;
- setFilterValue(v);
- };
- // 获取应用权限列表
- const { run: getAdmins, loading } = useRequest(
- async (appCode: string) => {
- const [, res] = await apiInterceptors(getAppAdmins(appCode));
- return res ?? [];
- },
- {
- manual: true,
- onSuccess: data => {
- setAdmins(data);
- },
- },
- );
- // 更新应用权限
- const { run: updateAdmins, loading: adminLoading } = useRequest(
- async (params: { app_code: string; admins: string[] }) => await apiInterceptors(updateAppAdmins(params)),
- {
- manual: true,
- onSuccess: () => {
- message.success('更新成功');
- },
- },
- );
- const handleChange = async (value: string[]) => {
- setAdmins(value);
- await updateAdmins({
- app_code: curApp?.app_code || '',
- admins: value,
- });
- await initData();
- };
- useEffect(() => {
- if (curApp) {
- getAdmins(curApp.app_code);
- }
- }, [curApp, getAdmins]);
- useEffect(() => {
- getListFiltered();
- }, [getListFiltered]);
- // 单击复制分享钉钉链接
- const shareDingding = (item: IApp) => {
- if (clickTimeout) {
- clearTimeout(clickTimeout);
- setClickTimeout(null);
- }
- const timeoutId = setTimeout(() => {
- const mobileUrl = `${location.origin}/mobile/chat/?chat_scene=${item?.team_context?.chat_scene || 'chat_agent'}&app_code=${item.app_code}`;
- const dingDingUrl = `dingtalk://dingtalkclient/page/link?url=${encodeURIComponent(mobileUrl)}&pc_slide=true`;
- const result = copy(dingDingUrl);
- if (result) {
- message.success('复制成功');
- } else {
- message.error('复制失败');
- }
- setClickTimeout(null);
- }, 300); // 双击时间间隔
- setClickTimeout(timeoutId as any);
- };
- // 双击直接打开钉钉
- const openDingding = (item: IApp) => {
- if (clickTimeout) {
- clearTimeout(clickTimeout);
- setClickTimeout(null);
- }
- const mobileUrl = `${location.origin}/mobile/chat/?chat_scene=${item?.team_context?.chat_scene || 'chat_agent'}&app_code=${item.app_code}`;
- const dingDingUrl = `dingtalk://dingtalkclient/page/link?url=${encodeURIComponent(mobileUrl)}&pc_slide=true`;
- window.open(dingDingUrl);
- };
- return (
- <ConstructLayout>
- <Spin spinning={spinning}>
- <div className='h-screen w-full px-4 bg-[#fff] overflow-y-auto mt-0'>
- <div className='mt-2 rounded-[10px] flex h-16 justify-between items-center px-2'>
- <Input
- variant='filled'
- prefix={<SearchOutlined />}
- placeholder={t('please_enter_the_keywords')}
- onChange={onSearch}
- onPressEnter={onSearch}
- allowClear
- className='w-[400px] h-[40px]
- border-1 border-[#d1d1d1]
- backdrop-filter
- backdrop-blur-lg
- dark:border-[#6f7f95]
- dark:bg-[#6f7f95]
- dark:bg-opacity-60'
- />
- <span className='flex gap-2 items-center'>
- <Avatar className='bg-gradient-to-tr from-[#31afff] to-[#1677ff] cursor-pointer'>
- </Avatar>
- <span
- >
- admin
- </span>
- </span>
- </div>
- <div className='rounded-[10px] h-full mt-4 relative bg-slate-200 p-4 border-1 mb-2'>
- <div className='flex justify-between items-center'>
- <Segmented
- className='backdrop-filter h-10 backdrop-blur-lg bg-white bg-opacity-30 border border-white rounded-lg shadow p-1 dark:border-[#6f7f95] dark:bg-[#6f7f95] dark:bg-opacity-60'
- options={items as any}
- onChange={handleTabChange}
- value={activeKey}
- />
- <Button
- className='border-none text-white bg-button-gradient flex items-center'
- onClick={handleCreate}
- >
- {'创建应用'}
- </Button>
- </div>
- <div className='w-full flex flex-wrap pb-12 mx-[-8px]'>
- {apps.map(item => {
- return (
- <BlurredCard
- key={item.app_code}
- code={item.app_code}
- name={item.app_name}
- description={item.app_describe}
- RightTop={
- <div className='flex items-center gap-2'>
- <Popover
- content={
- <div className='flex flex-col gap-2'>
- <div className='flex items-center gap-2'>
- <BulbOutlined
- style={{
- color: 'rgb(252,204,96)',
- fontSize: 12,
- }}
- />
- <span className='text-sm text-gray-500'>{t('copy_url')}</span>
- </div>
- <div className='flex items-center gap-2'>
- <BulbOutlined
- style={{
- color: 'rgb(252,204,96)',
- fontSize: 12,
- }}
- />
- <span className='text-sm text-gray-500'>{t('double_click_open')}</span>
- </div>
- </div>
- }
- >
- <DingdingOutlined
- className='cursor-pointer text-[#0069fe] hover:bg-white hover:dark:bg-black p-2 rounded-md'
- onClick={() => shareDingding(item)}
- onDoubleClick={() => openDingding(item)}
- />
- </Popover>
- <InnerDropdown
- menu={{
- items: [
- {
- key: 'publish',
- label: (
- <span
- onClick={e => {
- e.stopPropagation();
- operate(item);
- }}
- >
- {item.published === 'true' ? t('unpublish') : t('publish')}
- </span>
- ),
- },
- {
- key: 'del',
- label: (
- <span
- className='text-red-400'
- onClick={e => {
- e.stopPropagation();
- showDeleteConfirm(item);
- }}
- >
- {t('Delete')}
- </span>
- ),
- },
- ],
- }}
- />
- </div>
- }
- Tags={
- <div>
- <Tag>{languageMap[item.language]}</Tag>
- <Tag>{item.team_mode}</Tag>
- <Tag>{item.published === 'true' ? t('published') : t('unpublished')}</Tag>
- </div>
- }
- rightTopHover={false}
- LeftBottom={
- <div className='flex gap-2'>
- <span>{item.owner_name}</span>
- <span>•</span>
- {item?.updated_at && <span>{moment(item?.updated_at).fromNow() + ' ' + t('update')}</span>}
- </div>
- }
- RightBottom={
- <ChatButton
- onClick={() => {
- handleChat(item);
- }}
- />
- }
- onClick={() => {
- handleEdit(item);
- }}
- scene={item?.team_context?.chat_scene || 'chat_agent'}
- />
- );
- })}
- <div className='w-full flex justify-end shrink-0 pb-12'>
- <Pagination
- total={totalRef.current?.total_count || 0}
- pageSize={12}
- current={totalRef.current?.current_page}
- onChange={async (page, _page_size) => {
- await initData({ page });
- }}
- />
- </div>
- </div>
- </div>
- {open && (
- <CreateAppModal
- open={open}
- onCancel={() => {
- setOpen(false);
- }}
- refresh={initData}
- type={modalType}
- />
- )}
- </div>
- </Spin>
- <Modal title='权限管理' open={adminOpen} onCancel={() => setAdminOpen(false)} footer={null}>
- <Spin spinning={loading}>
- <div className='py-4'>
- <div className='mb-1'>管理员(工号,去前缀0):</div>
- <Select
- mode='tags'
- value={admins}
- style={{ width: '100%' }}
- onChange={handleChange}
- tokenSeparators={[',']}
- options={admins?.map((item: string) => ({
- label: item,
- value: item,
- }))}
- loading={adminLoading}
- />
- </div>
- </Spin>
- </Modal>
- </ConstructLayout>
- );
- }
|