import { useEffect, useState } from 'react';
import qs from 'query-string';
import { Button, message, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { TableDetailView } from '~/components/tableDetailView';
import { GetScoreListType } from '~/api/interface/pointManageType';
import { PointManageAPI } from '~/api';
import { ApproveModal } from '~/pages/pointManage/pointList/comp/approveModal';
import SearchView from '~/components/search-box';
import BankCardModal from './comp/bankCardModal';

// 列表的类型
type TableType = (ReturnType<GetScoreListType> extends Promise<infer T>
  ? T
  : never)['result']['list'];
// 请求的参数
type ReqType = Parameters<GetScoreListType>[0];
// 表单提交
let query: ReqType = {};
// 提现状态
const withdrawStatus = [
  { label: '处理中', value: 0 },
  { label: '已提现', value: 1 },
  { label: '提现失败', value: 2 },
];

function PointDetailList(props: any) {
  // 参数解析
  const option = qs.parse(props.location.search);
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 查看参数
  const [recordData, setRecordData] = useState<TableType[0]>();
  // 审批弹窗
  const [approveVisible, setApproveVisible] = useState(false);
  // 银行卡弹窗
  const [bankCardVisible, setBankCardVisible] = useState(false);
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  // 新版通用部分(ES6+ for React) ZhangLK 2022/08/30 Start
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await PointManageAPI.GetScoreList({
      type: option.type ? Number(option.type) : 0,
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list);
    } else {
      message.warning(res.message);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (data: any) => {
    const obj = {
      ...data,
    };
    pagination.current = 1;
    query = obj;
    getTableList({
      type: option.type ? option.type : 0,
      ...obj,
    }).then();
  };
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  // componentDidMount
  useEffect(() => {
    query = {};
    getTableList().then();
  }, []);
  // 类型列表
  const typeList: {
    label: string;
    value: string;
    columns: ColumnsType<TableType[0]>;
  }[] = [
    {
      label: '积分发放明细',
      value: '0',
      columns: [
        { title: 'UID', dataIndex: 'uid', align: 'center' },
        {
          title: '企业名称',
          dataIndex: 'entName',
          align: 'center',
          render: (text: string, record) => text || (record.phoneNum ? '微信用户' : '游客用户'),
        },
        { title: '手机号', dataIndex: 'phoneNum', align: 'center' },
        { title: '发放积分', dataIndex: 'releaseScore', align: 'center' },
        { title: '发放时间', dataIndex: 'releaseTime', align: 'center' },
      ],
    },
    {
      label: '积分兑换明细',
      value: '1',
      columns: [
        { title: 'UID', dataIndex: 'uid', align: 'center' },
        {
          title: '企业名称',
          dataIndex: 'entName',
          align: 'center',
          render: (text: string, record) => text || (record.phoneNum ? '微信用户' : '游客用户'),
        },
        { title: '手机号', dataIndex: 'phoneNum', align: 'center' },
        { title: '兑换积分', dataIndex: 'convertScore', align: 'center' },
        {
          title: '兑换比例',
          align: 'center',
          render: (_text, record) => `${record.score}:${record.coupon}`,
        },
        { title: '发放时间', dataIndex: 'convertTime', align: 'center' },
      ],
    },
    {
      label: '积分提现明细',
      value: '2',
      columns: [
        { title: 'UID', dataIndex: 'uid', align: 'center' },
        {
          title: '用户名称',
          dataIndex: 'userName',
          align: 'center',
          render: (text, record) => text || record?.nickName || `游客用户`,
          width: 80,
        },
        {
          title: '企业名称',
          dataIndex: 'entName',
          align: 'center',
          render: (text: string, record) => text || (record.phoneNum ? '微信用户' : '游客用户'),
        },
        { title: '手机号', dataIndex: 'phoneNum', align: 'center' },
        { title: '提现积分', dataIndex: 'withdrawScore', align: 'center' },
        {
          title: '银行卡',
          dataIndex: 'accountBank',
          align: 'center',
          render: (text: string, record) => (
            <>
              {text ? (
                <Button
                  type='link'
                  title='查看银行卡'
                  onClick={() => {
                    setRecordData(JSON.parse(JSON.stringify(record)));
                    setBankCardVisible(true);
                  }}
                >
                  {`${text} (${record?.bankCardNumber?.slice(-4)})`}
                </Button>
              ) : (
                '未绑定'
              )}
            </>
          ),
          width: 100,
        },
        {
          title: '状态',
          dataIndex: 'status',
          align: 'center',
          render: (text: number) => withdrawStatus?.find((i) => i.value === text)?.label || text,
        },
        { title: '提现时间', dataIndex: 'withdrawTime', align: 'center' },
        {
          title: '操作',
          align: 'center',
          render: (_text, record) => (
            <>
              <Button
                type='link'
                onClick={() => {
                  setRecordData(JSON.parse(JSON.stringify(record)));
                  setApproveVisible(true);
                }}
                disabled={record.status !== 0}
              >
                审批
              </Button>
            </>
          ),
        },
      ],
    },
  ];
  return (
    <>
      <TableDetailView
        isBack
        onCancel={() => {
          history.go(-1);
        }}
      >
        <div className='detail-table-label'>
          {typeList?.find((i) => i.value === (option.type || 0))?.label || '积分发放明细'}
        </div>
        {option && option.type === '2' && (
          <SearchView
            search={[
              {
                label: '兑换状态',
                name: 'status',
                type: 'select',
                placeholder: '请选择状态',
                options: withdrawStatus.map((i) => {
                  return { id: i.value, name: i.label };
                }),
              },
            ]}
            searchData={onFinish}
          />
        )}
        <Table
          size='small'
          dataSource={tableData}
          columns={
            typeList?.find((i) => i.value === (option.type || 0))?.columns || typeList[0].columns
          }
          rowKey='id'
          // scroll={{ x: 1500 }}
          bordered
          pagination={{
            total: pagination.total,
            pageSize: pagination.pageSize,
            current: pagination.current,
            showSizeChanger: true,
            showQuickJumper: true,
            onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
            showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
          }}
        />
      </TableDetailView>
      <ApproveModal
        open={approveVisible}
        data={{
          withdrawId: recordData?.id,
          ...recordData,
        }}
        title='提现审批'
        closed={() => {
          setApproveVisible(false);
          setRecordData(undefined);
          getTableList({
            type: option.type ? option.type : 0,
          }).then();
        }}
      />
      <BankCardModal
        open={bankCardVisible}
        data={recordData}
        title='查看银行卡'
        closed={() => {
          setBankCardVisible(false);
          setRecordData(undefined);
        }}
      />
    </>
  );
}

export default PointDetailList;
