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 { countGambitType, 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>;
//论坛统计数据返回类型
type getCountGambitType = InterDataType<countGambitType>;
const DynamicList = () => {
  const searchColumnsData: searchColumns[] = [
    {
      label: '作者',
      type: 'input',
      name: 'keyword',
      placeholder: '用户名称/用户UID/用户手机号码',
    },
    {
      label: '状态',
      type: 'Select',
      name: 'status',
      placeholder: '帖子状态',
      options: checkStatusList,
    },
  ];
  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',
      dataIndex: 'likesCount',
      render: (text) => text || 0,
    },
    {
      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 [countGambit, setCountGambit] = useState<getCountGambitType>();

  //动态列表
  const getDynamicList = (query?: forumParameters & { pageNo?: number; pageSize?: number }) => {
    ForumManageAPI.getForumList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setTableData(result.list || []);
      // pagination.totalCount = result.totalCount;
      setPagination({
        ...pagination,
        pageNo: result.pageNo,
        pageSize: result.pageSize,
        totalCount: result.totalCount,
      });
    });
  };
  //筛选
  const searchSuccess = (data: any) => {
    setPagination({
      ...pagination,
      pageNo: 1,
      pageSize: 10,
    });
    setQuery(data);
    getDynamicList(data);
  };
  //分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getDynamicList({ ...query, pageNo, pageSize });
  };
  // 获取动态不同状态个数
  const getCountGambit = () => {
    ForumManageAPI.getCountGambit().then(({ result }) => {
      if (result) {
        setCountGambit(result);
      }
    });
  };
  //强制删除论坛
  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);
            getCountGambit();
          }
        });
      },
    });
  };
  //强制隐藏
  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 replyReq = async (record: forumType[0], status: boolean) => {
    const res = await ForumManageAPI.checkDynamic({ dynamicId: record.id, status });
    if (res && res.code === '200') {
      message.success('操作成功');
      paginationChange(pagination.pageNo, pagination.pageSize);
      Modal.destroyAll();
      getCountGambit();
      (window as any).getMessageNumber();
    }
  };

  // 是否确认审核
  const handleCheckStatus = (record: forumType[0]) => {
    Modal.confirm({
      title: `确认审核`,
      content: `请确认是否审核通过？通过后动态将展示在论坛列表`,
      okText: '审核通过',
      cancelText: '审核不通过',
      closable: true,
      maskClosable: true,
      footer: (
        <div style={{ textAlign: 'right', marginTop: '10px' }}>
          <Button
            type='default'
            style={{ marginRight: '10px' }}
            onClick={() => replyReq(record, false)}
          >
            审核不通过
          </Button>
          <Button type='primary' onClick={() => replyReq(record, true)}>
            审核通过
          </Button>
        </div>
      ),
    });
  };
  // 组件挂载
  useEffect(() => {
    getDynamicList();
    getCountGambit();
  }, []);
  return (
    <div className='dynamic-list'>
      <SearchBox
        search={searchColumnsData}
        searchData={searchSuccess}
        sufFixBtn={
          <div className='data-statistics'>
            <div>
              <span>审核通过：</span>
              <span>{countGambit?.passDynamicAuditSum || 0}</span>
            </div>
            <div>
              <span>待审核：</span>
              <span>{countGambit?.unDynamicAuditSum || 0}</span>
            </div>
            <div>
              <span>审核不通过：</span>
              <span>{countGambit?.failDynamicAuditSum || 0}</span>
            </div>
          </div>
        }
      />
      <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;
