import SearchBox, { searchColumns } from '~/components/search-box';
import { Button, message, Modal, Table, Tooltip } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { useEffect, useState } from 'react';
import DynamicDetailModal from './components/dynamicDetailModal';
import { ForumManageAPI } from '~/api';
import { InterDataType, InterListType, InterReqListType, PaginationProps } from '~/api/interface';
import { forumDetailType, forumListType } from '~/api/interface/forumManageType';
import './index.scss';

// 动态审核状态
const checkStatusList = [
  { label: '审核中', value: 0 },
  { label: '审核通过', value: 1 },
  { label: '审核不通过', value: 2 },
];

//论坛列表返回类型
type forumType = InterListType<forumListType>;
//论坛列表参数类型
type forumParameters = InterReqListType<forumListType>;
//论坛详情返回类型
type detailType = InterDataType<forumDetailType>;
const DynamicList = () => {
  const searchColumnsData: searchColumns[] = [
    {
      label: '作者',
      type: 'input',
      name: 'keyword',
      placeholder: '用户名称/用户UID/用户手机号码',
    },
  ];
  const tableColumns: ColumnsType<forumType[0]> = [
    {
      title: '动态描述信息',
      align: 'center',
      dataIndex: 'description',
      width: '20%',
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className='forum-description'>{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '话题',
      align: 'center',
      dataIndex: 'gambitName',
      ellipsis: true,
      render: (text: string[]) => (
        <Tooltip title={text.join('，')}>
          <div className='forum-topic'>{text.join('，')}</div>
        </Tooltip>
      ),
    },
    {
      title: '作者（用户名称）',
      align: 'center',
      render: (_text: string, record) => (
        <div>{record.userBaseInfo?.userName || record.userBaseInfo?.nickName || ''}</div>
      ),
    },
    {
      title: '审核状态',
      align: 'center',
      dataIndex: 'checkStatus',
      render: (text: number) => checkStatusList.find((i) => i.value === text)?.label || text,
    },
    {
      title: '用户UID',
      align: 'center',
      render: (_text: string, record) => <div>{record.userBaseInfo?.uid || ''}</div>,
    },
    {
      title: '用户手机号',
      align: 'center',
      render: (_text: string, record) => <div>{record.userBaseInfo?.phone || ''}</div>,
    },
    {
      title: '发布时间',
      align: 'center',
      dataIndex: 'dynamicPublishTime',
    },
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      width: 180,
      render: (_text: string, record) => (
        <>
          <Button
            type='link'
            onClick={() => handleCheckStatus(record)}
            disabled={record.checkStatus !== 0}
          >
            审核
          </Button>
          <Button type='link' onClick={() => lookDynamicDetail(record)}>
            详情
          </Button>
          <Button
            type='link'
            onClick={() => deleteForumClick(record)}
            danger
            disabled={record.checkStatus === 0}
          >
            删除
          </Button>
          <Button
            type='link'
            onClick={() => hiddenForumClick(record)}
            disabled={record.checkStatus === 0}
          >
            {record.show ? '显示' : '隐藏'}
          </Button>
        </>
      ),
    },
  ];
  const [tableData, setTableData] = useState<forumType>([]);
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [forumDetail, setForumDetail] = useState<detailType>();
  const [query, setQuery] = useState<forumParameters>();
  const [dynamicDetailModalShow, setDynamicDetailModalShow] = useState<boolean>(false);

  //动态列表
  const getDynamicList = (query?: forumParameters) => {
    ForumManageAPI.getForumList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setTableData(result.list || []);
      pagination.totalCount = result.totalCount;
      setPagination(pagination);
    });
  };
  //筛选
  const searchSuccess = (data: any) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    setQuery(data);
    getDynamicList(data);
  };
  //分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getDynamicList(query);
  };
  //强制删除论坛
  const deleteForumClick = (record: forumType[0]) => {
    Modal.confirm({
      title: '强制删除',
      content: '确认删除这条动态？',
      onOk: () => {
        ForumManageAPI.deleteForum({ dynamicId: record.id }).then(({ code }) => {
          if (code === '200') {
            message.success('删除成功');
            if (pagination.pageNo !== 1 && tableData.length === 1) {
              pagination.pageNo -= 1;
            }
            getDynamicList(query);
          }
        });
      },
    });
  };
  //强制隐藏
  const hiddenForumClick = (record: forumType[0]) => {
    Modal.confirm({
      title: `${record.show ? '恢复显示' : '强制隐藏'}`,
      content: `确认${record.show ? '显示' : '隐藏'}这条动态？`,
      onOk: () => {
        ForumManageAPI.hiddenForum({ dynamicId: record.id }).then(({ code }) => {
          if (code === '200') {
            message.success(`${record.show ? '显示' : '隐藏'}成功`);
            getDynamicList(query);
          }
        });
      },
    });
  };
  const dynamicDetailModalOnCancel = () => {
    setDynamicDetailModalShow(false);
  };
  //查看详情
  const lookDynamicDetail = (record: forumType[0]) => {
    getForumDetail(record.id);
  };
  //获取论坛-详情
  const getForumDetail = (id: number) => {
    ForumManageAPI.getForumDetail({ dynamicId: id }).then(({ code, result }) => {
      if (code === '200') {
        setDynamicDetailModalShow(true);
        setForumDetail(result);
      }
    });
  };
  // 是否确认审核
  const handleCheckStatus = (record: forumType[0]) => {
    Modal.confirm({
      title: `确认审核`,
      content: `请确认是否审核通过？通过后动态将展示在论坛列表`,
      okText: '审核通过',
      cancelText: '审核不通过',
      onOk: async () => {
        const res = await ForumManageAPI.checkDynamic({ dynamicId: record.id, status: true });
        if (res && res.code === '200') {
          message.success('操作成功');
          paginationChange(pagination.pageNo, pagination.pageSize);
        }
      },
      onCancel: async () => {
        const res = await ForumManageAPI.checkDynamic({ dynamicId: record.id, status: false });
        if (res && res.code === '200') {
          message.success('操作成功');
          paginationChange(pagination.pageNo, pagination.pageSize);
        }
      },
    });
  };
  // 组件挂载
  useEffect(() => {
    getDynamicList();
  }, []);
  return (
    <div className='dynamic-list'>
      <SearchBox search={searchColumnsData} searchData={searchSuccess} />
      <Table
        size={'small'}
        bordered
        columns={tableColumns}
        dataSource={tableData}
        rowKey='id'
        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} 条数据`,
        }}
      />
      <DynamicDetailModal
        open={dynamicDetailModalShow}
        onCancel={dynamicDetailModalOnCancel}
        forumDetail={forumDetail}
      />
    </div>
  );
};
export default DynamicList;
