import React, { useEffect, useState } from 'react';
import { Button, message, Modal, Table } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import SearchView from '~/components/search-box';
import { BonusRuleListQueryType } from '~/api/interface/pointManageType';
import { PointManageAPI } from '~/api';
import '../divideOrder/index.scss';
import { DivideAddEditModal } from '~/pages/pointManage/divideRules/comp/divideAddEditModal';

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

function DivideRules() {
  // 查看规则弹窗
  const [divideViewVisible, setDivideViewVisible] = useState(false);
  // 查看规则弹窗
  const [divideEditVisible, setDivideEditVisible] = 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.BonusRuleListQuery({
      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 = () => {
    paginationChange(pagination.current, pagination.pageSize);
    setDivideEditVisible(false);
    setDivideViewVisible(false);
    setEditData(undefined);
  };
  // 删除数据
  const handleDelete = (record: TableType[0]) => {
    Modal.confirm({
      title: '提示',
      content: '删除后此数据将会丢失，确定删除吗？',
      onOk: async () => {
        const res = await PointManageAPI.RemoveBonusRule({ id: record.id });
        if (res && res.code === '200') {
          message.success('操作成功').then();
          paginationChange(
            tableData.length === 1 ? pagination.current - 1 : 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: 'ruleName',
      align: 'center',
      width: 300,
    },
    {
      title: '分成对象',
      dataIndex: 'proportionObject',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '是否为默认规则',
      dataIndex: 'defaultRule',
      align: 'center',
      width: 200,
      render: (text) => (text === 1 ? '否' : '是'),
    },
    {
      title: '操作',
      dataIndex: 'id',
      align: 'center',
      fixed: 'right',
      width: 180,
      render: (_text, record) => (
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Button
            type='link'
            onClick={() => {
              setEditData(record);
              setDivideViewVisible(true);
            }}
          >
            查看
          </Button>
          <Button
            type='link'
            onClick={() => {
              setEditData(record);
              setDivideEditVisible(true);
            }}
          >
            编辑
          </Button>
          <Button type='link' onClick={() => handleDelete(record)}>
            删除
          </Button>
        </div>
      ),
    },
  ];
  // componentDidMount
  useEffect(() => {
    query = {};
    (async () => {
      await getTableList();
    })();
  }, []);
  return (
    <>
      <SearchView
        search={[
          {
            label: '规则名称',
            name: 'ruleName',
            type: 'input',
            placeholder: '请输入规则名称',
            width: 180,
          },
        ]}
        sufFixBtn={
          <Button icon={<PlusOutlined />} type='primary' onClick={() => setDivideEditVisible(true)}>
            新建规则
          </Button>
        }
        searchData={onFinish}
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1000 }}
        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} 条数据`,
        }}
      />
      <DivideAddEditModal
        title={divideViewVisible ? '查看规则' : editData ? '编辑规则' : '新建规则'}
        open={divideViewVisible || divideEditVisible}
        closed={handleClosed}
        data={editData}
        isEdit={divideViewVisible}
      />
    </>
  );
}

export default DivideRules;
