import React, { useState, useEffect } from 'react';
import { Table, Typography, Button } from 'antd';
import { history, useIntl } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import { getHelpCenterList } from '@/servers/api/help';
import { QUESTION_TYPES } from '@/dicts/help';
import './help.less';

const { Title } = Typography;

const HelpPage: React.FC = () => {
  const intl = useIntl();
  const [helpData, setHelpData] = useState<API.HelpCenterRecord[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取帮助中心数据
  const fetchHelpData = async (current = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const response = await getHelpCenterList({
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
      });

      if (response.success) {
        setHelpData(response.data.records || []);
        setPagination({
          current: response.data.current,
          pageSize: response.data.size,
          total: response.data.total,
        });
      }
    } catch (error) {
      console.error('获取帮助中心列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载数据
  useEffect(() => {
    fetchHelpData();
  }, []);

  // 处理表格分页变化
  const handleTableChange = (newPagination: any) => {
    fetchHelpData(newPagination.current, newPagination.pageSize);
  };

  // 处理点击问题标题
  const handleHelpClick = (id: string) => {
    history.push(`/help/helpInfo?id=${id}`);
  };

  // 处理点击提问按钮
  const handleAskQuestion = () => {
    history.push('/help/helpQuestion');
  };

  // 获取问题分类名称
  const getQuestionTypeName = (type: string) => {
    const found = QUESTION_TYPES.find(item => item.value === type);
    return found ? found.label : type;
  };

  // 定义表格列
  const columns = [
    {
      title: intl.formatMessage({ id: 'help.column.index' }),
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_: any, __: any, index: number) => {
        return (pagination.current - 1) * pagination.pageSize + index + 1;
      },
    },
    {
      title: intl.formatMessage({ id: 'help.column.title' }),
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record: any) => (
        <a onClick={() => handleHelpClick(record.id)} className="help-title">
          {text}
        </a>
      ),
    },
    {
      title: intl.formatMessage({ id: 'help.column.type' }),
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type: string) => getQuestionTypeName(type),
    },
    {
      title: intl.formatMessage({ id: 'help.column.time' }),
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      align: 'center' as 'center',
    },
  ];

  return (
    <div className="help-container">
      <div className="help-header">
        <Title level={2}>{intl.formatMessage({ id: 'help.title' })}</Title>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAskQuestion}
          className="ask-button"
        >
          {intl.formatMessage({ id: 'help.ask' })}
        </Button>
      </div>
      <div className="help-table">
        <Table
          columns={columns}
          dataSource={helpData}
          rowKey="id"
          pagination={{
            ...pagination,
            showTotal: (total) => `${intl.formatMessage({ id: 'help.total' }, { total })}`,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
          loading={loading}
          onChange={handleTableChange}
          bordered
        />
      </div>
    </div>
  );
};

export default HelpPage;
