import { useEffect, useState } from 'react';
import { ColumnsType } from 'antd/es/table';
import { Button, message, Table } from 'antd';
import SearchView from '~/components/search-box';
import { PointManageAPI } from '~/api';
import { OrderBonusListPageType } from '~/api/interface/pointManageType';
import { DivideSetting } from '~/pages/pointManage/divideOrder/comp/divideSetting';
import './index.scss';

// 列表的类型
type TableType = (ReturnType<OrderBonusListPageType> extends Promise<infer T>
  ? T
  : never)['result']['list'];
type ReqType = Parameters<OrderBonusListPageType>[0];
// 搜索表单的数据
let query: ReqType = {};

// 分成状态
const orderStatus = [
  { label: '未分成', value: 0 },
  { label: '已分成', value: 1 },
];

function DivideOrder() {
  // 分成设置弹窗
  const [divideSettingVisible, setDivideSettingVisible] = useState(false);
  // 分成确认弹窗
  const [divideConfirmVisible, setDivideConfirmVisible] = useState(false);
  // 编辑数据
  const [editData, setEditData] = useState<TableType[0]>();
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  // 新版通用部分(ES6+ for React) ZhangLK 2022/08/30 Start
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await PointManageAPI.OrderBonusListPage({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      // console.log("getTableList --->", list);
      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: ReqType) => {
    pagination.current = 1;
    query = data;
    getTableList(data).then();
  };
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  const handleClosed = () => {
    setDivideConfirmVisible(false);
    setDivideSettingVisible(false);
    paginationChange(pagination.current, pagination.pageSize);
  };
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      width: 80,
      render: (_text, _record, index) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      align: 'center',
    },
    {
      title: '订单名称',
      dataIndex: 'orderName',
      align: 'center',
    },
    {
      title: '订单金额（元）',
      dataIndex: 'realityAmount',
      align: 'center',
      render: (text) => text.toLocaleString(),
    },
    {
      title: '分成状态',
      dataIndex: 'divide',
      align: 'center',
      render: (text: string) => orderStatus.find((i) => i.value === Number(text))?.label || text,
    },
    {
      title: '买家账号',
      dataIndex: 'userName',
      align: 'center',
      render: (_text, record) => `${record.userName}(${record.uid})`,
    },
    {
      title: '认证企业',
      dataIndex: 'entName',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'id',
      align: 'center',
      fixed: 'right',
      width: 180,
      render: (_text, record) => (
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Button
            type='link'
            onClick={() => {
              setDivideSettingVisible(true);
              setEditData(record);
            }}
            disabled={record.divide === 1}
          >
            分成设置
          </Button>
          <Button
            type='link'
            onClick={() => {
              setDivideConfirmVisible(true);
              setEditData(record);
            }}
            disabled={record.divide === 1}
          >
            确认分成
          </Button>
        </div>
      ),
    },
  ];
  // componentDidMount
  useEffect(() => {
    query = {};
    (async () => {
      await getTableList();
    })();
  }, []);
  return (
    <>
      <SearchView
        search={[
          {
            label: '订单编号',
            name: 'orderNo',
            type: 'input',
            placeholder: '请输入订单编号',
          },
          {
            label: '分成状态',
            name: 'divide',
            type: 'Select',
            placeholder: '请选择分成状态',
            options: orderStatus,
            width: 160,
          },
          {
            label: '买家账号',
            name: 'keyword',
            type: 'input',
            placeholder: '请输入买家姓名、昵称、UID',
            width: 220,
          },
          {
            label: '买家认证企业',
            name: 'entName',
            type: 'input',
            placeholder: '请输入买家认证企业',
            width: 180,
          },
        ]}
        searchData={onFinish}
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='orderId'
        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} 条数据`,
        }}
      />
      <DivideSetting
        open={divideSettingVisible || divideConfirmVisible}
        title='分成设置'
        closed={handleClosed}
        data={editData}
        isEdit={divideConfirmVisible}
      />
    </>
  );
}

export default DivideOrder;
