import React, { useEffect, useState } from 'react';
import { Button, message, Table } from 'antd';
import qs from 'query-string';
import { PlusOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import SearchView from '~/components/search-box';
import { UserScoreDetailsListType } from '~/api/interface/pointManageType';
import { PointManageAPI } from '~/api';
import { DetailModal } from '../comp/detailModal';
import { DistributionModal } from '~/pages/pointManage/pointList/comp/distributionModal';
import { ApproveModal } from '~/pages/pointManage/pointList/comp/approveModal';
import useOperate from '~/common/hook/optionHook';
import { useSearchParams } from 'react-router-dom';

// 列表的类型
type TableType = (ReturnType<UserScoreDetailsListType> extends Promise<infer T>
  ? T
  : never)['result']['list']['userScoreList'];
// 后台返回的类型，但不是列表
type ListType = (ReturnType<UserScoreDetailsListType> extends Promise<infer T>
  ? T
  : never)['result']['list'];
// 状态类型
const statusList = [
  { value: 0, label: '提现中' },
  { value: 1, label: '提现成功' },
  { value: 2, label: '提现失败' },
];
export function PointDetail(props: { location: { search: string } }) {
  const [searchParams] = useSearchParams();
  // 参数解析
  const option = qs.parse(props.location.search);
  // 路由操作
  const navigate = useNavigate();
  // 金额数据
  const [pointData, setPointData] = useState<ListType>();
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 查看参数
  const [recordData, setRecordData] = useState<TableType[0]>();
  // 显示查看弹窗
  const [detailVisible, setDetailVisible] = useState(false);
  // 积分发放弹窗
  const [distributionVisible, setDistributionVisible] = useState(false);
  // 审批弹窗
  const [approveVisible, setApproveVisible] = useState(false);
  // 按钮权限
  const isDistributePointBtnShow = useOperate(25101);
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  // 新版通用部分(ES6+ for React) ZhangLK 2022/08/30 Start
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await PointManageAPI.UserScoreDetailsList({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      mallUserId: Number(option.id),
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list.userScoreList);
      setPointData(res?.result?.list);
    } else {
      message.warning(res.message);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '积分数值',
      dataIndex: 'scoreNum',
      align: 'center',
      render: (text) => (text > 0 ? `+${text}` : text),
    },
    { title: '流通方式', dataIndex: 'type', align: 'center' },
    { title: '兑换比例', dataIndex: 'convertRatio', align: 'center' },
    { title: '领取时间', dataIndex: 'getTime', align: 'center' },
    {
      title: '使用时间',
      dataIndex: 'useTime',
      align: 'center',
      render: (_text, record) => {
        if (record?.type === '积分提现' && record?.status === 0) {
          return '';
        }
        if (record?.type === '积分提现' && record?.status === 2) {
          return '';
        }
        if (record?.type === '积分提现' && record?.status === 1) {
          return record?.approvalTime;
        }
        return record?.useTime;
      },
    },
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      align: 'center',
      render: (text, record) =>
        !!text && (
          <Button
            type='link'
            onClick={() => {
              // 跳转到订单列表
              navigate({
                pathname: '/orderManage/list/detail',
                search: qs.stringify({ id: record.orderId, activeTabKey: 1 }),
              });
            }}
          >
            {text}
          </Button>
        ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      render: (text) => statusList.find((i) => i.value === text)?.label || text,
    },
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      width: 180,
      render: (_text, record) => {
        return (
          <>
            {record.status === 0 && (
              <Button
                type='link'
                onClick={() => {
                  setRecordData(JSON.parse(JSON.stringify(record)));
                  setApproveVisible(true);
                }}
              >
                审批
              </Button>
            )}
            <Button
              type='link'
              onClick={() => {
                setRecordData(JSON.parse(JSON.stringify(record)));
                setDetailVisible(true);
              }}
            >
              查看
            </Button>
          </>
        );
      },
    },
  ];
  // 一键关闭全部弹窗
  const handleCloseAll = () => {
    setDetailVisible(false);
    setDistributionVisible(false);
    setApproveVisible(false);
    setRecordData(undefined);
    getTableList().then();
  };
  // 组件加载
  useEffect(() => {
    console.log('获取参数 --->', searchParams.get('id'));
    (async () => {
      await getTableList();
    })();
  }, []);
  return (
    <>
      <SearchView
        preFixBtn={
          <div>
            {pointData?.uid}&nbsp;{pointData?.userName}({pointData?.nickName})
          </div>
        }
        sufFixBtn={
          <div className='point-list-head-number'>
            <div className='head-number'>
              <span className='number-label'>积分总额</span>
              <Button type='link'>{pointData?.scoreTotal}</Button>
            </div>
            <div className='head-number'>
              <span className='number-label'>已使用积分</span>
              <Button type='link'>{pointData?.useScore}</Button>
            </div>
            <div className='head-number'>
              <span className='number-label'>已兑换积分</span>
              <Button type='link'>{pointData?.convertScore}</Button>
            </div>
            <div className='head-number'>
              <Button
                type='primary'
                icon={<PlusOutlined />}
                onClick={() => {
                  setDistributionVisible(true);
                }}
                disabled={!isDistributePointBtnShow}
              >
                积分发放
              </Button>
            </div>
          </div>
        }
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={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} 条数据`,
        }}
      />
      <DetailModal
        open={detailVisible}
        data={recordData}
        title='查看详情'
        closed={handleCloseAll}
      />
      <DistributionModal
        open={distributionVisible}
        data={pointData}
        title='发放积分'
        closed={handleCloseAll}
      />
      <ApproveModal
        open={approveVisible}
        data={recordData}
        title='提现审批'
        closed={handleCloseAll}
      />
    </>
  );
}
