import React, { useEffect, useState } from 'react';
import SearchView from '~/components/search-box';
import { ActivityManageAPI } from '~/api';
import { InterListType, InterReqListType } from '~/api/interface';
import { listActivityPagesType } from '~/api/interface/activityManage';
import { Button, message, Modal, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { PlusOutlined } from '@ant-design/icons';
import AddOrEditModal from '~/pages/activityManage/activityList/comp/addOrEditModal';

// 列表的类型
type TableType = InterListType<listActivityPagesType>;
// 搜索表单的类型
type ReqType = InterReqListType<listActivityPagesType>;
// 搜索表单的数据
let query: ReqType = {};
// 活动类型列表
const activityTypeList = [{ label: '新用户邀请', value: 0 }];
// 活动状态列表
const activityStatusList = [
  { label: '进行中', value: 1 },
  { label: '已结束', value: 0 },
];
// 奖励类型列表
const rewardTypeList = [
  { label: '积分', value: 0 },
  { label: '余额', value: 1 },
  // { label: '优惠券', value: 2 },
];

const ActivityListView = () => {
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 编辑弹窗是否开启
  const [addEditShow, setAddEditShow] = useState(false);
  // 需要编辑的数据
  const [recordData, setRecordData] = useState<TableType[0]>();
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  // 新版通用部分(ES6+ for React) ZhangLK 2022/08/30 Start
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await ActivityManageAPI.listActivityPages({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list || []);
      console.log('加载列表 --->', 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 handleDelete = (record: TableType[0]) => {
    Modal.confirm({
      title: '提示',
      content: '请确认是否删除？',
      onOk: async () => {
        const res = await ActivityManageAPI.activityDelete({ id: record?.id });
        if (res && res.code === '200') {
          paginationChange(
            tableData.length === 1 && pagination.current !== 1
              ? pagination.current - 1
              : pagination.current,
            pagination.pageSize,
          );
          message.success('删除成功');
        }
      },
    });
  };
  // 页面挂载
  useEffect(() => {
    query = {};
    (async () => {
      await getTableList();
    })();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '活动名称',
      dataIndex: 'activityName',
      align: 'center',
    },
    {
      title: '活动类型',
      dataIndex: 'activityType',
      align: 'center',
      render: (text) => activityTypeList.find((i) => i.value === text)?.label || text,
    },
    {
      title: '活动状态',
      dataIndex: 'activityStatus',
      align: 'center',
      render: (text) => activityStatusList.find((i) => i.value === text)?.label || text,
    },
    {
      title: '活动说明',
      dataIndex: 'description',
      align: 'center',
      width: '100px',
      ellipsis: true,
    },
    {
      title: '奖励类型',
      dataIndex: 'rewardType',
      align: 'center',
      render: (text) => rewardTypeList.find((i) => i.value === text)?.label || text,
    },
    {
      title: '奖励额度',
      dataIndex: 'rewardValue',
      align: 'center',
    },
    {
      title: '人数限制',
      dataIndex: 'requireNum',
      align: 'center',
      render: (text) => (text === 0 ? `无限制` : text),
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      align: 'center',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      fixed: 'right',
      render: (_text, record) => (
        <>
          <Button
            type={'link'}
            onClick={() => {
              setAddEditShow(true);
              setRecordData(record);
            }}
          >
            编辑
          </Button>
          <Button type={'link'} danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchView
        search={[
          {
            label: '活动名称',
            name: 'activityName',
            type: 'Input',
            placeholder: '请输入活动名称',
          },
          {
            label: '活动状态',
            name: 'activityStatus',
            type: 'Select',
            placeholder: '请选择活动状态',
            options: activityStatusList,
          },
          {
            label: '活动类型',
            name: 'activityType',
            type: 'Select',
            placeholder: '请选择活动类型',
            options: activityTypeList,
          },
        ]}
        searchData={onFinish}
        child={
          <>
            <Button
              type={'primary'}
              icon={<PlusOutlined />}
              onClick={() => {
                setAddEditShow(true);
                setRecordData(undefined);
              }}
            >
              新增活动
            </Button>
          </>
        }
      />
      <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} 条数据`,
        }}
      />
      <AddOrEditModal
        open={addEditShow}
        title={recordData ? '编辑' : '新增'}
        onCancel={() => {
          setAddEditShow(false);
          setRecordData(undefined);
          paginationChange(pagination.current, pagination.pageSize);
        }}
        data={recordData}
      />
    </>
  );
};

export default ActivityListView;
