wsj
4 days ago fe1692fd7f4f307fea8054da6c6c50d5df2bf2d8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  App as AntdApp,
  Button,
  Cascader,
  Drawer,
  Form,
  Input,
  InputNumber,
  Select,
  Space,
  Spin,
} from 'antd';
import { createEmployee, getEmployeeDetail, updateEmployee } from '../server';
import type {
  EmployeeFormValues,
  EmployeeVO,
  OrgTreeNode,
  SelectOption,
} from '../types';
 
interface OrgCascaderOption {
  value: number;
  label: string;
  children?: OrgCascaderOption[];
}
 
/** 组织树转为级联选择选项,按层级展示。 */
const toCascaderOptions = (nodes: OrgTreeNode[]): OrgCascaderOption[] =>
  nodes.map((node) => ({
    value: node.id,
    label: node.orgName,
    children: node.children?.length ? toCascaderOptions(node.children) : undefined,
  }));
 
/** 在组织树中查找某个组织 ID 的完整路径,用于编辑 / 详情时回填级联值。 */
const findOrgPath = (nodes: OrgTreeNode[], targetId: number): number[] | null => {
  for (const node of nodes) {
    if (node.id === targetId) return [node.id];
 
    const childPath = node.children ? findOrgPath(node.children, targetId) : null;
    if (childPath) return [node.id, ...childPath];
  }
 
  return null;
};
 
export type UserFormMode = 'create' | 'edit' | 'detail';
 
interface UserFormDrawerProps {
  open: boolean;
  mode: UserFormMode;
  /** 编辑 / 详情对象;新增时为空。 */
  record: EmployeeVO | null;
  /** 组织树,用于所属组织的二级联动选择。 */
  orgTree: OrgTreeNode[];
  roleOptions: SelectOption[];
  onClose: () => void;
  onSuccess: () => void;
}
 
const toFormValues = (
  employee: EmployeeVO,
  orgTree: OrgTreeNode[],
): EmployeeFormValues => ({
  name: employee.name,
  phone: employee.phone,
  orgPath: findOrgPath(orgTree, employee.orgId) ?? [],
  roleId: employee.roleId,
  position: employee.position,
  email: employee.email,
  holdLimit: employee.holdLimit,
  region: employee.region,
});
 
const UserFormDrawer = ({
  open,
  mode,
  record,
  orgTree,
  roleOptions,
  onClose,
  onSuccess,
}: UserFormDrawerProps) => {
  const [form] = Form.useForm<EmployeeFormValues>();
  const [submitting, setSubmitting] = useState(false);
  const [loading, setLoading] = useState(false);
  const { message } = AntdApp.useApp();
  const isDetail = mode === 'detail';
  const orgCascaderOptions = useMemo(() => toCascaderOptions(orgTree), [orgTree]);
 
  useEffect(() => {
    if (!open) return;
 
    let active = true;
 
    const initForm = async () => {
      form.resetFields();
 
      if (mode === 'detail') {
        if (!record) return;
 
        setLoading(true);
        try {
          const data = await getEmployeeDetail({ id: record.id });
          if (active) form.setFieldsValue(toFormValues(data, orgTree));
        } catch {
          // 错误已由 request 统一提示
          if (active) onClose();
        } finally {
          if (active) setLoading(false);
        }
        return;
      }
 
      if (mode === 'edit' && record) {
        form.setFieldsValue(toFormValues(record, orgTree));
      }
    };
 
    void initForm();
 
    return () => {
      active = false;
    };
  }, [form, mode, onClose, open, orgTree, record]);
 
  const handleSubmit = useCallback(async () => {
    if (isDetail) return;
 
    let values: EmployeeFormValues;
    try {
      values = await form.validateFields();
    } catch {
      return;
    }
 
    setSubmitting(true);
 
    const { orgPath, ...rest } = values;
    const orgId = orgPath[orgPath.length - 1];
 
    try {
      if (mode === 'edit' && record) {
        await updateEmployee({ id: record.id, ...rest, orgId });
        message.success('员工信息已更新');
      } else {
        await createEmployee({ ...rest, orgId });
        message.success('员工创建成功');
      }
 
      onSuccess();
    } catch {
      // 错误已由 request 统一提示
    } finally {
      setSubmitting(false);
    }
  }, [form, isDetail, message, mode, onSuccess, record]);
 
  const title = mode === 'create' ? '新增员工' : mode === 'edit' ? '编辑员工' : '员工详情';
 
  return (
    <Drawer
      title={title}
      width={420}
      open={open}
      forceRender
      onClose={onClose}
      footer={
        <Space style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <Button onClick={onClose}>{isDetail ? '关闭' : '取消'}</Button>
          {!isDetail && (
            <Button type="primary" loading={submitting} onClick={handleSubmit}>
              {mode === 'edit' ? '保存' : '创建'}
            </Button>
          )}
        </Space>
      }
    >
      <Spin spinning={loading}>
        <Form form={form} layout="vertical" preserve={false}>
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入员工姓名" disabled={isDetail} />
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
            ]}
          >
            <Input placeholder="请输入手机号" maxLength={11} disabled={isDetail} />
          </Form.Item>
          <Form.Item
            name="orgPath"
            label="所属组织"
            rules={[{ required: true, message: '请选择所属组织' }]}
          >
            <Cascader
              options={orgCascaderOptions}
              changeOnSelect
              showSearch
              placeholder="请选择所属组织"
              disabled={isDetail}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item
            name="roleId"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select
              showSearch
              optionFilterProp="label"
              options={roleOptions}
              placeholder="请选择角色"
              disabled={isDetail}
            />
          </Form.Item>
          <Form.Item name="position" label="职位">
            <Input placeholder="请输入职位" disabled={isDetail} />
          </Form.Item>
          <Form.Item name="region" label="负责区域">
            <Input placeholder="请输入负责区域" disabled={isDetail} />
          </Form.Item>
          <Form.Item name="holdLimit" label="客户持有上限">
            <InputNumber
              min={0}
              precision={0}
              style={{ width: '100%' }}
              disabled={isDetail}
            />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[{ type: 'email', message: '请输入正确的邮箱' }]}
          >
            <Input placeholder="请输入邮箱" disabled={isDetail} />
          </Form.Item>
        </Form>
      </Spin>
    </Drawer>
  );
};
 
export default UserFormDrawer;