import React, { useState, useEffect } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { Button, Table, Modal, message, Input, Form, Tooltip, Tag, Space, Switch, TablePaginationConfig, Select } from 'antd';
import {
  DeleteOutlined,
  ExclamationCircleOutlined,
  SearchOutlined
} from '@ant-design/icons';
import styles from './userQuestionManage.less';
// 引入封装的组件
import QuestionModal from './QuestionModal';
// 引入API
import {
  getQuestionPage,
  getQuestionDetail,
  deleteQuestion,
  batchDeleteQuestion
} from '@/servers/api/userQuestion';
// 引入字典
import {
  QuestionCategoryOptions,
  AnswerStatus,
  AnswerStatusText,
  AnswerStatusColor
} from '@/dicts/userQuestionDict';

const { confirm } = Modal;
const { Option } = Select;

// 用户提问类型定义，扩展API.QuestionRecord类型，添加key属性
type QuestionItemType = API.QuestionRecord & {
  key: string;
};

// 搜索参数类型
interface SearchParams {
  title?: string;
  type?: string;
  isAnswer?: number;
  answerStatus?: string; // 添加回答状态筛选
}

const ReadQuestionManage: React.FC = () => {
  const intl = useIntl();
  const [loading, setLoading] = useState<boolean>(false);
  const [questionData, setQuestionData] = useState<QuestionItemType[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [currentQuestion, setCurrentQuestion] = useState<QuestionItemType | null>(null);
  const [modalMode, setModalMode] = useState<'view' | 'edit'>('view');
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<SearchParams>({
    isAnswer: 1 // 默认已回答
  });

  // 获取已回答的用户提问列表数据
  const fetchQuestionList = async (
    current: number = 1,
    pageSize: number = 10,
    params: SearchParams = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    try {
      // 构造请求参数
      const requestParams: API.PageRequest = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
        ...params,
        isAnswer: 1, // 确保始终查询已回答的问题
      };

      const response = await getQuestionPage(requestParams);
      if (response && response.success) {
        const { records, total, current: currentPage, size } = response.data;

        // 添加key属性用于表格
        const formattedData = records.map((item: API.QuestionRecord) => ({
          ...item,
          key: item.id,
        }));

        setQuestionData(formattedData);
        setPagination({
          ...pagination,
          current: currentPage,
          pageSize: size,
          total,
        });
      } else {
        message.error(response.message || intl.formatMessage({ id: 'readQuestion.fetchFailed' }));
      }
    } catch (error) {
      console.error('获取问题列表失败:', error);
      message.error(intl.formatMessage({ id: 'readQuestion.fetchFailed' }));
    } finally {
      setLoading(false);
    }
  };

  // 首次加载时获取数据
  useEffect(() => {
    fetchQuestionList(pagination.current, pagination.pageSize);
  }, []);

  // 处理搜索
  const handleSearch = (values: SearchParams) => {
    const params = {
      ...values,
      isAnswer: 1,
      // 如果设置了answerStatus为已回答，则需要特殊处理
      ...values.answerStatus === AnswerStatus.ANSWERED ? { hasAnswerContent: 1 } : {}
    };
    fetchQuestionList(1, pagination.pageSize, params);
  };

  // 获取问题详情
  const fetchQuestionDetail = async (id: string, mode: 'view' | 'edit') => {
    try {
      const response = await getQuestionDetail(id);
      if (response && response.success) {
        const detailData = response.data;
        const formattedDetail = {
          ...detailData,
          key: detailData.id
        };

        setCurrentQuestion(formattedDetail);
        setModalMode(mode);
        setModalVisible(true);
      } else {
        message.error(response.message || intl.formatMessage({ id: 'readQuestion.fetchFailed' }));
      }
    } catch (error) {
      console.error('获取问题详情失败:', error);
      message.error(intl.formatMessage({ id: 'readQuestion.fetchFailed' }));
    }
  };

  // 处理查看详情
  const handleView = (record: QuestionItemType) => {
    fetchQuestionDetail(record.id, 'view');
  };

  // 处理编辑回答
  const handleEdit = (record: QuestionItemType) => {
    fetchQuestionDetail(record.id, 'edit');
  };

  // 处理删除
  const showDeleteConfirm = (record: QuestionItemType) => {
    confirm({
      title: intl.formatMessage({ id: 'readQuestion.confirmDelete' }),
      icon: <ExclamationCircleOutlined />,
      content: `${intl.formatMessage({ id: 'readQuestion.confirmDelete' })} "${record.title}"?`,
      okText: intl.formatMessage({ id: 'readQuestion.delete' }),
      okType: 'danger',
      cancelText: intl.formatMessage({ id: 'readQuestion.cancel' }),
      maskClosable: false,
      onOk: async () => {
        try {
          const response = await deleteQuestion(record.id);
          if (response && response.success) {
            message.success(intl.formatMessage({ id: 'readQuestion.deleteSuccess' }));
            fetchQuestionList(pagination.current, pagination.pageSize, searchParams); // 重新加载数据
          } else {
            message.error(response.message || intl.formatMessage({ id: 'readQuestion.deleteFailed' }));
          }
        } catch (error) {
          console.error('删除问题失败:', error);
          message.error(intl.formatMessage({ id: 'readQuestion.deleteFailed' }));
        }
      },
    });
  };

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

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning(intl.formatMessage({ id: 'readQuestion.selectRequired' }));
      return;
    }

    confirm({
      title: intl.formatMessage({ id: 'readQuestion.batchDelete' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'readQuestion.batchDeleteConfirm' }),
      okText: intl.formatMessage({ id: 'readQuestion.delete' }),
      okType: 'danger',
      cancelText: intl.formatMessage({ id: 'readQuestion.cancel' }),
      maskClosable: false,
      onOk: async () => {
        try {
          const response = await batchDeleteQuestion(selectedRowKeys as string[]);
          if (response && response.success) {
            setSelectedRowKeys([]);
            message.success(intl.formatMessage({ id: 'readQuestion.batchDeleteSuccess' }));
            fetchQuestionList(pagination.current, pagination.pageSize, searchParams);
          } else {
            message.error(response.message || intl.formatMessage({ id: 'readQuestion.batchDeleteFailed' }));
          }
        } catch (error) {
          console.error('批量删除失败:', error);
          message.error(intl.formatMessage({ id: 'readQuestion.batchDeleteFailed' }));
        }
      },
    });
  };

  // 行选择限制
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const hasSelected = selectedRowKeys.length > 0;

  // 获取回答状态标签
  const getAnswerTag = (record: QuestionItemType) => {
    if (record.answerContent && record.answerContent.trim() !== '') {
      return <Tag color={AnswerStatusColor[AnswerStatus.ANSWERED]}>{AnswerStatusText[AnswerStatus.ANSWERED]()}</Tag>;
    } else {
      return <Tag color={AnswerStatusColor[AnswerStatus.READ]}>{AnswerStatusText[AnswerStatus.READ]()}</Tag>;
    }
  };

  // 获取置顶状态标签
  const getTopTag = (isTop: number) => {
    return isTop === 1 ?
      <Tag color="red">{intl.formatMessage({ id: 'userQuestion.top' })}</Tag> :
      null;
  };

  // 表格列定义
  const columns = [
    {
      title: intl.formatMessage({ id: 'readQuestion.serialNumber' }),
      render: (_: any, __: any, index: number) => index + 1,
      width: 80,
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.questionTitle' }),
      dataIndex: 'title',
      key: 'title',
      ellipsis: {
        showTitle: false,
      },
      render: (title: string, record: QuestionItemType) => (
        <Tooltip placement="topLeft" title={title}>
          <span>
            {record.isTop === 1 && getTopTag(record.isTop)}
            {title}
          </span>
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.category' }),
      dataIndex: 'type',
      key: 'type',
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.asker' }),
      dataIndex: 'userName',
      key: 'userName',
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.company' }),
      dataIndex: 'companyName',
      key: 'companyName',
      ellipsis: {
        showTitle: false,
      },
      render: (companyName: string) => (
        <Tooltip placement="topLeft" title={companyName}>
          {companyName}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.account' }),
      dataIndex: 'fullName',
      key: 'fullName',
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.contact' }),
      dataIndex: 'contactDetails',
      key: 'contactDetails',
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.email' }),
      dataIndex: 'email',
      key: 'email',
      ellipsis: {
        showTitle: false,
      },
      render: (email: string) => (
        <Tooltip placement="topLeft" title={email}>
          {email}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.askTime' }),
      dataIndex: 'askTime',
      key: 'askTime',
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.answerTime' }),
      dataIndex: 'answerTime',
      key: 'answerTime',
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.respondent' }),
      dataIndex: 'answerBy',
      key: 'answerBy',
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.status' }),
      key: 'status',
      align: 'center' as const,
      render: (_: unknown, record: QuestionItemType) => (
        <Space>
          {getAnswerTag(record)}
          {record.isPublished === 1 && <Tag color="green">{intl.formatMessage({ id: 'userQuestion.published' })}</Tag>}
        </Space>
      ),
    },
    {
      title: intl.formatMessage({ id: 'readQuestion.operation' }),
      key: 'action',
      width: 260,
      align: 'center' as const,
      render: (_: unknown, record: QuestionItemType) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {intl.formatMessage({ id: 'userQuestion.view' })}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {intl.formatMessage({ id: 'readQuestion.edit' })}
          </Button>
          <Button type="link" onClick={() => showDeleteConfirm(record)}>
            {intl.formatMessage({ id: 'readQuestion.delete' })}
          </Button>
        </Space>
      ),
    },
  ];

  // 获取分类选项，处理为下拉框选项
  const getCategoryOptions = () => {
    return QuestionCategoryOptions.map(option => (
      <Option key={option.value} value={option.value}>
        {typeof option.label === 'function' ? option.label() : option.label}
      </Option>
    ));
  };

  return (
    <div className="common-container">
      <div className="filter-action-row">
        <Form
          form={form}
          name="search"
          onFinish={handleSearch}
          layout="inline"
          className="filter-form"
        >
          <Form.Item name="title" label={intl.formatMessage({ id: 'readQuestion.questionTitle' })}>
            <Input placeholder={intl.formatMessage({ id: 'readQuestion.questionPlaceholder' })} allowClear />
          </Form.Item>
          <Form.Item name="type" label={intl.formatMessage({ id: 'readQuestion.category' })}>
            <Select placeholder={intl.formatMessage({ id: 'readQuestion.selectCategory' })} allowClear style={{ width: 150 }}>
              {getCategoryOptions()}
            </Select>
          </Form.Item>
          <Form.Item name="answerStatus" label={intl.formatMessage({ id: 'readQuestion.answerStatus' })}>
            <Select placeholder={intl.formatMessage({ id: 'readQuestion.selectAnswerStatus' })} allowClear style={{ width: 120 }}>
              <Option value={AnswerStatus.READ}>{AnswerStatusText[AnswerStatus.READ]()}</Option>
              <Option value={AnswerStatus.ANSWERED}>{AnswerStatusText[AnswerStatus.ANSWERED]()}</Option>
            </Select>
          </Form.Item>
          <Form.Item className="filter-btns">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              {intl.formatMessage({ id: 'readQuestion.search' })}
            </Button>
            <Button
              type="primary"
              danger
              onClick={() => {
                form.resetFields();
                setSearchParams({ isAnswer: 1 });
                fetchQuestionList(1, pagination.pageSize, { isAnswer: 1 });
              }}
            >
              {intl.formatMessage({ id: 'readQuestion.reset' })}
            </Button>
          </Form.Item>
        </Form>

        <div className="right-buttons">
          <Button
            danger
            onClick={handleBatchDelete}
            disabled={!hasSelected}
            loading={loading}
          >
            {intl.formatMessage({ id: 'readQuestion.batchDelete' })}
          </Button>
          {hasSelected && (
            <span className="selected-count">
              {intl.formatMessage({ id: 'readQuestion.selectedCount' }, { count: selectedRowKeys.length })}
            </span>
          )}
        </div>
      </div>

      <div className="content-area">
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={questionData}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          rowKey="id"
        />
      </div>

      {/* 使用封装的问题模态框组件 */}
      <QuestionModal
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        question={currentQuestion}
        mode={modalMode}
        onSuccess={() => fetchQuestionList(pagination.current, pagination.pageSize, searchParams)}
      />
    </div>
  );
};

export default ReadQuestionManage;
