index.tsx 10.1 KB
import ButtonConfirm from '@/components/ButtomConfirm';
import EllipsisDiv from '@/components/Div/EllipsisDiv';
import { RESPONSE_CODE } from '@/constants/enum';
import {} from '@/pages/Invoice/constant';
import {
  postCanrdApiUserList,
  postPrepaidDelete,
  postPrepaidList,
} from '@/services';
import { enumValueToLabel, formatDateTime } from '@/utils';
import { PlusOutlined } from '@ant-design/icons';
import { ActionType, ProTable } from '@ant-design/pro-components';
import { Button, Divider, Image, Tabs, message } from 'antd';
import { cloneDeep } from 'lodash';
import React, { useRef, useState } from 'react';
import CheckModal from '../Order/components/CheckModal';
import { CHECK_TYPE } from '../Order/constant';
import BalanceChangeRecordsModal from './components/BalanceChangeRecordsModal';
import RechargePrepaymentModal from './components/RechargePrepaymentModal';
import {
  ACCOUNT_COLUMNS,
  PREPAID_STATUS_OPTIONS,
  SALES_RECHARGE_PREPAYMENT_COLUMNS,
} from './constant';
import './index.less';
const PrepaidPage = () => {
  const prepaidActionRef = useRef<ActionType>();
  const accountActionRef = useRef<ActionType>();
  const [rechargePrepaymentModalVisible, setRechargePrepaymentModalVisible] =
    useState(false);
  const [currentOptPrepaymentObj, setCurrentOptPrepaymentObj] = useState(null);
  const [currentOptUserObj, setCurrentOptUserObj] = useState(null);
  const [checkVisible, setCheckVisible] = useState(false);
  const [
    balanceChangeRecordsModalVisible,
    setBalanceChangeRecordsModalVisible,
  ] = useState(false);

  const reloadPrepaidTable = () => {
    prepaidActionRef.current?.reload();
  };

  const reloadAccountTable = () => {
    accountActionRef.current?.reload();
  };

  const getTableCellText = (target: any) => {
    if (!target) {
      return '';
    }

    if (target.props) {
      return target.props.text;
    }

    return target;
  };

  /**
   * 加载发票列表表格的各个列格式
   */
  const prepaidColumnsInit = () => {
    let columns = SALES_RECHARGE_PREPAYMENT_COLUMNS.map((item) => {
      let newItem = { ...item };
      let dataIndex = item.dataIndex;

      newItem.render = (text, record) => {
        let textValue = record[dataIndex];

        if (dataIndex === 'status') {
          textValue = enumValueToLabel(textValue, PREPAID_STATUS_OPTIONS);
        }

        if (dataIndex.endsWith('Time')) {
          textValue = formatDateTime(textValue);
        }

        if (
          dataIndex === 'proofImages' &&
          textValue !== null &&
          textValue !== undefined
        ) {
          console.log(textValue);
          return (
            <Image.PreviewGroup
              className="mr-10"
              preview={{
                onChange: (current, prev) =>
                  console.log(`current index: ${current}, prev index: ${prev}`),
              }}
            >
              {textValue.map((item, index) => (
                <React.Fragment key={index}>
                  {index > 0 ? <Divider type="vertical" /> : ''}
                  <Image
                    className="max-h-[35px] max-w-[45px]"
                    src={item}
                    title={item}
                  />{' '}
                </React.Fragment>
              ))}
            </Image.PreviewGroup>
          );
        }

        return <EllipsisDiv text={textValue} />;
      };

      return newItem;
    });

    columns.push({
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 120,
      render: (text, record) => {
        let btns = [];
        let opts = record.operations;
        if (opts?.includes('modify')) {
          btns.push(
            <Button
              className="p-0"
              key="modify"
              type="link"
              onClick={() => {
                setRechargePrepaymentModalVisible(true);
                setCurrentOptPrepaymentObj(cloneDeep(record));
              }}
            >
              编辑
            </Button>,
          );
        }

        if (opts?.includes('audit')) {
          btns.push(
            <Button
              className="p-0"
              key="view"
              type="link"
              onClick={() => {
                setCurrentOptPrepaymentObj(record);
                setCheckVisible(true);
              }}
            >
              审核
            </Button>,
          );
        }

        if (opts?.includes('delete')) {
          btns.push(
            <ButtonConfirm
              key="delete"
              className="p-0"
              title={'确认删除这条预存记录吗?'}
              text="删除"
              onConfirm={async () => {
                let res = await postPrepaidDelete({
                  data: { ids: [record.id] },
                });
                if (res && res.result === RESPONSE_CODE.SUCCESS) {
                  message.success(res.message);
                  reloadPrepaidTable();
                }
              }}
            />,
          );
        }
        return btns;
      },
    });

    return columns;
  };

  const accountColumnsInit = () => {
    let columns = ACCOUNT_COLUMNS.map((item) => {
      let newItem = { ...item };
      let dataIndex = item.dataIndex;

      newItem.render = (text, record) => {
        let textValue = record[dataIndex];
        return <EllipsisDiv text={getTableCellText(textValue)} />;
      };

      return newItem;
    });

    columns.push({
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 120,
      render: (text, record) => {
        let btns = [];
        btns.push(
          <Button
            className="p-0"
            key="view"
            type="link"
            onClick={() => {
              setCurrentOptUserObj(record);
              setBalanceChangeRecordsModalVisible(true);
            }}
          >
            消费记录
          </Button>,
        );
        return btns;
      },
    });

    return columns;
  };

  const tabsItems = [
    {
      key: 1,
      label: '预存管理',
      children: (
        <ProTable
          columns={prepaidColumnsInit()}
          actionRef={prepaidActionRef}
          cardBordered
          pagination={{
            pageSize: 10,
          }}
          request={async (params) => {
            const res = await postPrepaidList({
              data: { ...params },
            });
            return {
              data: res?.data?.data || [],
              total: res?.data?.total || 0,
            };
          }}
          columnsState={{
            persistenceKey: 'pro-table-singe-prepaid',
            persistenceType: 'localStorage',
            defaultValue: {
              option: { fixed: 'right', disable: true },
            },
            onChange(value) {
              console.log('value: ', value);
            },
          }}
          rowKey="id"
          search={{
            labelWidth: 'auto',
          }}
          options={{
            setting: {
              listsHeight: 400,
            },
          }}
          form={{}}
          dateFormatter="string"
          headerTitle="预存管理"
          scroll={{ x: 1400 }}
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                setCurrentOptPrepaymentObj(null);
                setRechargePrepaymentModalVisible(true);
              }}
              type="primary"
            >
              新建
            </Button>,
          ]}
        />
      ),
    },
    {
      key: 2,
      label: '账号列表',
      children: (
        <ProTable
          columns={accountColumnsInit()}
          actionRef={accountActionRef}
          cardBordered
          pagination={{
            pageSize: 10,
          }}
          request={async (params) => {
            const res = await postCanrdApiUserList({
              data: { ...params },
            });
            return {
              data: res?.data?.data || [],
              total: res?.data?.total || 0,
            };
          }}
          columnsState={{
            persistenceKey: 'pro-table-singe-account',
            persistenceType: 'localStorage',
            defaultValue: {
              option: { fixed: 'right', disable: true },
            },
            onChange(value) {
              console.log('value: ', value);
            },
          }}
          rowKey="id"
          search={{
            labelWidth: 'auto',
          }}
          options={{
            setting: {
              listsHeight: 400,
            },
          }}
          form={{}}
          dateFormatter="string"
          headerTitle="账号列表"
          scroll={{ x: 1400 }}
          toolBarRender={() => []}
        />
      ),
    },
  ];
  return (
    <div className="prepaid-index">
      <Tabs
        defaultActiveKey="1"
        items={tabsItems}
        onChange={(value) => {
          if (value === '1') {
            reloadPrepaidTable();
          } else {
            reloadAccountTable();
          }
        }}
      />

      {rechargePrepaymentModalVisible && (
        <RechargePrepaymentModal
          setVisible={setRechargePrepaymentModalVisible}
          onClose={() => {
            setRechargePrepaymentModalVisible(false);
            reloadPrepaidTable();
          }}
          prepaymentObject={currentOptPrepaymentObj}
        />
      )}

      {checkVisible && (
        <CheckModal
          setCheckVisible={(val: boolean) => {
            setCheckVisible(val);
          }}
          data={[currentOptPrepaymentObj]}
          subOrders={[currentOptPrepaymentObj]}
          orderCheckType={CHECK_TYPE.PREPAID_AUDIT}
          openOrderDrawer={false}
          onClose={() => {
            setCheckVisible(false);
            reloadPrepaidTable();
          }}
        />
      )}

      {balanceChangeRecordsModalVisible && (
        <BalanceChangeRecordsModal
          setVisible={(val: boolean) => {
            setBalanceChangeRecordsModalVisible(val);
          }}
          userInfoObj={currentOptUserObj}
          onClose={() => {
            setBalanceChangeRecordsModalVisible(false);
          }}
        />
      )}
    </div>
  );
};

export default PrepaidPage;