import { useEffect, useState } from 'react';
import qs from 'query-string';
import { Button, Image, message, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import SearchBox, { searchColumns } from '~/components/search-box';
import { DetailTableType, DetailFormType } from '~/pages/customManage/customMoney/propsType';
// import { UserAPI } from '~/api';
import { ChangeModal } from '~/pages/customManage/customMoney/comp/ChangeModal';
import { moneyFormat } from '~/utils/money';
import { useNavigate, useSearchParams } from 'react-router-dom';

const CustomMoneyDetail = () => {
  // 路由操作
  const navigate = useNavigate();
  // 参数钩子
  const [searchParams] = useSearchParams();
  // 接收到的参数
  const id = searchParams.get('id');
  const uid = searchParams.get('uid');
  const userName = searchParams.get('userName');
  // 是否打开变更弹窗
  const [changeVisible, setChangeVisible] = useState<boolean>(false);
  // 搜索数据
  const [typeOptions, setTypeOptions] = useState<{ name: string; id: number }[]>([]);
  // 搜索数据
  const [searchColumns, setSearchColumns] = useState<searchColumns[]>([
    {
      label: '编号',
      name: 'payNo',
      type: 'input',
      placeholder: '请输入交易编号或订单编号',
      width: 220,
    },
    {
      label: '日期',
      name: 'time',
      type: 'rangePicker',
      placeholder: '开始时间~结束时间',
    },
    {
      label: '类型',
      name: 'type',
      type: 'select',
      options: [],
      placeholder: '请选择变更类型',
    },
  ]);
  // 表头
  const tableColumns: ColumnsType<DetailTableType> = [
    {
      title: '交易编号',
      dataIndex: 'payNo',
      align: 'center',
    },
    {
      title: '交易时间',
      dataIndex: 'payTime',
      align: 'center',
    },
    {
      title: '相关订单编号',
      dataIndex: 'orderTaskNo',
      align: 'center',
    },
    {
      title: '相关订单名称',
      dataIndex: 'orderTaskName',
      align: 'center',
    },
    {
      title: '相关账号',
      dataIndex: 'updateUserName',
      align: 'center',
    },
    {
      title: '变更类型',
      dataIndex: 'payType',
      align: 'center',
      render: (value) => {
        const item = typeOptions.find((i) => i.id === value);
        return item ? item.name : value;
      },
    },
    {
      title: '变动',
      dataIndex: 'amtPaid',
      align: 'center',
      render: (value) => {
        return value > 0 ? `+${moneyFormat(value)}` : moneyFormat(value);
      },
    },
    {
      title: '已冻结',
      dataIndex: 'cashFreeze',
      align: 'center',
      render: (value) => {
        return moneyFormat(value);
      },
    },
    {
      title: '余额',
      dataIndex: 'cashAmt',
      align: 'center',
      render: (value) => {
        return moneyFormat(value);
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center',
    },
    {
      title: '凭证',
      dataIndex: 'voucher',
      align: 'center',
      render: (value) => {
        if (value) {
          const list = value.split(',');
          return (
            <div style={{ display: 'flex', justifyContent: 'space-around' }}>
              {list.map((i: string, j: number) => (
                <Image key={j} style={{ width: '48px', height: '48px' }} src={i} alt='凭证' />
              ))}
            </div>
          );
        }
        return '无';
      },
    },
  ];
  // 表格数据
  const [tableData, setTableData] = useState<DetailTableType[]>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  const [query, setQuery] = useState({});
  // 新版通用部分(ES6+ for React) ZhangLK 2022/08/30 Start
  // 加载列表
  const getTableList = async (value = {}) => {
    setTableData([{ id: Number(id) }]);
    // 只需要修改这个地方的接口即可
    // const res: any = await UserAPI.getBountyFlow({
    //   mallUserId: Number(id),
    //   pageNo: pagination.current,
    //   pageSize: pagination.pageSize,
    //   ...value,
    // });
    // if (res && res.code === '200') {
    //   // console.log("res -->", res);
    //   const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
    //   setPagination({
    //     total: totalCount,
    //     pageSize,
    //     current: pageNo,
    //     totalPage,
    //   });
    //   setTableData(list);
    // } else {
    //   message.warning(res.message);
    // }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (val: DetailFormType) => {
    // 在这里对提交的数据做处理，如range转为开始和结束时间
    const data = Object.fromEntries(
      // 过滤为空项
      Object.entries({
        ...val,
        startTime: (val.time && val.time[0]) || undefined,
        endTime: (val.time && val.time[1]) || undefined,
        pageNo: 1,
      }).filter((i) => i[1] !== '' && i[1] !== undefined && i[1] !== null),
    );
    setQuery(data);
    getTableList(data).then();
  };
  // 返回上一页
  const handleBack = () => {
    navigate(-1);
  };
  // 获取所有类型
  const getTypeAll = async () => {
    // const res: any = await UserAPI.getTypeAll();
    // if (res.result && res.result.length != 0) {
    //   const optionList = res.result.map((v: any) => ({
    //     id: v.code,
    //     name: v.status,
    //   }));
    //   searchColumns.map((v) => {
    //     if (v.name === 'type') {
    //       v.options = optionList;
    //     }
    //   });
    //   setSearchColumns([...searchColumns]);
    //   setTypeOptions(optionList);
    // }
  };
  // componentDidMount
  useEffect(() => {
    getTypeAll().then();
    getTableList().then();
    console.log('searchParams --->', searchParams);
  }, []);
  return (
    <>
      <SearchBox
        search={searchColumns}
        searchData={onFinish}
        preFixBtn={
          <>
            <div>
              {uid}({userName})
            </div>
            <Button
              type='primary'
              onClick={() => {
                setChangeVisible(true);
              }}
            >
              奖励金变更
            </Button>
            <Button className='backButton' onClick={handleBack}>
              返回
            </Button>
          </>
        }
      />
      <Table
        size='small'
        rowKey='id'
        dataSource={tableData}
        columns={tableColumns}
        scroll={{ x: 1500 }}
        pagination={{
          total: pagination.total,
          pageSize: pagination.pageSize,
          current: pagination.current,
          showSizeChanger: true,
          onChange: (page, pageSize) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
        bordered
      />
      <ChangeModal
        visible={changeVisible}
        closed={() => {
          setChangeVisible(false);
          getTableList({ ...pagination, ...query }).then();
        }}
        data={
          {
            // mallUserId: Number(qs.parse(props.location.search).id),
            // uid: qs.parse(props.location.search).uid,
            // userName: qs.parse(props.location.search).userName,
          }
        }
      />
    </>
  );
};

export default CustomMoneyDetail;
