广州市综治平台前端
liuwh
5 days ago be89af3bf4d7e591ef085f55f1de7c28fcf5f6a8
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/*
 * @Author: dminyi 1301963064@qq.com
 * @Date: 2024-08-29 17:41:09
 * @LastEditors: lwh
 * @LastEditTime: 2025-06-21 11:56:05
 * @FilePath: \gzDyh\gz-customerSystem\src\components\SelectObjModal\selectPerson.jsx
 * @Description: 选择经办人
 */
import React, { useState, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import { Button, Space, Input, Tree } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import './index.less';
import * as $$ from '../../utils/utility';
import { Modal, Spin } from '@arco-design/web-react';
 
const { Search } = Input;
 
const txtMap = {
  supUnit: '组织',
  dept: '部门',
  person: '人',
  unit: '组织'
}
 
// 获取人员,组织,部门数据
function getDataApi(type, searchData, caseId) {
  let url
  switch (type) {
    case 'dept':
      // url = `ctUnit/unitChoose`
      url = `ctUnit/unitTree`
      break;
    case 'person':
      url = 'ctUser/userChoose'
      break
    case 'unit':
      url = 'ctUser/unitList'
      break
    case 'supUnit':
      url = `caseInfoUnfold/superviceUnitChoose?caseId=${caseId}`
      break
    default:
      break;
  }
  return $$.ax.request({ url, type: 'get', data: searchData, service: type === 'supUnit' ? 'mediate' : 'cust' });
}
 
/**
 * visible, // 传入参数控制modal显示
 * checkKeys, // 选中,数据格式 [{value:'',label':''}]
 * type, // 'person': 选择人员 'unit': 选择组织 'dept': 选择部门 'supUnit': 督办组织
 * isCheckbox, // 是否多选
 * searchData, // 搜索条件
 * onClose, // 关闭
 * onOk, // 点击确定的回调
 */
const SelectObjModal = ({ visible = false, nameStr, checkKeys = [], type = 'dept', isCheckbox = false, searchData = {}, onClose, onOk, caseId }) => {
  // 默认调解员查询'22_00024-4'
  const searchRole = type === 'person' ? { roleCode: '22_00024-4' } : {};
  const [data, setData] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState({ keys: [], items: [] });
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [dataList, setDataList] = useState([]);
  const [loading, setLoading] = useState(false);
  // 新增状态:用于区分是否为搜索状态
  const [isSearchMode, setIsSearchMode] = useState(false);
 
  // 获取第一层级的key
  const getFirstLevelKeys = (treeData) => {
    return treeData.map(item => item.value);
  };
 
  // tree复选框选择
  function handleCheck(checkedKeys, e) {
    if (!isCheckbox && checkedKeys.length > 1) {
      $$.info({ type: 'warning', content: '当前选择只可单选' });
      return;
    }
    setCheckedKeys({ keys: checkedKeys, items: e.node });
  }
 
  // 删除选项
  function handleDelete(t) {
    checkedKeys.keys.splice(t, 1);
    checkedKeys.items.splice(t, 1);
    setCheckedKeys({ ...checkedKeys });
  }
 
  const getParentKey = (key, tree) => {
 
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.value === key)) {
          parentKey = node.value;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };
 
  // 获取所有父节点
  const getAllParentKeys = (key, tree, parents = []) => {
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.value === key)) {
          parents.push(node.value);
          getAllParentKeys(node.value, tree, parents);
        } else {
          getAllParentKeys(key, node.children, parents);
        }
      }
    }
    return parents;
  };
 
  // 检查节点或其子节点是否包含搜索值
  const hasMatchingChild = (node, searchValue) => {
    if (node.label.indexOf(searchValue) > -1) {
      return true;
    }
    if (node.children) {
      return node.children.some(child => hasMatchingChild(child, searchValue));
    }
    return false;
  };
 
  // 获取搜索时需要展开的所有节点key
  const getExpandedKeysForSearch = (searchValue, treeData) => {
    const expandedKeys = [];
    
    const traverse = (nodes, parentKeys = []) => {
      nodes.forEach(node => {
        const currentPath = [...parentKeys, node.value];
        
        // 如果当前节点匹配搜索值
        if (node.label.indexOf(searchValue) > -1) {
          // 添加所有父节点到展开列表
          expandedKeys.push(...parentKeys);
          // 添加当前节点到展开列表
          expandedKeys.push(node.value);
        }
        
        // 如果当前节点有子节点,继续遍历
        if (node.children && node.children.length > 0) {
          traverse(node.children, currentPath);
        }
      });
    };
    
    traverse(treeData);
    return Array.from(new Set(expandedKeys));
  };
 
  function handleSearch(value, dataList) {
    if (!value.trim()) {
      // 如果搜索值为空,恢复到初始状态
      const firstLevelKeys = getFirstLevelKeys(data);
      setExpandedKeys(firstLevelKeys);
      setSearchValue('');
      setAutoExpandParent(false);
      setIsSearchMode(false);
      return;
    }
 
    // 使用新的函数来精确计算需要展开的节点
    const newExpandedKeys = getExpandedKeysForSearch(value, data);
 
    setExpandedKeys(newExpandedKeys);
    setSearchValue(value);
    setAutoExpandParent(true);
    // 设置为搜索模式
    setIsSearchMode(true);
  }
 
  function handleSearch1(value, dataList) {
    if (!value.trim()) {
      // 如果搜索值为空,恢复到初始状态
      const firstLevelKeys = getFirstLevelKeys(data);
      setExpandedKeys(firstLevelKeys);
      setSearchValue('');
      setAutoExpandParent(false);
      setIsSearchMode(false);
      return;
    }
 
    // 使用新的函数来精确计算需要展开的节点
    const newExpandedKeys = getExpandedKeysForSearch(value, data);
 
    setExpandedKeys(newExpandedKeys);
    setSearchValue(value);
    setAutoExpandParent(true);
    // 设置为搜索模式
    setIsSearchMode(true);
  }
 
  useEffect(() => {
    if (!visible) return;
    // 获取数据
    async function getData() {
      setLoading(true)
      const res = await getDataApi(type, { ...searchRole, ...searchData }, caseId);
      setLoading(false)
      if (res.type) {
        setData(res.data || []);
      }
    }
    if (checkKeys.length !== 0) {
      setCheckedKeys({ keys: checkKeys, items: [] });
    } else {
      setCheckedKeys({ keys: [], items: [] });
    }
    // 重置搜索模式
    setIsSearchMode(false);
    getData();
  }, [type, visible]);
 
  console.log('checkedKeys', checkedKeys);
 
  // 搜索
  useEffect(() => {
    if (!visible) return;
    const arr = [];
    const generateList = (data) => {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const { value, label } = node;
        arr.push({ value, label });
        if (node.children) {
          generateList(node.children);
        }
      }
    };
    generateList(data);
    setDataList(arr);
    
    // 初始化时只展开第一层级,不调用handleSearch
    if (data.length > 0 && !isSearchMode) {
      const firstLevelKeys = getFirstLevelKeys(data);
      setExpandedKeys(firstLevelKeys);
      setAutoExpandParent(false);
    }
  }, [data]);
 
  const treeData = useMemo(() => {
    const loop = (data) => {
      const copiedData = JSON.parse(JSON.stringify(data));
      return copiedData.map((item, idx) => {
        const strTitle = item.label;
        const index = strTitle.indexOf(searchValue);
 
        // 如果有搜索值,只保留包含 searchValue 的项或有匹配子节点的项
        if (searchValue && index <= -1 && !hasMatchingChild(item, searchValue)) {
          return null; // 返回 null 表示不包含在最终结果中
        }
 
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);
        const label =
          index > -1 ? (
            <span>
              {beforeStr}
              <span className="selectObjModal-searchValue">{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{strTitle}</span>
          );
 
        if (item.children) {
          const filteredChildren = loop(item.children).filter(Boolean); // 递归处理子项并过滤掉 null
          return {
            label,
            name: strTitle,
            value: item.value,
            disabled: item.checkable ? false : true,
            checkable: item.checkable,
            children: filteredChildren.length > 0 ? filteredChildren : undefined,
          };
        }
 
        return {
          label,
          name: strTitle,
          disabled: item.checkable ? false : true,
          checkable: item.checkable,
          value: item.value,
        };
      }).filter(Boolean); // 过滤掉 null
    };
    return loop(data);
  }, [searchValue, data]);
 
  return (
    <Modal
      visible={!!visible}
      title={`选择${nameStr}`}
      footer={null}
      onCancel={onClose}
      unmountOnExit={true}
      maskClosable={false}
      style={{ width: '560px' }}
    >
      <div className="selectObjModal-main">
        <div style={{ width: "100%" }}>
          <div className="selectObjModal-left-search" style={{ paddingRight: '0px' }}>
            <Search 
              placeholder={`查询${nameStr}名称`} 
              value={searchValue}
              onChange={(e) => {
                const value = e.target.value;
                if (!value.trim()) {
                  // 清空搜索时恢复到初始状态
                  const firstLevelKeys = getFirstLevelKeys(data);
                  setExpandedKeys(firstLevelKeys);
                  setSearchValue('');
                  setAutoExpandParent(false);
                  setIsSearchMode(false);
                } else {
                  // 实时搜索,使用相同的展开逻辑
                  const newExpandedKeys = getExpandedKeysForSearch(value, data);
                  setExpandedKeys(newExpandedKeys);
                  setSearchValue(value);
                  setAutoExpandParent(true);
                  setIsSearchMode(true);
                }
              }}
              onSearch={(e) => handleSearch1(e, dataList)} 
            />
          </div>
          <div className="selectObjModal-left-main">
            <Spin loading={loading} style={{ width: '100%', height: '100%' }}>
              {data.length > 0 ? (
                <Tree
                  checkStrictly
                  // defaultExpandAll
                  onExpand={(newExpandedKeys) => {
                    setExpandedKeys(newExpandedKeys);
                    setAutoExpandParent(false);
                  }}
                  expandedKeys={expandedKeys}
                  // autoExpandParent={autoExpandParent}
                  onSelect={(checkedKeys, e) => {
                    handleCheck(checkedKeys, e);
                    onOk && onOk(e.node)
                  }}
                  selectedKeys={checkedKeys.keys}
                  treeData={treeData}
                  fieldNames={{ title: 'label', key: 'value' }}
                  height={400}
                />
              ) : (
                $$.MyEmpty()
              )}
            </Spin>
          </div>
        </div>
      </div>
    </Modal>
  );
};
 
SelectObjModal.propTypes = {
  visible: PropTypes.any,
  checkKeys: PropTypes.array,
  type: PropTypes.string,
  isCheckbox: PropTypes.bool,
  searchData: PropTypes.object,
  onClose: PropTypes.func,
  onOk: PropTypes.func,
};
 
export default SelectObjModal;