wsj
3 days ago 71719ffa0eeb4a28a1b736f87499bcda2847a848
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
import { useCallback, useEffect, useMemo, useState } from 'react';
import { ProFormSelect, ProFormTreeSelect } from '@ant-design/pro-components';
import {
  App as AntdApp,
  Button,
  Drawer,
  Form,
  Input,
  InputNumber,
  Select,
  Space,
} from 'antd';
import { createOrg, getLeaderDetail, getLeaderOptions, updateOrg } from '../service';
import type { DepartmentFormValues, OrgVO } from '../types';
import { toOrgTreeSelectData } from '../utils';
 
interface DepartmentFormDrawerProps {
  open: boolean;
  mode: 'create' | 'edit';
  /** 编辑对象;新增时为空。 */
  record: OrgVO | null;
  /** 新增子部门时的上级组织 ID。 */
  parentId?: number;
  /** 组织树,用于上级组织选择。 */
  orgTree: OrgVO[];
  onClose: () => void;
  onSuccess: () => void;
}
 
const DepartmentFormDrawer = ({
  open,
  mode,
  record,
  parentId,
  orgTree,
  onClose,
  onSuccess,
}: DepartmentFormDrawerProps) => {
  const [form] = Form.useForm<DepartmentFormValues>();
  const [submitting, setSubmitting] = useState(false);
  const { message } = AntdApp.useApp();
  const isEdit = mode === 'edit';
  /** 新增入口只有「新增子部门」,上级组织已确定,不允许再选择。 */
  const parentDisabled = !isEdit;
 
  const parentOptions = useMemo(
    () => toOrgTreeSelectData(orgTree, isEdit ? record?.id : undefined),
    [isEdit, orgTree, record],
  );
 
  /** 负责人远程搜索:按姓名 / 手机号模糊查询员工。 */
  const requestLeaderOptions = useCallback(
    async ({ keyWords }: { keyWords?: string }) => {
      const keyword = keyWords?.trim();
      const result = await getLeaderOptions({
        page: 1,
        size: 50,
        keyword: keyword || undefined,
      });
      const options = (result.records ?? []).map((employee) => ({
        label: employee.name,
        value: employee.id,
      }));
 
      // 编辑时把当前负责人补进首屏选项,避免回填后显示为员工 ID。
      const currentLeaderId = isEdit ? record?.leaderId : undefined;
      if (
        !keyword &&
        currentLeaderId &&
        !options.some((option) => option.value === currentLeaderId)
      ) {
        try {
          const leader = await getLeaderDetail({ id: currentLeaderId });
          options.unshift({ label: leader.name, value: leader.id });
        } catch {
          // 错误已由 request 统一提示
        }
      }
 
      return options;
    },
    [isEdit, record],
  );
 
  useEffect(() => {
    if (!open) return;
 
    form.resetFields();
    form.setFieldsValue(
      isEdit && record
        ? {
            orgName: record.orgName,
            orgType: record.orgType ?? 'DEPT',
            parentId: record.parentId ?? undefined,
            leaderId: record.leaderId ?? undefined,
            region: record.region,
            sortOrder: record.sortOrder,
          }
        : {
            orgType: 'DEPT',
            parentId,
          },
    );
  }, [form, isEdit, open, parentId, record]);
 
  const handleSubmit = useCallback(async () => {
    let values: DepartmentFormValues;
    try {
      values = await form.validateFields();
    } catch {
      return;
    }
 
    setSubmitting(true);
 
    try {
      if (isEdit && record) {
        await updateOrg({ id: record.id, ...values });
        message.success('部门已更新');
      } else {
        await createOrg(values);
        message.success('部门创建成功');
      }
 
      onSuccess();
    } catch {
      // 错误已由 request 统一提示
    } finally {
      setSubmitting(false);
    }
  }, [form, isEdit, message, onSuccess, record]);
 
  const title = isEdit ? '编辑部门' : '新增子部门';
 
  return (
    <Drawer
      title={title}
      width={420}
      open={open}
      forceRender
      onClose={onClose}
      footer={
        <Space style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <Button onClick={onClose}>取消</Button>
          <Button type="primary" loading={submitting} onClick={handleSubmit}>
            {isEdit ? '保存' : '创建'}
          </Button>
        </Space>
      }
    >
      <Form form={form} layout="vertical" preserve={false}>
        <Form.Item
          name="orgName"
          label="部门名称"
          rules={[{ required: true, whitespace: true, message: '请输入部门名称' }]}
        >
          <Input placeholder="请输入部门名称" maxLength={50} />
        </Form.Item>
        <Form.Item
          name="orgType"
          label="组织类型"
          rules={[{ required: true, message: '请选择组织类型' }]}
        >
          <Select
            placeholder="请选择组织类型"
            options={[
              { label: '总部', value: 'HQ' },
              { label: '分公司', value: 'BRANCH' },
              { label: '经销商', value: 'DEALER' },
              { label: '代理商', value: 'AGENT' },
              { label: '部门', value: 'DEPT' },
              { label: '团队', value: 'TEAM' },
            ]}
          />
        </Form.Item>
        <ProFormTreeSelect
          name="parentId"
          label="上级组织"
          placeholder="不选则作为根组织"
          disabled={parentDisabled}
          fieldProps={{
            treeData: parentOptions,
            treeDefaultExpandAll: true,
            allowClear: true,
            showSearch: true,
            treeNodeFilterProp: 'title',
            style: { width: '100%' },
          }}
        />
        <ProFormSelect
          name="leaderId"
          label="负责人"
          rules={isEdit ? undefined : [{ required: true, message: '请选择负责人' }]}
          placeholder="请输入姓名搜索负责人"
          showSearch
          allowClear
          debounceTime={300}
          request={requestLeaderOptions}
          fieldProps={{ filterOption: false, style: { width: '100%' } }}
        />
        <Form.Item name="region" label="所在地区">
          <Input placeholder="请输入所在地区" maxLength={50} />
        </Form.Item>
        <Form.Item name="sortOrder" label="同级排序">
          <InputNumber
            min={0}
            precision={0}
            placeholder="数字越小越靠前"
            style={{ width: '100%' }}
          />
        </Form.Item>
      </Form>
    </Drawer>
  );
};
 
export default DepartmentFormDrawer;