import SearchBox from '~/components/search-box';
import { searchColumns as searchColumnsType } from '~/components/search-box';
import { Button, Table } from 'antd';
import { ColumnsType } from 'antd/es/table/InternalTable';
import { DepleteManageTypeAPI } from '~/api';
import { useEffect, useState } from 'react';
import { InterDataType, InterListType, PaginationProps } from '~/api/interface';
import { listPageWithdrawalApplyType, statisticsType } from '~/api/interface/depleteManageType';
import { filterObjAttr } from '~/utils';
import ApplyStatusModal from '~/pages/depleteManage/withDrawList/components/applyStatusModal';
import { withdrawStatusList } from '~/utils/dictionary';
import './index.scss';

// 提现列表返回类型
type withdrawalApplyType = InterListType<listPageWithdrawalApplyType>;
// 提现列表请求类型
type withdrawalApplyParameterType = InterListType<listPageWithdrawalApplyType>;
// 提现数据统计返回类型
type statisticsDataType = InterDataType<statisticsType>;
// 提现方式字典
const settleTypeDic = [
  {
    label: '微信',
    value: 'wechat',
  },
  {
    label: '支付宝',
    value: 'alipay',
  },
  {
    label: '银行卡',
    value: 'bankcard',
  },
];

const WithDrawManage = () => {
  const searchColumns: searchColumnsType[] = [
    {
      label: '关键字',
      placeholder: '请输入关键字',
      name: 'keyword',
      type: 'input',
    },
    {
      label: '状态',
      placeholder: '请选择状态',
      name: 'tradeStatus',
      type: 'Select',
      options: withdrawStatusList,
    },
    {
      label: '提现方式',
      placeholder: '请选择提现方式',
      name: 'settleType',
      type: 'Select',
      options: settleTypeDic,
    },
    {
      label: '时间',
      name: 'time',
      type: 'rangePicker',
      placeholder: '',
    },
  ];
  const tableColumns: ColumnsType<withdrawalApplyType[0]> = [
    {
      title: '流水编号',
      align: 'center',
      dataIndex: 'outerTradeNo',
    },
    {
      title: '账户名称',
      align: 'center',
      dataIndex: 'empName',
    },
    {
      title: '金额',
      align: 'center',
      dataIndex: 'applyAmt',
      render: (text: number) => text.toFixed(2).toLocaleString(),
    },
    {
      title: '提现方式',
      align: 'center',
      dataIndex: 'settleType',
      render: (text: string) => settleTypeDic.find((v) => v.value === text)?.label || '',
    },
    {
      title: '手机号',
      align: 'center',
      dataIndex: 'phoneNum',
    },
    {
      title: '收款账号',
      align: 'center',
      dataIndex: 'payAccount',
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'tradeStatus',
      render: (text: string) => withdrawStatusList.find((v) => v.value === text)?.label || '',
    },
    {
      title: '处理信息',
      align: 'center',
      dataIndex: 'tradeResult',
    },
    {
      title: '申请时间',
      align: 'center',
      dataIndex: 'createTime',
    },
    {
      title: '备注',
      align: 'center',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      align: 'center',
      render: (_: any, record) => (
        <Button
          type='link'
          onClick={() => applyStatusEvent(record)}
          disabled={record.applyStatus !== 0}
        >
          审批
        </Button>
      ),
    },
  ];
  const [tableData, setTableData] = useState<withdrawalApplyType>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [query, setQuery] = useState<withdrawalApplyParameterType>();
  // 审批弹窗
  const [applyStatusModalShow, setApplyStatusModalShow] = useState<boolean>(false);
  // 当前审批对象
  const [currentWithDrawItem, setCurrentWithDrawItem] = useState<withdrawalApplyType[0]>();
  // 提现数据统计
  const [statisticsData, setStatisticsData] = useState<statisticsDataType>();

  // 获取提现列表
  const getListPageWithdrawalApply = (query?: withdrawalApplyParameterType) => {
    setLoading(true);
    DepleteManageTypeAPI.getListPageWithdrawalApply({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setLoading(false);
      pagination.totalCount = result.totalCount;
      setPagination({ ...pagination });
      setTableData(result.list || []);
    });
  };
  // 提现数据统计
  const getCashAmountAndWithdrawAmount = () => {
    DepleteManageTypeAPI.getCashAmountAndWithdrawAmount().then(({ result }) => {
      if (result) {
        setStatisticsData(result);
      }
    });
  };
  // 分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getListPageWithdrawalApply(query);
  };
  // 筛选成功
  const searchSuccess = (value: any) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    const filterQuery = filterObjAttr(value, ['time']);
    setQuery(filterQuery);
    getListPageWithdrawalApply(filterQuery);
    getCashAmountAndWithdrawAmount();
  };
  // 审批弹窗事件
  const applyStatusEvent = (record: withdrawalApplyType[0]) => {
    setCurrentWithDrawItem(record);
    setApplyStatusModalShow(true);
  };
  const applyStatusModalCancel = () => {
    setApplyStatusModalShow(false);
  };
  const applyStatusModalOk = () => {
    setApplyStatusModalShow(false);
    getListPageWithdrawalApply(query);
  };

  useEffect(() => {
    getListPageWithdrawalApply();
    getCashAmountAndWithdrawAmount();
  }, []);
  return (
    <div className='with-draw-manage'>
      <SearchBox
        search={searchColumns}
        searchData={searchSuccess}
        sufFixBtn={
          <div className='data-statistics'>
            <div>
              <span>已提现：</span>
              <span>
                {statisticsData?.totalWithdrawAmt
                  ? statisticsData?.totalWithdrawAmt.toFixed(2).toLocaleString()
                  : 0}
              </span>
            </div>
            <div>
              <span>账户余额：</span>
              <span>
                {statisticsData?.cashPoolAmount
                  ? statisticsData?.cashPoolAmount.toFixed(2).toLocaleString()
                  : 0}
              </span>
            </div>
          </div>
        }
      />
      <Table
        bordered
        columns={tableColumns}
        rowKey='id'
        dataSource={tableData}
        loading={loading}
        pagination={{
          total: pagination.totalCount,
          pageSize: pagination.pageSize,
          current: pagination.pageNo,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
      {/*审批*/}
      <ApplyStatusModal
        open={applyStatusModalShow}
        onCancel={applyStatusModalCancel}
        onOk={applyStatusModalOk}
        currentWithDrawItem={currentWithDrawItem}
      />
    </div>
  );
};
export default WithDrawManage;
