CommunicationHistoryModal.tsx 10.7 KB
import { RESPONSE_CODE } from '@/constants/enum';
import {
  postAdminClientAddOrModifyClientComunicationInfo,
  postAdminClientQueryClientComunicationInfo,
  postAdminClientRemoveClientComunicationInfo,
  postServiceConstClientWay,
  postServiceConstTradeStatus,
} from '@/services';
import { enumToSelect } from '@/utils';
import {
  ActionType,
  EditableProTable,
  ModalForm,
  ProFormInstance,
} from '@ant-design/pro-components';
import { Descriptions, Popconfirm, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import ClientModal from './ClientModal';
import InformationHistoryModal from './InformationHistoryModal';
export default ({ record }) => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState();
  const ref = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();
  const [refreshKey, setRefreshKey] = useState(0); // 用于强制刷新的键

  const reloadInformationHistoryModal = () => {
    actionRef.current.reload(); // 重新加载数据

    // 更新 refreshKey,强制刷新 CommunicationHistoryModal
    setRefreshKey((prevKey) => prevKey + 1);
  };
  const columns = [
    {
      title: '跟进时间',
      dataIndex: 'datetime',
      width: 50,
      valueType: 'dateTime',
      rules: [{ required: true, message: '请选择时间' }],
    },
    {
      title: '跟进人',
      width: 50,
      rules: [{ required: true, message: '请输入跟进人' }],
      dataIndex: 'updateByName',
    },
    {
      title: '跟进方式',
      width: 50,
      dataIndex: 'way',
      rules: [{ required: true, message: '请选择方式' }],
      render: (text, record) => record.wayText, // 显示 wayText
      request: async () => {
        const res = await postServiceConstClientWay();
        return enumToSelect(res.data);
      },
    },
    {
      title: '跟进状态',
      width: 50,
      dataIndex: 'tradeStatus',
      rules: [{ required: true, message: '请选择方式' }],
      render: (text, record) => record.tradeStatusLike, // 显示 wayText
      request: async () => {
        const res = await postServiceConstTradeStatus();
        return enumToSelect(res.data);
      },
    },
    {
      title: '跟进详情',
      width: 80,
      valueType: 'textarea',
      rules: [{ required: true, message: '请输入内容' }],
      dataIndex: 'content',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 60,
      render: (text, record, _, action) => [
        // <a
        //   key="editable"
        //   onClick={() => {
        //     action?.startEditable?.(record.tid);
        //   }}
        // >
        //   编辑
        // </a>,
        <InformationHistoryModal
          // key={'communicationHistory'}
          key={`communicationHistory-${refreshKey}`} // 使用 refreshKey 来强制更新组件
          data={record}
          // reloadTable={() => {
          //   actionRef.current.reload();
          //   console.log('5656flush');
          // }}
          reloadTable={reloadInformationHistoryModal}
        />,
        <Popconfirm
          key={'delete'}
          title="删除记录"
          description="确认删除记录?"
          onConfirm={async () => {
            setDataSource(dataSource.filter((item) => item.tid !== record.tid));
            const res = await postAdminClientRemoveClientComunicationInfo({
              query: {
                id: record.id,
              },
            });
            if (res.result === RESPONSE_CODE.SUCCESS) {
              message.success(res.message);
              action?.reload();
            } else {
              message.error('删除失败');
            }
          }}
          okText="是"
          cancelText="否"
        >
          <a type={'danger'}>删除</a>
        </Popconfirm>,
      ],
    },
  ];
  const [name, setName] = useState(''); // 客户名称
  const [leaderName, setLeaderName] = useState(''); // 负责人
  const [sourceText, setSourceText] = useState(''); // 来源文本
  const [phoneNumber, setPhoneNumber] = useState(''); // 联系电话
  const [institutionContactName, setInstitutionContactName] = useState(''); // 联系电话
  const [department, setDepartment] = useState(''); // 联系电话
  const [gradePosition, setGradePosition] = useState(''); // 联系电话
  const [referrers, setReferrers] = useState(''); // 推荐人
  const [levelText, setLevelText] = useState(''); // 客户等级文本
  const [createTime, setCreateTime] = useState(null); // 最新沟通时间
  const [address, setAddress] = useState(''); // 客户地址
  const [notes, setNotes] = useState(''); // 备注信息
  const [createByName, setCreateByName] = useState(''); // 创建人
  const [latestObject, setLatestObject] = useState(); // 最新跟进时间
  const [recordSave, setRecordSave] = useState(); //新增跟进
  useEffect(() => {
    const request = async () => {
      const resShow = await postAdminClientQueryClientComunicationInfo({
        data: {
          clientId: record.id,
        },
      });
      if (resShow?.data?.data !== null) {
        const data = resShow?.data?.data;
        // const latest = data.reduce((latest: any, current: any) => {
        //   return new Date(current.updateTime) > new Date(latest.updateTime) ? current : latest;
        // });
        // const data = [];
        const latestObject2 =
          data?.length > 0
            ? data.reduce((latest, current) =>
                new Date(current.datetime) > new Date(latest.datetime)
                  ? current
                  : latest,
              )
            : null; // 或返回其他默认值
        setLatestObject(latestObject2?.datetime);
      }
      setRecordSave(record);
      setName(record.name);
      setLeaderName(record.leaderName);
      setSourceText(record.sourceText);
      setPhoneNumber(record.phoneNumber);
      setInstitutionContactName(record.institutionContactName);
      setDepartment(record.department);
      setGradePosition(record.gradePosition);
      setReferrers(record.referrers);
      setLevelText(record.levelText);
      setCreateTime(record.createTime);
      setAddress(record.address);
      setNotes(record.notes);
      setCreateByName(record.createByName);
    };
    request();
  }, []);
  const items = [
    {
      key: '1',
      label: '客户名称',
      children: name, // 客户名称
    },
    {
      key: '2',
      label: '负责人',
      children: leaderName, // 负责人
    },
    {
      key: '3',
      label: '来源',
      children: sourceText, // 来源文本
    },
    {
      key: '4',
      label: '联系电话',
      children: phoneNumber, // 联系电话
    },
    {
      key: '5',
      label: '课题组',
      children: institutionContactName, // 推荐人
    },
    {
      key: '6',
      label: '部门',
      children: department, // 推荐人
    },
    {
      key: '7',
      label: '年级/职位',
      children: gradePosition, // 推荐人
    },
    {
      key: '8',
      label: '推荐人',
      children: referrers, // 推荐人
    },
    {
      key: '10',
      label: '客户等级',
      children: levelText, // 客户等级文本
    },
    {
      key: '11',
      label: '创建时间',
      children: createTime, // 最新沟通时间
    },
    {
      key: '12',
      label: '客户地址',
      children: address, // 客户地址
    },
    {
      key: '13',
      label: '备注',
      children: notes, // 备注信息
    },
    {
      key: '14',
      label: '创建人',
      children: createByName, // 创建人
    },
    {
      key: '15',
      label: '最新跟进时间',
      children: latestObject, // 最新跟进时间
    },
  ];
  return (
    <ModalForm
      title="客户详情"
      trigger={<a type="primary">查看</a>}
      modalProps={{
        destroyOnClose: true,
      }}
      onFinish={async () => {
        return true;
      }}
    >
      <Descriptions items={items} column={2} />
      <ClientModal
        key={'add'}
        data={recordSave}
        reloadTable={() => {
          actionRef.current?.reload();
        }}
        type={'add2'}
      />
      <EditableProTable
        rowKey="tid"
        formRef={ref}
        actionRef={actionRef}
        recordCreatorProps={false}
        // recordCreatorProps={{
        //   record: () => ({ tid: (Math.random() * 1000000).toFixed(0) }),
        // }}
        loading={false}
        columns={columns}
        request={async () => {
          const res = await postAdminClientQueryClientComunicationInfo({
            data: {
              clientId: record.id,
            },
          });
          if (res.result === RESPONSE_CODE.SUCCESS) {
            console.log(JSON.stringify(res.data));
            return {
              ...res.data,
              data: res.data.data.map((item) => {
                return {
                  ...item,
                  tid: (Math.random() * 1000000).toFixed(0),
                };
              }),
            };
          } else {
            message.error('获取失败');
          }
        }}
        value={dataSource}
        onChange={setDataSource}
        editable={{
          type: 'multiple',
          editableKeys,
          onSave: async (rowKey, data, row) => {
            console.log(rowKey, data, row);
            if (data?.way === '拜访') {
              data.way = 'VISIT';
            } else if (data?.way === '电话') {
              data.way = 'PHONE';
            } else if (data?.way === '微信') {
              data.way = 'WECHAT';
            } else if (data?.way === '邮件') {
              data.way = 'EMAIL';
            } else if (data?.way === '其他') {
              data.way = 'OTHER';
            }
            const res = await postAdminClientAddOrModifyClientComunicationInfo({
              data: {
                ...data,
                clientId: record.id,
              },
            });
            if (res.result === RESPONSE_CODE.SUCCESS) {
              message.success(res.message);
            } else {
              message.error('修改失败');
            }
            actionRef.current?.reload();
          },
          onChange: setEditableRowKeys,
        }}
      />
      {/* <Descriptions title="User Info" items={items} column={2} /> */}
      {/*<ProCard title="表格数据" headerBordered collapsible defaultCollapsed>
                <ProFormField
                    ignoreFormItem
                    fieldProps={{
                        style: {
                            width: '100%',
                        },
                    }}
                    mode="read"
                    valueType="jsonCode"
                    text={JSON.stringify(dataSource)}
                />
            </ProCard>*/}
    </ModalForm>
  );
};