Blame view

src/pages/Prepaid/PrivatePocket/components/AddPrivatePocketModal.tsx 6.8 KB
1
import {
柏杨 authored
2
  postCanrdApiUserList,
3
4
5
6
  postCanrdPrivatePocketSave,
  postServiceOrderQuerySalesCode,
} from '@/services';
import { getUserInfo } from '@/utils/user';
柏杨 authored
7
import { Form, Modal, Select, message } from 'antd';
8
import React, { useEffect, useRef, useState } from 'react';
9
10
11
12
13
14
15
16
17
18
19
20

interface AddPrivatePocketModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

interface SalesCodeItem {
  number: string | null;
  userName: string;
}
柏杨 authored
21
22
23
24
25
26
27
28
29
interface UserItem {
  uid: string;
  realName: string;
  institution?: string;
  nowMoney?: string | number;
  phone: string;
  [key: string]: any;
}
30
31
32
33
34
35
36
37
const AddPrivatePocketModal: React.FC<AddPrivatePocketModalProps> = ({
  visible,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [salesCodeList, setSalesCodeList] = useState<SalesCodeItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
柏杨 authored
38
39
  const [userList, setUserList] = useState<any[]>([]);
  const [searchKeywords, setSearchKeywords] = useState<string>('');
40
41
  const userInfo = getUserInfo();
  const userName = userInfo?.username || '';
42
  const searchTimerRef = useRef<any>(null);
43
44
45
46
47
48
49
50
51
52
53
54
55

  const fetchSalesCodeList = async () => {
    try {
      const res = await postServiceOrderQuerySalesCode();
      if (res?.data) {
        setSalesCodeList(res.data);
      }
    } catch (error) {
      console.error('获取销售编码列表失败:', error);
      message.error('获取销售编码列表失败');
    }
  };
柏杨 authored
56
57
58
  // Define a function to fetch user list that can be called from multiple places
  const fetchUserList = async (keywords: string) => {
    try {
59
60
61
62
      if (!keywords || keywords.trim() === '') {
        return [];
      }
柏杨 authored
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
      const res = await postCanrdApiUserList({
        data: { keywords: keywords, pageSize: 1000000 },
      });

      if (res?.data?.data) {
        setUserList(res.data.data);
      }
      return res?.data?.data || [];
    } catch (error) {
      console.error('获取用户列表失败:', error);
      return [];
    }
  };

  // Initial fetch when component mounts
  useEffect(() => {
    if (visible) {
      fetchUserList('');
    }
  }, [visible]);
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
  useEffect(() => {
    if (visible) {
      fetchSalesCodeList();
      form.resetFields();
    }
  }, [visible, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const res = await postCanrdPrivatePocketSave({
        data: {
          account: values.account,
          salesCode: values.salesCode,
          createByName: userName,
        },
      });
104
      if (res?.result === 0 || res?.code === 200 || res?.success) {
105
106
107
108
109
110
111
112
113
114
115
116
        message.success('添加隐私钱包成功');
        onSuccess();
      } else {
        message.error(res?.message || '添加失败');
      }
    } catch (error) {
      console.error('添加隐私钱包失败:', error);
    } finally {
      setLoading(false);
    }
  };
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
  // Function to handle search with debounce
  const handleSearch = (value: string) => {
    setSearchKeywords(value);

    // Clear any existing timer
    if (searchTimerRef.current) {
      clearTimeout(searchTimerRef.current);
    }

    // Set a new timer to fetch users after 1000ms of inactivity
    searchTimerRef.current = setTimeout(() => {
      fetchUserList(value);
    }, 1000);
  };
132
133
134
135
136
137
138
139
140
141
142
143
144
  return (
    <Modal
      title="添加隐私钱包"
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      destroyOnClose
    >
      <Form form={form} layout="vertical">
        <Form.Item
          name="account"
          label="绑定普通账户"
柏杨 authored
145
          rules={[{ required: true, message: '请选择账户' }]}
146
        >
柏杨 authored
147
148
149
150
151
152
153
          <Select
            showSearch
            placeholder="请选择账户"
            optionFilterProp="children"
            defaultActiveFirstOption={false}
            notFoundContent={null}
            filterOption={false} // Disable built-in filtering to use server-side search
154
            onSearch={handleSearch} // Use the debounced search handler
柏杨 authored
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
            onChange={(value) => {
              // When a value is selected, find the corresponding phone from userList
              // or use the value directly if it's a custom entry

              // Check if this is a custom entry (value is the same as searchKeywords)
              if (value === searchKeywords && searchKeywords.trim() !== '') {
                form.setFieldsValue({ account: searchKeywords });
                return;
              }

              // Find the selected user from userList to get their phone
              const selectedUser = userList.find((user) => user.uid === value);
              if (selectedUser && selectedUser.phone) {
                form.setFieldsValue({ account: selectedUser.phone });
              }
            }}
            dropdownRender={(menu) => (
              <div>
                {menu}
                {searchKeywords.trim() !== '' && (
                  <div
                    style={{
                      padding: '8px',
                      cursor: 'pointer',
                      borderTop: '1px solid #e8e8e8',
                    }}
                    onClick={() => {
                      form.setFieldsValue({ account: searchKeywords });
                    }}
                  >
                    <span style={{ color: '#333333' }}>{searchKeywords}</span>
                    {' | '}
                    <span style={{ color: 'orange' }}>自定义</span>
                  </div>
                )}
              </div>
            )}
          >
            {userList.map((user: UserItem) => {
              const displayText = `${user.realName || '-'} | ${
                user.institution || '-'
              } | ${user.nowMoney || '0'}¥ | ${user.phone || '-'}`;
              return (
                <Select.Option
                  key={user.uid}
                  value={user.uid}
                  title={displayText}
                >
                  <div>
                    <span>{displayText}</span>
                  </div>
                </Select.Option>
              );
            })}
          </Select>
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
        </Form.Item>
        <Form.Item
          name="salesCode"
          label="负责销售"
          rules={[{ required: true, message: '请选择负责销售' }]}
        >
          <Select
            placeholder="请选择负责销售"
            showSearch
            optionFilterProp="children"
            filterOption={(input, option) =>
              (option?.label?.toString() || '')
                .toLowerCase()
                .includes(input.toLowerCase())
            }
            options={salesCodeList.map((item) => ({
              value: item.userName,
              label: item.userName,
            }))}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddPrivatePocketModal;