import { useEffect, useState } from 'react';
import { Button, message, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { PlusOutlined } from '@ant-design/icons';
import SearchView from '~/components/search-box/index';
import { PointManageAPI } from '~/api';
import { ListConvertRuleType } from '~/api/interface/pointManageType';
import { AddEditModal } from './comp/addEditModal/index';
import useOperate from '~/common/hook/optionHook';

// 列表的类型
type TableType = (ReturnType<ListConvertRuleType> extends Promise<infer T>
  ? T
  : never)['result']['list'];
type ReqType = Parameters<ListConvertRuleType>[0];
// 搜索表单的数据
let query: ReqType = {};
// 规则状态
const ruleOptions = [
  // { id: undefined, name: "全部状态" },
  { id: 0, name: '生效中' },
  { id: 1, name: '已失效' },
  { id: 2, name: '未生效' },
];

export const PointRules = () => {
  // 新增弹窗是否显示
  const [addEditVisible, setAddEditVisible] = useState(false);
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 按钮权限
  // const isPointRuleBtn = useOperate(25201);
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  // 新版通用部分(ES6+ for React) ZhangLK 2022/08/30 Start
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await PointManageAPI.ListConvertRule({
      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 columns: ColumnsType<TableType[0]> = [
    {
      title: '规则名称',
      dataIndex: 'ruleName',
      align: 'center',
    },
    {
      title: '兑换比例（积分：券额）',
      dataIndex: 'convertRatio',
      align: 'center',
    },
    {
      title: '生效时间',
      dataIndex: 'entryIntoForceTime',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      render: (text: string) => ruleOptions.find((i) => i.id === Number(text))?.name || text,
    },
  ];
  useEffect(() => {
    query = {};
    (async () => {
      await getTableList();
    })();
  }, []);
  return (
    <>
      <SearchView
        search={[
          {
            label: '规则状态',
            name: 'status',
            type: 'select',
            placeholder: '请选择规则状态',
            options: ruleOptions,
          },
        ]}
        searchData={onFinish}
        child={
          <Button
            icon={<PlusOutlined />}
            type='primary'
            onClick={() => {
              setAddEditVisible(true);
            }}
            // disabled={!isPointRuleBtn}
          >
            新增规则
          </Button>
        }
      />
      <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} 条数据`,
        }}
      />
      <AddEditModal
        open={addEditVisible}
        title='新增兑换规则'
        closed={() => {
          setAddEditVisible(false);
          setTimeout(() => {
            paginationChange(pagination.current, pagination.pageSize);
          }, 500);
        }}
      />
    </>
  );
};
