ResearchGroupAddModal.tsx 16.4 KB
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 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
import { RESPONSE_CODE } from '@/constants/enum';
import {
  postCanrdApiUserAddressList,
  postCanrdApiUserList,
  postResearchGroupsAdd,
  postResearchGroupsDetail,
  postResearchGroupsEdit,
} from '@/services';
import { getDefaultString, isEmpty } from '@/utils/StringUtil';
import { getRandomNumber } from '@/utils/numberUtil';
import { getSalesCodeOptions } from '@/utils/order';
import { validatePhoneNumberBool } from '@/utils/validators';
import {
  ModalForm,
  ProCard,
  ProForm,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { Button, Form, Spin, message } from 'antd';
import { cloneDeep } from 'lodash';
import { useEffect, useState } from 'react';
import '../index.less';

// import { cloneDeep } from 'lodash';
export default ({ setVisible, researchGroupId, onClose }) => {
  const [form] = Form.useForm();
  const [salesCodeOptions, setSalesCodeOptions] = useState([]);
  const [memberOptions, setMemberOptions] = useState<any[]>([]);
  const [accountOptions, setAccountOptions] = useState<any[]>([]);
  const [researchGroupInfo, setResearchGroupInfo] = useState<any>(null);
  const [modalLoading, setModalLoading] = useState(false);
  const groupId = cloneDeep(researchGroupId);
  const [requestCount, setRequestCount] = useState(1);

  /**
   * 获取课题组信息
   * @returns
   */
  const loadResearchGroupInfo = async () => {
    if (groupId === null) {
      return;
    }
    setModalLoading(true);
    let res = await postResearchGroupsDetail({ data: { id: groupId } });
    if (res && res.result === RESPONSE_CODE.SUCCESS) {
      setResearchGroupInfo(res.data);
    }
    setModalLoading(false);
  };

  /**
   * 获取销售代码枚举,在复制和编辑的时候判断是否为旧的代码
   */
  const loadSalesCodeOptions = async () => {
    let options = await getSalesCodeOptions();
    setSalesCodeOptions(options);
  };

  /**
   * 对options去重
   * @param options
   * @returns
   */
  function deduplicateOptions(options: any) {
    const seen = new Set();
    const result: any[] = [];
    options.forEach((option: any) => {
      const uniqueKey = `${option.realName}-${option.phone}`;
      if (!seen.has(uniqueKey)) {
        seen.add(uniqueKey);
        result.push(option);
      }
    });
    return result;
  }

  /**
   * 自动填充客户信息
   * @param option
   */
  function autoFillCustomerInfo(option: any) {
    if (!option) {
      return;
    }
    let realName = option.realName;
    let id = option.value;
    if (id === 3.1415926) {
      message.warning(
        '请填写下方的【客户名称】和【手机号】,填写完成确保信息无误后点击添加按钮。',
      );
      form.setFieldValue('realName', option.name);
      return;
    }
    //判断当前客户信息是否已添加过:id匹配或者option的phone匹配说明添加过了
    let memberIds = form.getFieldValue('members');
    if (!memberIds) {
      //表单项没值的时候默认是undefined。初始化为数组
      memberIds = [];
    }
    if (memberIds.includes(id)) {
      message.info(`${realName} 重复添加`);
      return;
    }
    //表单项的value添加当前option的value
    memberIds.push(id);
    form.setFieldValue('members', memberIds);
    message.success(`${realName} 添加成功`);
    //判断options中是否已经有这个option
    for (let memberOption of memberOptions) {
      if (
        memberIds.includes(memberOption.value) &&
        memberOption.phone === option.phone
      ) {
        return;
      }
    }
    //option添加到memberOptions中
    let newMemberOptions = [...memberOptions];
    newMemberOptions.push(option);
    setMemberOptions(newMemberOptions);

    //清空信息
    form.setFieldValue('realName', undefined);
    form.setFieldValue('phone', undefined);
    form.setFieldValue('customerName', null);
  }

  /**
   * 保存account的options
   * @param option
   * @returns
   */
  function autoAccountSelectOptions(option: any) {
    if (!option) {
      return;
    }
    let id = option.value;
    //判断当前客户信息是否已添加过:id匹配或者option的phone匹配说明添加过了
    let accountIds = form.getFieldValue('accounts');
    if (!accountIds) {
      //表单项没值的时候默认是undefined。初始化为数组
      accountIds = [];
    }
    if (accountIds.includes(id)) {
      return;
    }
    //option添加到accountOptions中
    setAccountOptions(option);
  }

  /**
   * 添加自定义成员
   */
  function addCustomMember() {
    let realName = form.getFieldValue('realName');
    let phone = form.getFieldValue('phone');
    if (isEmpty(realName)) {
      message.error('请填写客户名称');
    }
    if (isEmpty(phone)) {
      message.error('请填写手机号');
    }
    if (!validatePhoneNumberBool(phone)) {
      message.error('请填写正确格式的手机号');
      return;
    }
    let customOption = {
      value: getRandomNumber(10),
      realName: realName,
      phone: phone,
    };
    autoFillCustomerInfo(customOption);
  }

  function parseFormValues(values: any) {
    if (!values) {
      return {};
    }

    let memberIds = values.members;
    let accountIds = values.accounts;
    values.id = groupId;

    //成员对象封装
    if (memberIds) {
      let memberObjs: any[] = [];
      for (let memberOption of memberOptions) {
        if (memberIds.includes(memberOption.value)) {
          memberObjs.push({
            memberName: memberOption.realName,
            memberPhone: memberOption.phone,
            id: memberOption.id,
            groupId: memberOption.groupId,
          });
        }
      }
      values.members = memberObjs;
    }

    //预存账号对象封装
    if (accountIds) {
      let accountObjs: any[] = [];
      for (let accountOption of accountOptions) {
        if (accountIds.includes(accountOption.uid)) {
          accountObjs.push({
            accountPhone: accountOption.phone,
            accountId: accountOption.uid,
            accountName: accountOption.realName,
            id: accountOption.id,
            groupId: accountOption.groupId,
          });
        }
      }
      values.accounts = accountObjs;
    }

    return values;
  }

  /**
   * 设置表单默认信息
   * @returns
   */
  const loadFormDefaultValue = async () => {
    if (!researchGroupInfo) {
      return;
    }

    let members = researchGroupInfo.members;
    if (members !== null) {
      let newMemberOptions = [];
      for (let member of members) {
        let name = member.memberName;
        let phone = member.memberPhone;
        let id = member.id;
        newMemberOptions.push({
          ...member,
          realName: name,
          phone: phone,
          value: id,
        });
      }
      setMemberOptions(newMemberOptions);
      form.setFieldValue(
        'members',
        members?.map((item: any) => {
          return item.id;
        }),
      );
    }

    let accounts = researchGroupInfo.accounts;
    if (accounts !== null) {
      let phones: any[] = [];
      let accountIds = accounts
        .filter((account: any) => {
          //id为空的按照手机号查询
          if (account.accountId === null) {
            phones.push(account.accountPhone);
            return false;
          }
          return true;
        })
        .map((item: any) => item.accountId);

      let uidIdMap = new Map(
        accounts.map((item: any) => [item.accountId, item.id]),
      );
      let res = await postCanrdApiUserList({
        data: { uids: accountIds, phones: phones },
      });
      if (res && res.result === RESPONSE_CODE.SUCCESS) {
        let accountList = res?.data?.data;
        console.log(accountList);
        let newAccountOptions = accountList?.map((item) => {
          item.value = uidIdMap.get(item.uid);
          return item;
        });

        console.log(newAccountOptions);
        setAccountOptions(newAccountOptions);
      }

      form.setFieldValue('accounts', accountIds);
    }

    form.setFieldValue('group', researchGroupInfo.groupName);
    form.setFieldValue('leader', researchGroupInfo.leaderName);
  };

  useEffect(() => {
    loadSalesCodeOptions();
    loadResearchGroupInfo();
  }, []);

  useEffect(() => {
    loadFormDefaultValue();
  }, [researchGroupInfo]);

  return (
    <div className="research-group-index">
      <ModalForm
        width={800}
        open
        title="新增/编辑课题组"
        form={form}
        autoFocusFirstInput
        submitter={{}}
        modalProps={{
          okText: '提交',
          cancelText: '关闭',
          destroyOnClose: true,
          onCancel: () => {
            setVisible(false);
          },
        }}
        onFinish={async (values) => {
          let newValues = parseFormValues(values);
          let res;
          if (researchGroupInfo === null) {
            res = await postResearchGroupsAdd({
              data: newValues,
            });
          } else {
            res = await postResearchGroupsEdit({
              data: newValues,
            });
          }
          if (res && res.result === RESPONSE_CODE.SUCCESS) {
            message.success(res.message);
            onClose();
          }
        }}
        onOpenChange={setVisible}
      >
        <Spin spinning={modalLoading} tip="加载中...">
          <ProForm.Group>
            <ProFormText
              name="group"
              label="课题组名称"
              placeholder="请输入课题组名称"
              rules={[{ required: true, message: '请输入课题组名称' }]}
            />
            <ProFormSelect
              name="leader"
              key="leader"
              width="lg"
              showSearch
              label="负责人"
              placeholder="请输入课题组负责人"
              rules={[{ required: true, message: '请输入课题组负责人' }]}
              options={salesCodeOptions}
            />
          </ProForm.Group>

          <ProFormSelect
            name="accounts"
            key="accounts"
            width="lg"
            showSearch
            label="绑定预存账号(可多选)"
            placeholder="请选择预存账号"
            onChange={(_, option) => {
              autoAccountSelectOptions(option);
            }}
            rules={[{ required: true, message: '请至少选择绑定一个预存账号' }]}
            fieldProps={{
              mode: 'multiple',
              filterOption() {
                return true;
              },
              optionItemRender(item: any) {
                let name =
                  item.label +
                  ' | ' +
                  item.institution +
                  ' | ' +
                  item.nowMoney +
                  '¥' +
                  ' | ' +
                  item.phone;
                return (
                  <div title={name}>
                    <span style={{ color: '#333333' }}>{name}</span>
                  </div>
                );
              },
            }}
            debounceTime={1000}
            request={async (value, {}) => {
              const keywords = value.keyWords;
              let body = {
                keywords: keywords,
                pageSize: 20,
                researchGroupId: undefined,
              };

              if (requestCount === 1) {
                body.researchGroupId = groupId;
              }

              const res = await postCanrdApiUserList({
                data: body,
              });
              let options = res?.data?.data?.map((c: any) => {
                return {
                  ...c,
                  label: c.realName,
                  value: c.uid,
                  key: c.uid,
                };
              });

              setRequestCount(requestCount + 1);
              return options;
            }}
          />

          <ProFormSelect
            name="members"
            key="members"
            width="lg"
            showSearch
            label="课题组成员"
            placeholder="请添加课题组成员"
            fieldProps={{
              mode: 'multiple',
              filterOption() {
                return true;
              },
              optionItemRender(item: any) {
                let name = item.realName + ' | ' + item.phone;
                return (
                  <div title={name}>
                    <span style={{ color: '#333333' }}>{name}</span>
                  </div>
                );
              },
            }}
            options={memberOptions}
          />

          <ProCard
            title="选择或自定义课题组成员信息"
            bordered
            tooltip="从【客户信息】选择框中可以直接搜索客户,选中后自动添加到【课题组成员】中。也可以自定义输入【客户名称】和【手机号】,点击添加按钮手动添加到【课题组成员】中。"
          >
            <ProForm.Group>
              <ProFormSelect
                key="customerName"
                label="客户信息(选择)"
                width="lg"
                showSearch
                name="customerName"
                placeholder="请选择客户信息"
                onChange={(_, option) => {
                  autoFillCustomerInfo(option);
                }}
                fieldProps={{
                  filterOption() {
                    return true;
                  },
                  optionItemRender(item: any) {
                    if (item.type === 'add') {
                      return (
                        <div title={item.name + '(新增客户)'}>
                          <span style={{ color: '#333333' }}>{item.name}</span>
                          {' | '}
                          <span style={{ color: 'orange' }}>自定义</span>
                        </div>
                      );
                    }

                    let title = '';
                    let spanText = '';
                    let realName = item.realName;
                    let phone = item.phone;

                    title =
                      getDefaultString(realName) +
                      '|' +
                      getDefaultString(phone);

                    spanText =
                      getDefaultString(realName) +
                      '|' +
                      getDefaultString(phone);
                    return (
                      <div title={title}>
                        <span style={{ color: '#333333' }}>{spanText}</span>
                      </div>
                    );
                  },
                }}
                debounceTime={1000}
                request={async (value, {}) => {
                  const keywords = value.keyWords;
                  if (keywords === '') {
                    return [];
                  }
                  const res = await postCanrdApiUserAddressList({
                    data: { keywords: keywords },
                  });
                  let options = res?.data?.map((c: any) => {
                    return {
                      ...c,
                      label: c.name,
                      value: c.id,
                      key: c.id,
                    };
                  });

                  //对options去重,realName和phone唯一
                  options = deduplicateOptions(options);

                  //第一个商品默认为要新增客户
                  if (keywords.trim() !== '') {
                    options.unshift({
                      name: keywords,
                      type: 'add',
                      label: keywords,
                      value: 3.1415926,
                      key: keywords,
                    });
                  }

                  return options;
                }}
              />
            </ProForm.Group>

            <ProForm.Group>
              <ProFormText
                name="realName"
                label="客户名称(自定义)"
                placeholder="请输入客户名称"
                rules={[{ required: false, message: '请输入客户名称' }]}
              />
              <ProFormText
                name="phone"
                label="手机号(自定义)"
                width="md"
                placeholder="请输入手机号"
                rules={[{ required: false, message: '请输入手机号' }]}
              />
            </ProForm.Group>
            <Button
              type="primary"
              onClick={() => {
                addCustomMember();
              }}
            >
              添加
            </Button>
          </ProCard>
        </Spin>
      </ModalForm>
    </div>
  );
};