| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501 |
- import { TreeSelect as ATreeSelect } from 'antd';
- import { useIntl } from 'umi';
- import type { Field } from '@formily/core';
- import { createForm, registerValidateRules } from '@formily/core';
- import { createSchemaField } from '@formily/react';
- import React, { useEffect, useState } from 'react';
- import * as ICONS from '@ant-design/icons';
- import { PlusOutlined } from '@ant-design/icons';
- import {
- Form,
- FormGrid,
- FormItem,
- Input,
- Password,
- Select,
- Switch,
- TreeSelect,
- } from '@formily/antd';
- import type { ISchema } from '@formily/json-schema';
- import { action } from '@formily/reactive';
- import type { Response } from '@/utils/typings';
- import { service } from '@/pages/system/User';
- import { Modal, PermissionButton } from '@/components';
- import usePermissions from '@/hooks/permission';
- import { onlyMessage } from '@/utils/util';
- import { getMenuPathByCode } from '@/utils/menu';
- interface Props {
- model: 'add' | 'edit' | 'query';
- data: Partial<UserItem>;
- close: () => void;
- }
- const Save = (props: Props) => {
- const { model } = props;
- const intl = useIntl();
- const { permission: deptPermission } = usePermissions('system/Department');
- const { permission: rolePermission } = usePermissions('system/Role');
- const [data, setData] = useState<Partial<UserItem>>(props.data);
- const getRole = () => service.queryRoleList();
- const getOrg = () => service.queryOrgList({ paging: false });
- const departmentPath = getMenuPathByCode('system/Department');
- const rolePath = getMenuPathByCode('system/Role');
- const useAsyncDataSource = (api: any) => (field: Field) => {
- field.loading = true;
- api(field).then(
- action.bound!((resp: Response<any>) => {
- field.dataSource = resp.result?.map((item: Record<string, unknown>) => ({
- ...item,
- label: item.name,
- value: item.id,
- }));
- field.loading = false;
- }),
- );
- };
- registerValidateRules({
- checkStrength(value: string) {
- if (!value || value.length < 8 || value.length > 64) return true;
- if (/^[0-9]+$/.test(value) || /^[a-zA-Z]+$/.test(value) || /^[~!@#$%^&*]+$/.test(value)) {
- return {
- type: 'error',
- message: '密码强度不够',
- };
- }
- return true;
- },
- });
- const getUser = async () => {
- if (props.data.id) {
- const response: Response<UserItem> = await service.queryDetail(props.data?.id);
- if (response.status === 200) {
- const temp = response.result as UserItem;
- temp.orgIdList = (temp.orgList as { id: string; name: string }[]).map((item) => item.id);
- temp.roleIdList = (temp.roleList as { id: string; name: string }[]).map((item) => item.id);
- setData(temp);
- }
- }
- };
- useEffect(() => {
- if (model === 'edit') {
- getUser();
- } else {
- setData({});
- }
- }, [props.data, props.model]);
- const form = createForm({
- validateFirst: true,
- initialValues: data,
- });
- const SchemaField = createSchemaField({
- components: {
- FormItem,
- Input,
- Password,
- Switch,
- Select,
- TreeSelect,
- FormGrid,
- },
- scope: {
- icon(name: any) {
- return React.createElement(ICONS[name]);
- },
- },
- });
- const schema: ISchema = {
- type: 'object',
- properties: {
- layout: {
- type: 'void',
- 'x-decorator': 'FormGrid',
- 'x-decorator-props': {
- maxColumns: 2,
- minColumns: 2,
- columnGap: 24,
- },
- properties: {
- name: {
- title: intl.formatMessage({
- id: 'pages.system.name',
- defaultMessage: '姓名',
- }),
- type: 'string',
- 'x-decorator': 'FormItem',
- 'x-component': 'Input',
- 'x-decorator-props': {
- gridSpan: 1,
- },
- 'x-component-props': {
- placeholder: '请输入姓名',
- },
- name: 'name',
- 'x-validator': [
- {
- max: 64,
- message: '最多可输入64个字符',
- },
- {
- required: true,
- message: '请输入姓名',
- },
- ],
- // required: true,
- },
- username: {
- title: intl.formatMessage({
- id: 'pages.system.username',
- defaultMessage: '用户名',
- }),
- 'x-decorator-props': {
- gridSpan: 1,
- },
- type: 'string',
- 'x-decorator': 'FormItem',
- 'x-component': 'Input',
- 'x-component-props': {
- disabled: model === 'edit',
- placeholder: '请输入用户名',
- },
- 'x-validator': [
- {
- max: 64,
- message: '最多可输入64个字符',
- },
- {
- required: true,
- message: '请输入用户名',
- },
- {
- triggerType: 'onBlur',
- validator: (value: string) => {
- return new Promise((resolve) => {
- if (!value) resolve('');
- service
- .validateField('username', value)
- .then((resp) => {
- if (resp.status === 200) {
- if (resp.result.passed) {
- resolve('');
- } else {
- resolve(model === 'edit' ? '' : resp.result.reason);
- }
- }
- resolve('');
- })
- .catch(() => {
- return '验证失败!';
- });
- });
- },
- },
- ],
- name: 'username',
- required: true,
- },
- },
- },
- password: {
- type: 'string',
- title: intl.formatMessage({
- id: 'pages.system.password',
- defaultMessage: '密码',
- }),
- 'x-decorator': 'FormItem',
- 'x-component': 'Password',
- 'x-component-props': {
- checkStrength: true,
- placeholder: '请输入密码',
- },
- 'x-visible': model === 'add',
- // 'x-reactions': [
- // {
- // dependencies: ['.confirmPassword'],
- // fulfill: {
- // state: {
- // selfErrors:
- // '{{$deps[0].length > 8 && $deps[0].length > 8 && $self.value && $self.value !==$deps[0] ? "两次密码输入不一致" : ""}}',
- // },
- // },
- // },
- // ],
- name: 'password',
- 'x-validator': [
- {
- max: 64,
- message: '密码最多可输入64位',
- },
- {
- min: 8,
- message: '密码不能少于8位',
- },
- {
- required: model === 'add',
- message: '请输入密码',
- },
- {
- triggerType: 'onBlur',
- validator: (value: string) => {
- return new Promise((resolve) => {
- if (!value || value.length < 8 || value.length > 64) resolve('');
- service
- .validateField('password', value)
- .then((resp) => {
- if (resp.status === 200) {
- if (resp.result.passed) {
- resolve('');
- } else {
- resolve(model === 'edit' ? '' : resp.result.reason);
- }
- }
- resolve('');
- })
- .catch(() => {
- return '验证失败!';
- });
- });
- },
- },
- // {
- // checkStrength: true,
- // },
- ],
- },
- confirmPassword: {
- type: 'string',
- title: intl.formatMessage({
- id: 'pages.system.confirmPassword',
- defaultMessage: '确认密码?',
- }),
- 'x-decorator': 'FormItem',
- 'x-component': 'Password',
- 'x-component-props': {
- checkStrength: true,
- placeholder: '请再次输入密码',
- },
- 'x-visible': model === 'add',
- 'x-validator': [
- // {
- // max: 64,
- // message: '密码最多可输入64位',
- // },
- // {
- // min: 8,
- // message: '密码不能少于8位',
- // },
- {
- required: model === 'add',
- message: '请输入确认密码',
- },
- // {
- // checkStrength: true,
- // },
- ],
- 'x-reactions': [
- {
- dependencies: ['.password'],
- fulfill: {
- state: {
- selfErrors:
- '{{$deps[0] && $self.value && $self.value !== $deps[0] ? "两次密码输入不一致" : ""}}',
- },
- },
- },
- ],
- 'x-decorator-props': {},
- name: 'confirmPassword',
- },
- layout2: {
- type: 'void',
- 'x-decorator': 'FormGrid',
- 'x-decorator-props': {
- maxColumns: 2,
- minColumns: 2,
- columnGap: 24,
- },
- properties: {
- roleIdList: {
- title: '角色',
- 'x-decorator': 'FormItem',
- 'x-component': 'Select',
- 'x-component-props': {
- mode: 'multiple',
- showArrow: true,
- placeholder: '请选择角色',
- filterOption: (input: string, option: any) =>
- option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0,
- },
- 'x-reactions': ['{{useAsyncDataSource(getRole)}}'],
- 'x-decorator-props': {
- gridSpan: 1,
- addonAfter: (
- <PermissionButton
- // type="link"
- type="primary"
- ghost
- style={{ padding: '0 8px' }}
- isPermission={rolePermission.add && !!rolePath}
- onClick={() => {
- const tab: any = window.open(`${origin}/#${rolePath}?save=true`);
- tab!.onTabSaveSuccess = (value: any) => {
- form.setFieldState('roleIdList', async (state) => {
- state.dataSource = await getRole().then((resp) =>
- resp.result?.map((item: Record<string, unknown>) => ({
- ...item,
- label: item.name,
- value: item.id,
- })),
- );
- state.value = [...(state.value || []), value.id];
- });
- };
- }}
- >
- <PlusOutlined />
- </PermissionButton>
- ),
- },
- },
- orgIdList: {
- title: '组织',
- 'x-decorator': 'FormItem',
- 'x-component': 'TreeSelect',
- 'x-component-props': {
- multiple: true,
- showArrow: true,
- placeholder: '请选择组织',
- showCheckedStrategy: ATreeSelect.SHOW_ALL,
- filterOption: (input: string, option: any) =>
- option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0,
- fieldNames: {
- label: 'name',
- value: 'id',
- },
- treeNodeFilterProp: 'name',
- },
- 'x-decorator-props': {
- gridSpan: 1,
- addonAfter: (
- <PermissionButton
- // type="link"
- // style={{ padding: 0 }}
- type="primary"
- ghost
- style={{ padding: '0 8px' }}
- isPermission={deptPermission.add && !!departmentPath}
- onClick={() => {
- const tab: any = window.open(`${origin}/#${departmentPath}?save=true`);
- tab!.onTabSaveSuccess = (value: any) => {
- form.setFieldState('orgIdList', async (state) => {
- state.dataSource = await getOrg().then((resp) =>
- resp.result?.map((item: Record<string, unknown>) => ({
- ...item,
- label: item.name,
- value: item.id,
- })),
- );
- state.value = [...(state.value || []), value.id];
- });
- };
- }}
- >
- <PlusOutlined />
- </PermissionButton>
- ),
- },
- 'x-reactions': ['{{useAsyncDataSource(getOrg)}}'],
- },
- telephone: {
- title: '手机号',
- 'x-decorator': 'FormItem',
- 'x-component': 'Input',
- 'x-validator': [
- {
- format: 'phone',
- message: '请输入正确的手机号',
- },
- ],
- 'x-decorator-props': {
- gridSpan: 1,
- },
- 'x-component-props': {
- placeholder: '请输入手机号',
- },
- },
- email: {
- title: '邮箱',
- 'x-decorator': 'FormItem',
- 'x-component': 'Input',
- 'x-validator': [
- {
- format: 'email',
- message: '请输入正确的邮箱',
- },
- ],
- 'x-decorator-props': {
- gridSpan: 1,
- },
- 'x-component-props': {
- placeholder: '请输入邮箱',
- },
- },
- },
- },
- },
- };
- const save = async () => {
- const value = await form.submit<UserItem>();
- const temp: any = {};
- temp.id = value.id;
- temp.user = value;
- temp.user.roleList = [];
- temp.orgIdList = value.orgIdList;
- temp.roleIdList = value.roleIdList?.length ? value.roleIdList : null;
- const response = await service.saveUser(temp, model);
- if (response.status === 200) {
- onlyMessage(
- intl.formatMessage({
- id: 'pages.data.option.success',
- defaultMessage: '操作成功',
- }),
- );
- props.close();
- } else {
- onlyMessage('操作失败!', 'error');
- }
- };
- return (
- <Modal
- title={intl.formatMessage({
- id: `pages.data.option.${model}`,
- defaultMessage: '编辑',
- })}
- maskClosable={false}
- visible={model !== 'query'}
- onCancel={props.close}
- onOk={save}
- width="35vw"
- permissionCode={'system/User'}
- permission={['update']}
- >
- <Form form={form} layout="vertical">
- <SchemaField schema={schema} scope={{ useAsyncDataSource, getRole, getOrg }} />
- </Form>
- </Modal>
- );
- };
- export default Save;
|