import { Button, Table, Image, Tag, Modal, message } from 'antd';
import SearchBox from '~/components/search-box';
import AddTopicModal from './components/addTopicModal';
import { useEffect, useState } from 'react';
import { ForumManageAPI } from '~/api';
import { InterListType, InterReqListType, PaginationProps } from '~/api/interface';
import { listGambitType } from '~/api/interface/forumManageType';
import { ColumnsType } from 'antd/es/table/InternalTable';
import { gambitPropertyList } from '~/utils/dictionary';

// 话题列表返回类型
type topicListType = InterListType<listGambitType>;
// 话题列表参数类型
type topicParameters = InterReqListType<listGambitType>;
const TopicList = () => {
  const tableColumns: ColumnsType<topicListType[0]> = [
    {
      title: '名称',
      align: 'center',
      dataIndex: 'gambitName',
      width: '20%',
    },
    {
      title: '属性',
      align: 'center',
      dataIndex: 'gambitProperty',
      render: (text: number) => (
        <Tag>{gambitPropertyList.find((v) => v.value === text)?.label}</Tag>
      ),
    },
    {
      title: '图标',
      align: 'center',
      dataIndex: 'gambitIcon',
      render: (text: string) => <Image src={text} width={50} height={50} />,
    },
    {
      title: '封面',
      align: 'center',
      dataIndex: 'gambitCover',
      render: (text: string) => <Image src={text} width={50} height={50} />,
    },
    {
      title: '帖子数',
      dataIndex: 'postCount',
      align: 'center',
      render: (text: number) => text || 0,
    },
    {
      title: '操作',
      align: 'center',
      width: '20%',
      render: (_text: any, record) => (
        <>
          <Button type='link' onClick={() => addTopicModalShowClick(record)}>
            编辑
          </Button>
          <Button type='link' onClick={() => deleteTopic(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];

  const [addTopicModalShow, setAddTopicModalShow] = useState<boolean>(false);
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [query, setQuery] = useState<topicParameters>();
  const [tableData, setTableData] = useState<topicListType>([]);
  const [currentTopicItem, setCurrentTopicItem] = useState<topicListType[0]>();

  // 筛选
  const searchSuccess = (value: topicParameters) => {
    pagination.pageSize = 10;
    pagination.pageNo = 1;
    setQuery(value);
    getTopicList(value);
  };
  // 获取话题列表
  const getTopicList = (query?: topicParameters) => {
    ForumManageAPI.getTopicList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setTableData(result.list || []);
      pagination.totalCount = result.totalCount;
      setPagination({ ...pagination });
    });
  };
  // 分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getTopicList(query);
  };

  // 新建话题弹窗
  const addTopicModalShowClick = (record?: topicListType[0]) => {
    setCurrentTopicItem(record ? { ...record } : undefined);
    setAddTopicModalShow(true);
  };
  const addTopicModalCancel = () => {
    setAddTopicModalShow(false);
  };
  const addTopicModalShowOk = () => {
    getTopicList();
    setAddTopicModalShow(false);
  };
  // 删除话题
  const deleteTopic = (record: topicListType[0]) => {
    Modal.confirm({
      title: '删除话题',
      content: '确认删除该话题？',
      onOk: () => {
        ForumManageAPI.deleteGambit({ id: record.id }).then(({ code }) => {
          if (code === '200') {
            message.success('删除成功');
            getTopicList();
          }
        });
      },
    });
  };

  useEffect(() => {
    getTopicList();
  }, []);

  return (
    <div className='topic-list'>
      <SearchBox
        search={[
          {
            label: '名称',
            type: 'input',
            name: 'gambitName',
            placeholder: '请输入名称',
          },
          {
            label: '属性',
            type: 'Select',
            name: 'gambitProperty',
            options: gambitPropertyList,
            placeholder: '请选择属性',
          },
        ]}
        child={
          <Button type='primary' onClick={() => addTopicModalShowClick()}>
            新建
          </Button>
        }
        searchData={searchSuccess}
        sufFixBtn={
          <div style={{ color: 'red', textAlign: 'right' }}>
            <span>话题总个数：</span>
            <span>{pagination.totalCount}</span>
          </div>
        }
      />
      <Table
        size='small'
        bordered
        dataSource={tableData}
        rowKey='id'
        columns={tableColumns}
        pagination={{
          total: pagination.totalCount,
          pageSize: pagination.pageSize,
          current: pagination.pageNo,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
      <AddTopicModal
        open={addTopicModalShow}
        onCancel={addTopicModalCancel}
        onOk={addTopicModalShowOk}
        currentTopicItem={currentTopicItem}
      />
    </div>
  );
};
export default TopicList;
