Commit 5de40c62 authored by 前端-许佳敏's avatar 前端-许佳敏

feat: 角色权限更改

parent 87431790
import React, {
useState,
ReactText,
useEffect,
useRef,
} from 'react';
import { Tree, Space, Tooltip, Input } from 'antd';
import {
findItemAndDelete,
findTreeKeys,
treeReduction,
getParentTreeTitles,
} from '@/utils';
import './index.less';
import deepClone from 'clone';
import { TreeProps } from 'antd/lib/tree';
import {
DeleteOutlined,
PlusCircleOutlined,
} from '@ant-design/icons';
import cx from 'classnames';
import { useSelections } from '@umijs/hooks';
export interface TabTreeActions {
selected: ReactText[];
getExpandedKeys: () => ReactText[];
getSelectKey: () => ReactText;
getSelectKeys: () => ReactText[];
setExpandedKeys: (keys: ReactText[]) => void;
setSelectKey: (key: ReactText) => void;
setSelectKeys: (keys: ReactText[]) => void;
getParentPath: (id: ReactText) => string;
getParent: (id) => any;
}
export interface toolsRenderProps {
addNode?(node);
addChildNode?(node);
deleteNode?(node);
}
export interface TabTreeProps extends TreeProps {
treeData: any[];
fetchData?(params?): Promise<any>;
actions?: TabTreeActions;
title?: React.ReactNode;
showSave?; // 是否显示保存按钮
// 若传入该字段, 则会作为tree识别的节点, 默认是`key`, 传入后原有的key值将无效
customKey?: string | number;
customTitle?: string | number;
handleSelect?: (key: ReactText, node: any) => void | Promise<any>;
handleSubmit?();
toolsRender?: toolsRenderProps;
getMenuSelectData?(): Promise<any>;
handleCheck?: (keys: any, nodes: any) => {};
customExpandkeys?: any[]; // props 传入自定义展开的key
enableSearch?: boolean; // 是否可搜索
searchPlaceholder?: string; // 搜索
resetSearch?: boolean;
}
export interface InnermostTreeNodeProps {}
export interface RenderIconsProps {
node: any;
nowKey: any;
toolsRender?: toolsRenderProps;
}
export const useTreeActions = (action?): TabTreeActions => {
const actionRef = useRef<any>(null);
actionRef.current = actionRef.current || action || createTreeActions();
return actionRef.current;
};
export const createTreeActions = () => {
const actions: TabTreeActions = {
selected: [],
getExpandedKeys() {
return [];
},
getSelectKey() {
return '';
},
getSelectKeys() {
return [];
},
setSelectKey() {},
setSelectKeys() {},
setExpandedKeys() {},
getParentPath(id) {
return '';
},
getParent(id) {
return null;
},
};
return actions;
};
const InnermostTreeNode: React.FC<InnermostTreeNodeProps> = props => {
return (
<span style={{ display: 'flex', alignItems: 'center' }}>
<span className="tree-node-circle"></span>
<span>{props.children}</span>
</span>
);
};
const RenderIcons: React.FC<RenderIconsProps> = props => {
const { toolsRender } = props;
// @todo 去掉点击active时, 保持icon显示
// return <Space className={cx('god-tabtree-icons', props.nowKey === props.node.key ? 'show' : 'hide')}>
return (
<Space className={cx('god-tabtree-icons')}>
<Tooltip title="新增节点">
<PlusCircleOutlined
onClick={e => {
e.stopPropagation();
toolsRender &&
toolsRender.addNode &&
toolsRender.addNode(props.node);
}}
/>
</Tooltip>
<Tooltip title="新增子节点">
<PlusCircleOutlined
onClick={e => {
e.stopPropagation();
toolsRender &&
toolsRender.addChildNode &&
toolsRender.addChildNode(props.node);
}}
/>
</Tooltip>
<Tooltip title="删除当前节点">
<DeleteOutlined
onClick={e => {
e.stopPropagation();
toolsRender &&
toolsRender.deleteNode &&
toolsRender.deleteNode(props.node);
}}
/>
</Tooltip>
</Space>
);
};
// 将无children的叶子节点中的title 转化为带有样式的title, 由于每次render 都需要重新deepClone深拷贝,可以优化
// 在多选模式下无需转化
function transformSingleTitle(
data,
nowKey,
checkable,
disabled,
toolsRender,
customKey?,
customTitle?,
) {
if (Array.isArray(data) && data.length > 0) {
for (let item = 0; item < data.length; item++) {
// 指定默认key
if (customKey) {
data[item]._key = data[item].key;
data[item].key = data[item][customKey];
}
if (data[item].children) {
transformSingleTitle(
data[item].children,
nowKey,
checkable,
disabled,
toolsRender,
customKey,
customTitle,
);
}
data[item]._title = data[item]._title || data[item].title;
data[item].title = (
<span
className="god-tabtree-title"
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
{checkable ||
(data[item].children && data[item].children.length !== 0) ? (
data[item].title
) : (
<InnermostTreeNode>{data[item].title}</InnermostTreeNode>
)}
<div>
{toolsRender && (
<RenderIcons
node={data[item]}
nowKey={nowKey}
toolsRender={toolsRender}
/>
)}
</div>
</span>
);
// 使选中样式受控
data[item].className = cx(
'god-tabtree-select',
String(nowKey) === String(data[item].key) ? 'show' : 'hide',
);
if (disabled) {
data[item].disableCheckbox = disabled;
}
if (customTitle) {
data[item]._title = data[item].title;
data[item].title = data[item][customTitle];
}
}
}
return data;
}
const TabTree: React.FC<TabTreeProps> = props => {
const {
treeData,
actions,
checkable,
customKey,
customTitle,
toolsRender,
disabled,
getMenuSelectData,
handleCheck,
customExpandkeys,
checkStrictly = false,
} = props;
const selfActions = useTreeActions(actions);
// 需展开的key
const [expandkeys, setExpandkeys] = useState<ReactText[]>([]);
// 当前选中的node
const [selectKey, setSelectKey] = useState<string | number>('');
// 自动展开父级
const [autoExpandParent, setAutoExpandParent] = useState<boolean>(false);
const data = transformSingleTitle(
deepClone(treeData),
selectKey,
checkable,
disabled,
toolsRender,
customKey,
customTitle,
);
// 重写选择方法, 只有在开启多选的时候才会启用
const checkedKeys = findTreeKeys(treeData, customKey);
const {
selected,
select,
setSelected,
} = useSelections(checkedKeys, []);
useEffect(() => {
if (getMenuSelectData) {
getMenuSelectData().then(res => {
const { ids } = res.data;
setSelected(ids);
});
}
}, []);
useEffect(() => {
if (customExpandkeys?.length) {
setExpandkeys(customExpandkeys);
setAutoExpandParent(true);
}
}, [customExpandkeys]);
if (selfActions) {
selfActions.getExpandedKeys = () => expandkeys;
selfActions.getSelectKey = () => selectKey;
selfActions.getSelectKeys = () => selected;
selfActions.selected = selected;
selfActions.setSelectKeys = (keys: ReactText[]) => {
setSelected(keys);
};
selfActions.setExpandedKeys = (keys: ReactText[]) => {
setExpandkeys(keys);
};
selfActions.setSelectKey = (key: ReactText) => {
setSelectKey(key);
};
selfActions.getParentPath = (id: ReactText) => {
return getParentTreeTitles(treeData, id);
};
selfActions.getParent = id => {
const reductData = treeReduction(treeData);
const targetInfo = reductData[id];
const parentInfo = reductData[targetInfo.parentId];
// fixbug 当选中根节点下的节点时, 由于无parentId, 需自动补充0
return parentInfo || { id: 0 };
};
}
const batchSelect = (items: any) => {
if (items.checked) {
// 更改为严格模式
items.checked.forEach(v => select(v));
} else {
items.forEach(v => select(v));
}
};
// 展开/收起的回调
const onExpand = expandedKeys => {
setAutoExpandParent(false);
setExpandkeys(expandedKeys);
};
return (
<Tree
className="god-tabtree"
treeData={data}
blockNode
checkable={checkable}
checkedKeys={selected}
expandedKeys={expandkeys}
autoExpandParent={autoExpandParent}
checkStrictly={checkStrictly}
onExpand={onExpand}
onCheck={(keys, nodes) => {
const { node, checked, checkedNodes } = nodes;
checked
? batchSelect(keys as any)
: setSelected(checkedNodes.map(v => v.key));
// 用户自定义的勾选后触发事件
if (handleCheck) {
handleCheck(keys, nodes);
}
}}
onSelect={(keys, e) => {
// 控制点击node时可以展开
const { node, selected } = e;
// 用户自定义的选择后触发事件
if (props.handleSelect) {
const result = props.handleSelect(node.key, node);
// 存在返回值则不执行选中事件, 一般用于切换node时,不希望离开当前页面
if (result) {
result
.then(() => {
// 若promise 是resolve状态, 说明确认离开了当前页面
setSelectKey(selectKey === node.key ? '' : node.key);
setExpandkeys(
expandkeys.includes(node.key)
? findItemAndDelete(expandkeys, node.key)
: [...expandkeys, node.key],
);
})
.catch(() => {});
return false;
}
}
// 如果重复点击 需要取消选中
setSelectKey(selectKey === node.key ? '' : node.key);
setExpandkeys(
expandkeys.includes(node.key)
? findItemAndDelete(expandkeys, node.key)
: [...expandkeys, node.key],
);
}}
/>
);
};
TabTree.defaultProps = {};
export default TabTree;
.field-header_container {
display: flex;
justify-content: space-between;
font-size: 14px;
margin-bottom: 18px;
}
.field-header_title {
display: flex;
align-items: center;
font-weight: 700;
&::before {
content: "";
width: 2px;
height: 14px;
background: #00B37A;
margin-right: 6px;
}
}
import React, { ReactNode } from 'react'
import mixinsClassName from 'classnames'
import './index.less'
export interface FieldHeaderProps extends React.HTMLAttributes<HTMLDivElement> {
renderTitle: ReactNode,
extra?: ReactNode,
}
const FieldHeader:React.FC<FieldHeaderProps> = (props) => {
const { renderTitle, extra, className, ...restDivProps } = props
return (
<div className={mixinsClassName('field-header_container', className)} {...restDivProps}>
<div className='field-header_title'>{renderTitle}</div>
<div>{extra}</div>
</div>
)
}
FieldHeader.defaultProps = {}
export default FieldHeader
...@@ -2,7 +2,6 @@ import React from 'react'; ...@@ -2,7 +2,6 @@ import React from 'react';
import { Space } from 'antd'; import { Space } from 'antd';
const CustomStatus = props => { const CustomStatus = props => {
console.log(props);
return ( return (
<> <>
<Space> <Space>
......
import React, { useState, ReactText, useImperativeHandle, useEffect, useRef } from 'react' import React, {
import { Tree, Space, Tooltip, Button, Input } from 'antd' useState,
import { findItemAndDelete, findTreeKeys, treeReduction, getParentTreeTitles } from '@/utils' ReactText,
import './index.less' useImperativeHandle,
import deepClone from 'clone' useEffect,
import { TreeProps } from 'antd/lib/tree' useRef,
import { PlusOutlined, DeleteOutlined, PlusCircleOutlined } from '@ant-design/icons' } from 'react';
import cx from 'classnames' import { Tree, Space, Tooltip, Button, Input } from 'antd';
import { useSelections } from '@umijs/hooks' import {
findItemAndDelete,
findTreeKeys,
treeReduction,
getParentTreeTitles,
} from '@/utils';
import './index.less';
import deepClone from 'clone';
import { TreeProps } from 'antd/lib/tree';
import {
PlusOutlined,
DeleteOutlined,
PlusCircleOutlined,
} from '@ant-design/icons';
import cx from 'classnames';
import { useSelections } from '@umijs/hooks';
import FieldHeader from '../FieldHeader';
const { Search } = Input; const { Search } = Input;
...@@ -18,8 +34,8 @@ export interface TabTreeActions { ...@@ -18,8 +34,8 @@ export interface TabTreeActions {
setExpandedKeys: (keys: ReactText[]) => void; setExpandedKeys: (keys: ReactText[]) => void;
setSelectKey: (key: ReactText) => void; setSelectKey: (key: ReactText) => void;
setSelectKeys: (keys: ReactText[]) => void; setSelectKeys: (keys: ReactText[]) => void;
getParentPath: (id: ReactText) => string getParentPath: (id: ReactText) => string;
getParent: (id) => any getParent: (id) => any;
} }
export interface toolsRenderProps { export interface toolsRenderProps {
...@@ -43,7 +59,7 @@ export interface TabTreeProps extends TreeProps { ...@@ -43,7 +59,7 @@ export interface TabTreeProps extends TreeProps {
getMenuSelectData?(): Promise<any>; getMenuSelectData?(): Promise<any>;
handleCheck?: (keys: any, nodes: any) => {}; handleCheck?: (keys: any, nodes: any) => {};
customExpandkeys?: any[]; // props 传入自定义展开的key customExpandkeys?: any[]; // props 传入自定义展开的key
enableSearch?: boolean; // 是否可搜索 enableSearch?: boolean; // 是否可搜索
searchPlaceholder?: string; // 搜索 searchPlaceholder?: string; // 搜索
resetSearch?: boolean; resetSearch?: boolean;
} }
...@@ -78,8 +94,12 @@ export const createTreeActions = () => { ...@@ -78,8 +94,12 @@ export const createTreeActions = () => {
setSelectKey() {}, setSelectKey() {},
setSelectKeys() {}, setSelectKeys() {},
setExpandedKeys() {}, setExpandedKeys() {},
getParentPath(id){return ''}, getParentPath(id) {
getParent(id){return null} return '';
},
getParent(id) {
return null;
},
}; };
return actions; return actions;
}; };
...@@ -222,12 +242,12 @@ const TabTree: React.FC<TabTreeProps> = props => { ...@@ -222,12 +242,12 @@ const TabTree: React.FC<TabTreeProps> = props => {
handleCheck, handleCheck,
customExpandkeys, customExpandkeys,
enableSearch = false, enableSearch = false,
searchPlaceholder = "搜索", searchPlaceholder = '搜索',
checkStrictly = false, checkStrictly = false,
resetSearch, resetSearch,
} = props; } = props;
const selfActions = useTreeActions(actions) const selfActions = useTreeActions(actions);
// 需展开的key // 需展开的key
const [expandkeys, setExpandkeys] = useState<ReactText[]>([]); const [expandkeys, setExpandkeys] = useState<ReactText[]>([]);
...@@ -235,17 +255,17 @@ const TabTree: React.FC<TabTreeProps> = props => { ...@@ -235,17 +255,17 @@ const TabTree: React.FC<TabTreeProps> = props => {
const [selectKey, setSelectKey] = useState<string | number>(''); const [selectKey, setSelectKey] = useState<string | number>('');
// 自动展开父级 // 自动展开父级
const [autoExpandParent, setAutoExpandParent] = useState<boolean>(false) const [autoExpandParent, setAutoExpandParent] = useState<boolean>(false);
// 搜索的值 // 搜索的值
const [searchValue, setSearchValue] = useState() const [searchValue, setSearchValue] = useState();
useEffect(()=> { useEffect(() => {
if(resetSearch) { if (resetSearch) {
setSearchValue(null) setSearchValue(null);
setExpandkeys([]) setExpandkeys([]);
} }
}, [resetSearch]) }, [resetSearch]);
const data = transformSingleTitle( const data = transformSingleTitle(
deepClone(treeData), deepClone(treeData),
...@@ -277,11 +297,11 @@ const TabTree: React.FC<TabTreeProps> = props => { ...@@ -277,11 +297,11 @@ const TabTree: React.FC<TabTreeProps> = props => {
}, []); }, []);
useEffect(() => { useEffect(() => {
if(customExpandkeys?.length) { if (customExpandkeys?.length) {
setExpandkeys(customExpandkeys) setExpandkeys(customExpandkeys);
setAutoExpandParent(true) setAutoExpandParent(true);
} }
}, [customExpandkeys]) }, [customExpandkeys]);
const toggleSelectAll = () => { const toggleSelectAll = () => {
if (allSelected) { if (allSelected) {
...@@ -306,71 +326,73 @@ const TabTree: React.FC<TabTreeProps> = props => { ...@@ -306,71 +326,73 @@ const TabTree: React.FC<TabTreeProps> = props => {
setSelectKey(key); setSelectKey(key);
}; };
selfActions.getParentPath = (id: ReactText) => { selfActions.getParentPath = (id: ReactText) => {
return getParentTreeTitles(treeData, id) return getParentTreeTitles(treeData, id);
} };
selfActions.getParent = (id) => { selfActions.getParent = id => {
const reductData = treeReduction(treeData) const reductData = treeReduction(treeData);
const targetInfo = reductData[id] const targetInfo = reductData[id];
const parentInfo = reductData[targetInfo.parentId] const parentInfo = reductData[targetInfo.parentId];
// fixbug 当选中根节点下的节点时, 由于无parentId, 需自动补充0 // fixbug 当选中根节点下的节点时, 由于无parentId, 需自动补充0
return parentInfo || {id: 0} return parentInfo || { id: 0 };
} };
} }
const batchSelect = (items: any) => { const batchSelect = (items: any) => {
if (items.checked) { if (items.checked) {
// 更改为严格模式 // 更改为严格模式
items.checked.forEach(v => select(v)) items.checked.forEach(v => select(v));
} else { } else {
items.forEach(v => select(v)) items.forEach(v => select(v));
} }
}; };
// 展开/收起的回调 // 展开/收起的回调
const onExpand = expandedKeys => { const onExpand = expandedKeys => {
setAutoExpandParent(false) setAutoExpandParent(false);
setExpandkeys(expandedKeys) setExpandkeys(expandedKeys);
}; };
const onSearchChange = v => { const onSearchChange = v => {
// todo 找到目标节点的父级key // todo 找到目标节点的父级key
setSearchValue(v) setSearchValue(v);
if(v) { if (v) {
const reductData = Object.values(treeReduction(treeData)) const reductData = Object.values(treeReduction(treeData));
const expandedKeys = reductData.filter(item => item['title'].indexOf(v) > -1).map(_item => _item['parentId']) const expandedKeys = reductData
setExpandkeys(expandedKeys) .filter(item => item['title'].indexOf(v) > -1)
setAutoExpandParent(true) .map(_item => _item['parentId']);
setExpandkeys(expandedKeys);
setAutoExpandParent(true);
} else { } else {
setExpandkeys([]) setExpandkeys([]);
} }
} };
const renderExtra = (
<>
{checkable && (
<Button onClick={toggleSelectAll} disabled={disabled} type="link">
{allSelected ? '取消全选' : '全选'}
</Button>
)}
{showSave && checkable && (
<Button onClick={handleSubmit} disabled={disabled} type="link">
保存
</Button>
)}
</>
);
return ( return (
<div> <div>
{title && ( {title && <FieldHeader renderTitle={title} extra={renderExtra} />}
<div className="god-tabtree-header"> {enableSearch && data?.length > 0 && (
<div>{title}</div> <Search
{checkable && (
<Button onClick={toggleSelectAll} disabled={disabled} type="link">
{allSelected ? '取消全选' : '全选'}
</Button>
)}
{showSave && checkable && (
<Button onClick={handleSubmit} disabled={disabled} type="link">
保存
</Button>
)}
</div>
)}
{
enableSearch && data?.length > 0 && <Search
style={{ marginBottom: 8 }} style={{ marginBottom: 8 }}
placeholder={searchPlaceholder} placeholder={searchPlaceholder}
value={searchValue} value={searchValue}
onChange={(v:any) => setSearchValue(v.target.value)} onChange={(v: any) => setSearchValue(v.target.value)}
onSearch={onSearchChange} onSearch={onSearchChange}
/> />
} )}
<Tree <Tree
className="god-tabtree" className="god-tabtree"
treeData={data} treeData={data}
......
import { Modal } from "antd"
import { ReactNode, useCallback, useEffect, useState } from "react"
export interface leaveOptions {
title?: ReactNode,
onSave: any,
onModalOk(resolve: any),
onModalCancel(reject: any),
}
/**
* 对即将离开某个操作时, 发出提示弹窗
*/
export const useLeavePage = (options: leaveOptions): [React.Dispatch<React.SetStateAction<boolean>>, any] => {
const { title, onSave, onModalOk, onModalCancel } = options
const [saveStatus, setSaveStatus] = useState<boolean>(true)
const validateSaveStatus = useCallback(() => {
if (saveStatus) {
return Promise.resolve()
} else {
return new Promise((resolve, reject) => {
Modal.confirm({
content: title || '确认要离开当前页面吗,您提交的数据尚未保存',
onOk() {
onModalOk(resolve)
},
onCancel() {
onModalCancel(reject)
}
})
})
}
}, [saveStatus])
return [setSaveStatus, validateSaveStatus]
}
import { useMap } from '@umijs/hooks'
import React, { useState, useEffect } from 'react'
import { Modal } from 'antd'
import { TabTreeActions } from '@/components/TabTree'
import { ISchemaFormActions } from '@formily/antd'
import { isObject } from '@/utils'
export enum FormState {
FREE, // 空闲状态
EDIT, // 编辑状态
ADD, // 新增状态
}
export interface useTreeTabOptions {
selectCallback?(selectKey?, node?),
fetchMenuData?(),
fetchItemDetailData?(id),
// 重置右侧详情
resetDetail?(),
// 对树形工具栏做render扩展
extendsToolsRender?: any,
// 树形的实例操作方法
treeActions?: TabTreeActions
// 右侧表单的实例操作方法
formActions?: ISchemaFormActions
// 删除菜单时调用的API
deleteMenu?: any
}
export interface treeNodeResponse {
/**
* 该节点是否选中
*/
selected: boolean,
/**
* 节点信息
*/
node: any
}
export const useTreeData = (options: useTreeTabOptions = {}) => {
const { selectCallback, fetchMenuData, treeActions, formActions, extendsToolsRender, deleteMenu } = options
const [treeExtraMaps, { set, get }] = useMap<any, any>()
const [treeData, setTreeData] = useState<any[]>([])
const [treeStatus, setTreeStatus] = useState<FormState>(FormState.FREE)
const [nodeRecord, setNodeRecord] = useState<any>(null)
const [isEditForm, setIsEditForm] = useState<boolean>(false)
useEffect(() => {
resetMenu()
}, [])
const resetMenu = async () => {
if (fetchMenuData) {
const res = await fetchMenuData()
setTreeData(res.data || [])
}
}
const handleSelect = (selectKey?, node?) => {
return new Promise<treeNodeResponse>((resolve, reject) => {
if (selectCallback) {
// 完全自定义点击节点事件
selectCallback(selectKey, node)
return;
}
resolve({
selected: true,
node: node || null
})
})
}
const handleDeleteMenu = (id) => {
deleteMenu({
id: isObject(id) ? nodeRecord.key : id
}).then(() => {
setTreeStatus(FormState.FREE)
setNodeRecord(undefined)
resetMenu()
})
}
// 新增整合树形操作菜单
// 树形工具栏
const toolsRender = {
addNode(node) {
const activeParentId = treeActions && treeActions.getParent(node.key || node.id)?.id
setNodeRecord({
...node,
parentId: activeParentId, // 添加同级的时候 使用上一级的id作为parentId
})
formActions && formActions.reset({ validate: false })
setTreeStatus(FormState.ADD)
},
addChildNode(node) {
setNodeRecord({
...node,
parentId: node.key || node.id
})
formActions && formActions.reset({ validate: false })
set(node.key || node.id, null)
setTreeStatus(FormState.ADD)
},
deleteNode(node) {
const id = node.key || node.id
handleDeleteMenu(id)
},
...extendsToolsRender
}
return {
handleSelect,
treeStatus,
setTreeStatus,
treeData,
setTreeData,
nodeRecord,
setNodeRecord,
isEditForm,
setIsEditForm,
treeExtraMaps,
setTreeMaps: set,
getTreeMaps: get,
resetMenu,
toolsRender,
handleDeleteMenu
}
}
import React, { useContext, useState, useEffect, useRef, useLayoutEffect, useCallback } from 'react'; import React, {
import { Row, Col, Button, Form, Input, Space, Tabs, message, Badge, Card } from 'antd'; useContext,
import { IntegrateTree } from 'god' useState,
useEffect,
useRef,
useLayoutEffect,
useCallback,
useMemo,
} from 'react';
import {
Row,
Col,
Button,
Form,
Input,
Space,
Tabs,
Checkbox,
Badge,
Card,
Tag,
} from 'antd';
import { IntegrateTree } from 'god';
import { history } from 'umi'; import { history } from 'umi';
import { historyContainer } from '@/hooks/useHistoryContainer'; import { historyContainer } from '@/hooks/useHistoryContainer';
import NiceForm from '@/components/NiceForm'; import NiceForm from '@/components/NiceForm';
import TabTree, { useTreeActions, createTreeActions } from '@/components/TabTree'; import TabTree, {
useTreeActions,
createTreeActions,
} from '@/components/TabTree';
import { PublicApi } from '@/services/api'; import { PublicApi } from '@/services/api';
import styled from './index.less' import styled from './index.less';
import CheckboxTree from '@/components/CheckBoxTree'; import CheckboxTree from '@/components/CheckBoxTree';
import { useTreeTabs } from '@/hooks/useTreeTabs'; import { useTreeData } from '@/hooks/useTreeData';
import { createFormActions } from '@formily/antd'; import { createFormActions } from '@formily/antd';
import { usePageStatus, PageStatus } from '@/hooks/usePageStatus'; import { usePageStatus, PageStatus } from '@/hooks/usePageStatus';
import { PageHeaderWrapper } from '@ant-design/pro-layout'; import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ReutrnEle from '@/components/ReturnEle'; import ReutrnEle from '@/components/ReturnEle';
import { useLeavePage } from '@/hooks/useLeavePage';
import { useMap } from '@umijs/hooks';
import FieldHeader from '@/components/FieldHeader';
import OrgModal from './orgModal';
import { PlusOutlined } from '@ant-design/icons';
import { useTreeTabs } from '@/hooks/useTreeTabs';
const pageTitles = [ const pageTitles = ['新增', '编辑', '预览'];
'新增',
'编辑',
'预览'
]
const TabFormErrors = (props) => { const TabFormErrors = props => {
return ( return (
<Badge dot={props.dot} offset={[5, -5]}> <Badge dot={props.dot} offset={[5, -5]}>
{props.children} {props.children}
</Badge> </Badge>
) );
} };
const fetchMenuData = async () => { const fetchMenuData = async () => {
const res = await PublicApi.getMemberRoleAuthTree() const res = await PublicApi.getMemberRoleAuthTree();
return res return { data: res.data.menus };
} };
const TabsItem = Tabs.TabPane;
const menuActions = createFormActions();
const treeActions = createTreeActions();
const fetchOrgsTreeData = async () => {
const res = await PublicApi.getMemberOrgTree();
return res;
};
const TabsItem = Tabs.TabPane const getTreeNode = (treeData: any, targetNodeId: any) => {
if (!Array.isArray(treeData)) {
return null;
}
const menuActions = createFormActions() for (let i = 0; i < treeData.length; i++) {
const item = treeData[i];
if (item.id === targetNodeId) {
return item;
}
const treeActions = createTreeActions() if (item.children) {
return getTreeNode(item.children, targetNodeId);
}
}
return {
id: '',
title: '',
};
};
const MemberDetail: React.FC<{}> = () => { const MemberDetail: React.FC<{}> = () => {
const [form] = Form.useForm(); const [form] = Form.useForm();
const value = useContext(historyContainer) const value = useContext(historyContainer);
const [nodeRecord, setNodeRecord] = useState<any>(null);
const [orgModalVisible, setOrgModalVisible] = useState(false);
const [treeExtraMaps, { set: setButtonAuth, get: getButtonAuth }] = useMap<
any,
any
>();
const { const {
treeData, treeData: plateformTreeData,
handleSelect, handleSelect: handleSyncSelect,
nodeRecord,
isEditForm,
setIsEditForm,
getTreeMaps,
} = useTreeTabs({ } = useTreeTabs({
fetchMenuData: fetchOrgsTreeData,
});
const { treeData, handleSelect } = useTreeData({
fetchMenuData, fetchMenuData,
fetchItemDetailData: ({ id }) => PublicApi.getMemberRoleAuthButton({ fetchItemDetailData: ({ id }) =>
menuId: id PublicApi.getMemberRoleAuthButton({
}) menuId: id,
}) }),
});
const actionRef = useRef<any>({})
const formInitValue = nodeRecord ? getTreeMaps(nodeRecord.key) : {}
const [errors, setErrors] = useState<boolean>(false)
const [formValue, setFormValue] = useState<any>(null)
const {
pageStatus,
id
} = usePageStatus()
const actionRef = useRef<any>({});
const formInitValue = nodeRecord ? getButtonAuth(nodeRecord.key) : {};
const [errors, setErrors] = useState<boolean>(false);
const [formValue, setFormValue] = useState<any>(null);
// 储存的按钮数据
const [buttonInfos, setButtonInfos] = useState<any>([]);
// 储存的数据权限选项
const [authInfos, setAuthInfos] = useState<any>({});
const disabledCheckAuthConfig = useMemo(() => {
if (nodeRecord && authInfos[nodeRecord.id]) {
return authInfos[nodeRecord.id] as {
hasDataAuth: number;
dataAuthConfig: number;
orgIds: any[];
};
} else {
return { hasDataAuth: 0, dataAuthConfig: 0, orgIds: [] };
}
}, [authInfos, nodeRecord]);
const { pageStatus, id } = usePageStatus();
const fetchItemDetailData = useCallback(
async node => {
const isAdd = pageStatus === PageStatus.ADD;
const fn = isAdd
? PublicApi.getMemberRoleAuthButton
: PublicApi.getMemberRoleAuthButtonCheck;
const params = isAdd ? {} : { memberRoleId: id };
const { data } = await fn({
menuId: node ? node.id : nodeRecord.id,
...params,
});
setButtonAuth(node.id, data);
// 该配置由pass平台控制, 如果为1 则表示该角色可以配置数据权限
if (authInfos[node.id]) {
// 已经存在了配置权限, 则不做更新, 防止修改后被重置
} else {
setAuthInfos({
...authInfos,
[node.id]: {
hasDataAuth: isAdd ? 0 : data.hasDataAuth,
dataAuthConfig: data.dataAuthConfig,
orgIds: isAdd ? [] : data.orgIds,
},
});
}
},
[nodeRecord, authInfos],
);
const [setEditForm, validateEditForm] = useLeavePage({
onSave: () => {},
onModalOk: () => {},
onModalCancel: () => {},
});
const handleNodeSelected = async (selectKey, selectNode) => {
try {
const { node } = await handleSelect(selectKey, selectNode);
if (nodeRecord) {
return new Promise((resolve, reject) => {
if (selectKey !== nodeRecord.key) {
validateEditForm()
.then(() => {
setNodeRecord(node);
fetchItemDetailData(node);
resolve(true);
})
.catch(() => {
reject();
});
} else {
resolve(null);
}
});
} else {
setNodeRecord(node);
fetchItemDetailData(node);
}
} catch (error) {}
};
// 编辑和预览模式下需回显数据 // 编辑和预览模式下需回显数据
const fetchRoleMenuDetail = async (id) => { const fetchRoleMenuDetail = async id => {
// 10秒缓存 // 10秒缓存
const res = await PublicApi.getMemberRoleGet({ const res = await PublicApi.getMemberRoleGet(
memberRoleId: id {
}, { useCache: true, ttl: 10 * 1000 }) memberRoleId: id,
return res },
} { useCache: true, ttl: 10 * 1000 },
);
// 储存的按钮数据 return res;
const [buttonInfos, setButtonInfos] = useState<any>([]) };
useEffect(() => { useEffect(() => {
if (!id) return; if (!id) return;
fetchRoleMenuDetail(id).then(res => { fetchRoleMenuDetail(id).then(res => {
const { data } = res const { data } = res;
setFormValue(data) setFormValue(data);
}) });
}, []) }, []);
useEffect(() => { useEffect(() => {
if (formInitValue) { if (formInitValue) {
// 显示右侧checkbox // 显示右侧checkbox
setButtonInfos(formInitValue.buttons || []) setButtonInfos(formInitValue.buttons || []);
// 回显右侧checkbox的值 // 回显右侧checkbox的值
if (actionRef.current.setSelected) { if (actionRef.current.setSelected) {
actionRef.current.setSelected() actionRef.current.setSelected();
} }
} }
}, [getTreeMaps]) }, [getButtonAuth, nodeRecord]);
const handleSubmit = () => { const handleSubmit = () => {
menuActions.submit().then(async ({ values }) => { menuActions
setErrors(false) .submit()
// 如果未点击过操作权限tab, 则无法获取到actionRef实例, 需补充手动补充回显的ids, 新增的时候如果未设置按钮,则返回空数组 .then(async ({ values }) => {
const buttonCheckIds = actionRef.current.selected || (formValue && formValue.ids) || [] setErrors(false);
const treeCheckIds = treeActions.getSelectKeys() // 如果未点击过操作权限tab, 则无法获取到actionRef实例, 需补充手动补充回显的ids, 新增的时候如果未设置按钮,则返回空数组
const menuIds = [...buttonCheckIds, ...treeCheckIds] const buttonCheckIds =
if (pageStatus === PageStatus.EDIT) { actionRef.current.selected || (formValue && formValue.ids) || [];
await PublicApi.postMemberRoleUpdate({ const treeCheckIds = treeActions.getSelectKeys();
...values,
memberRoleId: id, const publicParams = {
menuIds
})
} else {
await PublicApi.postMemberRoleAdd({
...values, ...values,
menuIds hasImAuth: values.hasImAuth ? 1 : 0,
}) auth: treeCheckIds.map(v => ({
} menuId: v,
history.goBack(-1) // @todo 暂时写死为空
}).catch(err => { buttonIds: [],
console.log(err) hasDataAuth: authInfos[v].hasDataAuth,
if (Array.isArray(err)) { orgIds: authInfos[v].orgIds
setErrors(true) })),
} };
}) if (pageStatus === PageStatus.EDIT) {
} await PublicApi.postMemberRoleUpdate({
memberRoleId: id,
...publicParams,
});
} else {
await PublicApi.postMemberRoleAdd({
...publicParams,
});
}
history.goBack(-1);
})
.catch(err => {
console.log(err);
if (Array.isArray(err)) {
setErrors(true);
}
});
};
const changeTabs = (key) => { const changeTabs = key => {
if (key === '2' && id) { if (key === '2' && id) {
fetchRoleMenuDetail(id).then(res => { fetchRoleMenuDetail(id).then(res => {
const { data } = res const { data } = res;
// 获取菜单id选中的集合 // 获取菜单id选中的集合
const { const { checkIds, ...reset } = data;
checkIds, treeActions.setSelectKeys(checkIds);
...reset });
} = data
treeActions.setSelectKeys(checkIds)
})
} }
} };
const onDataAuthChange = e => {
setAuthInfos({
...authInfos,
[nodeRecord.id]: Object.assign(
{ ...authInfos[nodeRecord.id] },
{ hasDataAuth: e.target.checked ? 1 : 0 },
),
});
};
const extraButtons = ( const extraButtons = (
<Space> <Space>
<Button type='primary' disabled={pageStatus === PageStatus.PREVIEW} onClick={handleSubmit}>保存</Button> <Button
type="primary"
disabled={pageStatus === PageStatus.PREVIEW}
onClick={handleSubmit}
>
保存
</Button>
</Space> </Space>
) );
const handleOrgSuccess = selectKeys => {
setAuthInfos({
...authInfos,
[nodeRecord.id]: Object.assign(
{ ...authInfos[nodeRecord.id] },
{ orgIds: selectKeys },
),
});
setOrgModalVisible(false);
};
const handleOrgCancel = () => {
setOrgModalVisible(false);
};
const handleOpenOrg = () => {
setOrgModalVisible(true);
};
return ( return (
<PageHeaderWrapper <PageHeaderWrapper
onBack={() => history.goBack()} onBack={() => history.goBack()}
backIcon={<ReutrnEle description="返回" />} backIcon={<ReutrnEle description="返回" />}
className='addRepository' className="addRepository"
title={pageTitles[pageStatus]} title={pageTitles[pageStatus]}
extra={[ extra={[extraButtons]}
extraButtons
]}
> >
<Card> <Card>
<Tabs type='card' className='black-tabs' onChange={changeTabs}> <Tabs type="card" className="black-tabs" onChange={changeTabs}>
<TabsItem tab={<TabFormErrors dot={errors}>基本信息</TabFormErrors>} key='1'> <TabsItem
tab={<TabFormErrors dot={errors}>基本信息</TabFormErrors>}
key="1"
>
<NiceForm <NiceForm
labelCol={4} labelCol={4}
wrapperCol={12} wrapperCol={12}
initialValues={formValue} initialValues={formValue}
labelAlign='left' labelAlign="left"
actions={menuActions} actions={menuActions}
editable={pageStatus !== PageStatus.PREVIEW} editable={pageStatus !== PageStatus.PREVIEW}
previewPlaceholder=' ' previewPlaceholder=" "
schema={{ schema={{
type: 'object', type: 'object',
properties: { properties: {
roleName: { roleName: {
type: 'string', type: 'string',
title: '角色名称', title: '角色名称',
required: true required: true,
}, },
remark: { remark: {
type: 'textarea', type: 'textarea',
title: '备注', title: '备注',
"x-rules": [ 'x-rules': [
{ {
limitByte: true, limitByte: true,
maxByte: 120 maxByte: 120,
} },
], ],
"x-component-props": { 'x-component-props': {
rows: 4 rows: 4,
} },
},
hasImAuth: {
type: 'number',
title: '是否具有IM通讯权限',
'x-component': 'CheckboxSingle',
}, },
state: { state: {
type: 'number', type: 'number',
title: '状态', title: '状态',
"x-component": 'CustomStatus', 'x-component': 'CustomStatus',
default: 1 default: 1,
} },
} },
}} }}
> ></NiceForm>
</NiceForm>
</TabsItem> </TabsItem>
<TabsItem tab='操作权限' key='2'> <TabsItem tab="操作权限" key="2">
<Row justify='space-between'> <Row justify="space-between">
<Col span={17} className={styled['menu-role-tree']}> <Col span={8} className={styled['menu-role-tree']}>
<TabTree <TabTree
title='菜单访问权限' title="菜单访问权限"
fetchData={params => fetchMenuData()} fetchData={params => fetchMenuData()}
checkable checkable
actions={treeActions} actions={treeActions}
treeData={treeData} treeData={treeData}
handleSelect={handleSelect} handleSelect={handleNodeSelected}
checkStrictly={true} checkStrictly={true}
customKey='id' customKey="id"
disabled={pageStatus === PageStatus.PREVIEW} disabled={pageStatus === PageStatus.PREVIEW}
/> />
</Col> </Col>
<Col span={6} className={styled['menu-role-tree']}> <Col span={7} className={styled['menu-role-tree']}>
<CheckboxTree <CheckboxTree
actions={actionRef} actions={actionRef}
disabled={pageStatus === PageStatus.PREVIEW} disabled={pageStatus === PageStatus.PREVIEW}
checkedNodes={buttonInfos} checkedNodes={buttonInfos}
title='菜单接口访问权限' title="菜单接口访问权限"
/> />
</Col> </Col>
<Col span={7} className={styled['menu-role-tree']}>
<FieldHeader renderTitle="数据权限" />
{nodeRecord && (
<>
<Checkbox
checked={!!disabledCheckAuthConfig.hasDataAuth}
onChange={e => onDataAuthChange(e)}
disabled={
pageStatus === PageStatus.PREVIEW ||
!disabledCheckAuthConfig.dataAuthConfig
}
>
是否需要数据权限
</Checkbox>
<div style={{marginTop: 16}}>
<p style={{color: '#909399'}}>组织机构授权</p>
{disabledCheckAuthConfig.orgIds.map(v => {
const node = getTreeNode(plateformTreeData, v);
if (!node) return null;
return (
<div className="org-tag-container" key={v.id}>
<Tag color={'#F4F5F7'} className="org-tag">
{node.title}
</Tag>
</div>
);
})}
<Button block type="dashed" onClick={handleOpenOrg}>
<PlusOutlined /> 关联
</Button>
</div>
</>
)}
</Col>
</Row> </Row>
</TabsItem> </TabsItem>
</Tabs> </Tabs>
<OrgModal
handleSyncSelect={handleSyncSelect}
plateformTreeData={plateformTreeData}
fetchOrgsTreeData={fetchOrgsTreeData}
selectKeys={disabledCheckAuthConfig.orgIds}
visible={orgModalVisible}
onSuccess={handleOrgSuccess}
onCancel={handleOrgCancel}
/>
</Card> </Card>
</PageHeaderWrapper> </PageHeaderWrapper>
) );
} };
export default MemberDetail export default MemberDetail;
.org-tag-container {
margin-bottom: 8px;
.ant-tag-has-color, .ant-tag-has-color a, .ant-tag-has-color a:hover, .ant-tag-has-color .anticon-close, .ant-tag-has-color .anticon-close:hover {
color: #606266;
}
}
.org-tag {
color: #606266;
}
import TabTree, { createTreeActions } from '@/components/TabTree'
import { useTreeTabs } from '@/hooks/useTreeTabs'
import { PublicApi } from '@/services/api'
import { Button, Drawer, Row } from 'antd'
import React, { useEffect, useState } from 'react'
import './orgModal.less'
export interface OrgModalProps {
visible: boolean,
handleSyncSelect: any,
plateformTreeData: any,
fetchOrgsTreeData: any,
selectKeys: any[],
onSuccess(selectKeys: any[]),
onCancel(),
}
const syncTreeActions = createTreeActions()
const OrgModal:React.FC<OrgModalProps> = (props) => {
const { visible, onSuccess, onCancel, plateformTreeData, handleSyncSelect, fetchOrgsTreeData, selectKeys } = props
const [resetSearch, setResetSearch] = useState(false)
const [customPlateformExpandkeys, setCustomPlateformExpandkeys] = useState<any>()
const handleSuccess = () => {
onSuccess(syncTreeActions.getSelectKeys())
}
useEffect(() => {
syncTreeActions.setSelectKeys(selectKeys)
}, [selectKeys])
return (
<Drawer
visible={visible}
closable={false}
placement='right'
width={600}
>
<TabTree
fetchData = {params => fetchOrgsTreeData()}
treeData={plateformTreeData}
handleSelect={handleSyncSelect}
actions={syncTreeActions}
customKey="id"
enableSearch
searchPlaceholder="组织机构名称"
checkStrictly
resetSearch={resetSearch}
customExpandkeys={customPlateformExpandkeys}
checkable={true}
/>
<Row justify='end'>
<Button onClick={onCancel} style={{marginRight: 8}}>关闭</Button>
<Button onClick={handleSuccess} type='primary'>确认</Button>
</Row>
</Drawer>
)
}
OrgModal.defaultProps = {}
export default OrgModal
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment