import React, { useState, useEffect } from 'react';
import { useIntl } from 'umi';
import { Button, Table, Modal, message, Input, Select, Form, Tooltip, Tag } from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import styles from './helpManage.less';
// 引入API
import {
  getHelpList,
  deleteHelp,
  batchDeleteHelp,
  updateHelpStatus,
  getHelpDetail,
} from '@/servers/api/help';
// 引入字典和组件
import {
  HelpStatus,
  HelpStatusText,
  HelpStatusColor,
  TopStatus,
  categoryOptions,
} from '@/dicts/helpManageDict';
import HelpManageForm from './HelpManageForm';
import HelpManageInfo from './HelpManageInfo';

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

// 帮助中心条目类型定义
interface HelpItemType extends API.HelpRecord {
  key: string;
}

interface SearchParams {
  title?: string;
  type?: string;
  status?: string;
}

const HelpManage: React.FC = () => {
  const intl = useIntl();
  const [loading, setLoading] = useState<boolean>(false);
  const [helpData, setHelpData] = useState<HelpItemType[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [isViewMode, setIsViewMode] = useState<boolean>(false);
  const [currentId, setCurrentId] = useState<string>('');
  const [viewData, setViewData] = useState<API.HelpRecord | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<SearchParams>({});

  // 获取帮助中心列表数据
  const fetchHelpList = (
    current: number = 1,
    pageSize: number = 10,
    params: SearchParams = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    // 调用API
    getHelpList({
      ...params,
      pageNo: current,
      pageSize,
    })
      .then((res) => {
        if (res && res.success && res.data && res.data.records) {
          const records = res.data.records.map((item: API.HelpRecord) => ({
            ...item,
            key: item.id,
          }));
          setHelpData(records);
          setPagination({
            ...pagination,
            current,
            pageSize,
            total: res.data.total || records.length,
          });
        } else {
          message.error(intl.formatMessage({ id: 'helpManage.fetchFailed' }));
        }
      })
      .catch((error) => {
        console.error('获取帮助中心列表失败:', error);
        message.error(intl.formatMessage({ id: 'helpManage.fetchFailed' }));
      })
      .finally(() => {
        setLoading(false);
      });
  };

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

  // 处理搜索
  const handleSearch = (values: SearchParams) => {
    fetchHelpList(1, pagination.pageSize, values);
  };

  // 处理添加
  const handleAdd = () => {
    setIsEdit(false);
    setIsViewMode(false);
    setCurrentId('');
    setViewData(null);
    setModalVisible(true);
  };

  // 处理查看
  const handleView = async (record: HelpItemType) => {
    setCurrentId(record.id);
    setIsViewMode(true);

    try {
      const response = await getHelpDetail(record.id);
      if (response && response.success) {
        // 设置查看详情数据
        setViewData(response.data);
        setModalVisible(true);
      } else {
        message.error(
          response.message || intl.formatMessage({ id: 'helpManage.fetchDetailFailed' }),
        );
      }
    } catch (error) {
      console.error('获取帮助详情失败:', error);
      message.error(intl.formatMessage({ id: 'helpManage.fetchDetailFailed' }));
    }
  };

  // 处理编辑
  const handleEdit = (record: HelpItemType) => {
    // 检查是否为已发布状态
    if (record.status === HelpStatus.PUBLISHED) {
      message.warning(intl.formatMessage({ id: 'helpManage.publishedNoEdit' }));
      return;
    }

    setIsEdit(true);
    setIsViewMode(false);
    setCurrentId(record.id);
    setModalVisible(true);
  };

  // 处理删除
  const showDeleteConfirm = (record: HelpItemType) => {
    // 检查是否为已发布状态
    if (record.status === HelpStatus.PUBLISHED) {
      message.warning(intl.formatMessage({ id: 'helpManage.publishedNoDelete' }));
      return;
    }

    confirm({
      title: intl.formatMessage({ id: 'helpManage.confirmDelete' }),
      icon: <ExclamationCircleOutlined />,
      content: `${intl.formatMessage({ id: 'helpManage.deleteConfirmTitle' })}: ${record.title}`,
      okText: intl.formatMessage({ id: 'helpManage.delete' }),
      okType: 'danger',
      cancelText: intl.formatMessage({ id: 'helpManage.cancel' }),
      maskClosable: false,
      onOk: async () => {
        try {
          // 调用删除API
          const response = await deleteHelp(record.id);
          if (response && response.success) {
            message.success(intl.formatMessage({ id: 'helpManage.deleteSuccess' }));
            fetchHelpList(pagination.current, pagination.pageSize, searchParams);
          } else {
            message.error(
              response.message || intl.formatMessage({ id: 'helpManage.deleteFailed' }),
            );
          }
        } catch (error) {
          console.error('删除帮助失败:', error);
          message.error(intl.formatMessage({ id: 'helpManage.deleteFailed' }));
        }
      },
    });
  };

  // 处理发布/下架
  const handlePublishStatus = async (record: HelpItemType) => {
    const isPublished = record.status === HelpStatus.PUBLISHED;
    const actionText = isPublished
      ? intl.formatMessage({ id: 'helpManage.unpublish' })
      : intl.formatMessage({ id: 'helpManage.publish' });
    const newStatus = isPublished ? HelpStatus.UNPUBLISHED : HelpStatus.PUBLISHED;
    const confirmMsgId = isPublished ? 'helpManage.confirmUnpublish' : 'helpManage.confirmPublish';
    const successMsgId = isPublished ? 'helpManage.unpublishSuccess' : 'helpManage.publishSuccess';
    const failedMsgId = isPublished ? 'helpManage.unpublishFailed' : 'helpManage.publishFailed';

    confirm({
      title: intl.formatMessage({ id: confirmMsgId }),
      icon: <ExclamationCircleOutlined />,
      content: `${intl.formatMessage({ id: 'helpManage.deleteConfirmTitle' })}: ${record.title}`,
      okText: intl.formatMessage({ id: 'helpManage.submit' }),
      cancelText: intl.formatMessage({ id: 'helpManage.cancel' }),
      maskClosable: false,
      onOk: async () => {
        try {
          // 调用API更新状态
          const response = await updateHelpStatus(record.id, newStatus);
          if (response && response.success) {
            message.success(intl.formatMessage({ id: successMsgId }));
            fetchHelpList(pagination.current, pagination.pageSize, searchParams);
          } else {
            message.error(response.message || intl.formatMessage({ id: failedMsgId }));
          }
        } catch (error) {
          console.error(`${actionText}失败:`, error);
          message.error(intl.formatMessage({ id: failedMsgId }));
        }
      },
    });
  };
  // 获取状态标签
  const getStatusTag = (status: string) => {
    const statusKey = status as keyof typeof HelpStatusText;
    const color = HelpStatusColor[statusKey] || 'default';
    const getText = HelpStatusText[statusKey];
    const text =
      typeof getText === 'function'
        ? getText()
        : intl.formatMessage({ id: 'helpManage.status.unknown' });
    return <Tag color={color}>{text}</Tag>;
  };

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

  // 处理批量删除
  const handleBatchDelete = () => {
    confirm({
      title: intl.formatMessage({ id: 'helpManage.batchDelete' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'helpManage.deleteConfirmContent' }),
      okText: intl.formatMessage({ id: 'helpManage.delete' }),
      okType: 'danger',
      cancelText: intl.formatMessage({ id: 'helpManage.cancel' }),
      maskClosable: false,
      onOk: async () => {
        setLoading(true);
        try {
          // 获取可删除的ID（非已发布状态）
          const deleteIds = selectedRowKeys.filter((key) => {
            const record = helpData.find((item) => item.key === key);
            return record && record.status !== HelpStatus.PUBLISHED;
          }) as string[];

          if (deleteIds.length > 0) {
            // 调用批量删除API
            const response = await batchDeleteHelp(deleteIds);
            if (response && response.success) {
              setSelectedRowKeys([]);
              message.success(intl.formatMessage({ id: 'helpManage.batchDeleteSuccess' }));
              fetchHelpList(pagination.current, pagination.pageSize, searchParams);
            } else {
              message.error(
                response.message || intl.formatMessage({ id: 'helpManage.batchDeleteFailed' }),
              );
            }
          } else {
            message.warning(intl.formatMessage({ id: 'helpManage.noDeleteItems' }));
          }
        } catch (error) {
          console.error('批量删除失败:', error);
          message.error(intl.formatMessage({ id: 'helpManage.batchDeleteFailed' }));
        } finally {
          setLoading(false);
        }
      },
    });
  };

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

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    getCheckboxProps: (record: HelpItemType) => ({
      disabled: record.status === HelpStatus.PUBLISHED, // 已发布的不能选择
    }),
  };

  const hasSelected = selectedRowKeys.length > 0;

  // 处理模态框取消
  const handleModalCancel = () => {
    setModalVisible(false);
    setIsViewMode(false);
    setViewData(null);
  };

  // 表格列定义
  const columns = [
    {
      title: intl.formatMessage({ id: 'helpManage.serialNumber' }),
      render: (_: any, record: HelpItemType, index: number) => index + 1,
      width: 80,
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'helpManage.title.label' }),
      dataIndex: 'title',
      key: 'title',
      ellipsis: {
        showTitle: false,
      },
      render: (title: string, record: HelpItemType) => (
        <Tooltip placement="topLeft" title={title}>
          <span>
            {record.isTop === TopStatus.YES && (
              <Tag color="red" style={{ marginRight: 8 }}>
                {intl.formatMessage({ id: 'helpManage.top' })}
              </Tag>
            )}
            {title}
          </span>
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'helpManage.category' }),
      dataIndex: 'type',
      key: 'type',
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'helpManage.date' }),
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'helpManage.status' }),
      dataIndex: 'status',
      key: 'status',
      align: 'center' as const,
      render: (status: string) => getStatusTag(status),
    },
    {
      title: intl.formatMessage({ id: 'helpManage.publisher' }),
      dataIndex: 'createBy',
      key: 'createBy',
      align: 'center' as const,
    },
    {
      title: intl.formatMessage({ id: 'helpManage.operation' }),
      key: 'action',
      width: 300,
      align: 'center' as const,
      render: (_: unknown, record: HelpItemType) => (
        <>
          <Button type="link" onClick={() => handleView(record)}>
            {intl.formatMessage({ id: 'helpManage.view' })}
          </Button>
          {record.status === HelpStatus.PUBLISHED ? (
            <>
              <Button type="link" onClick={() => handlePublishStatus(record)}>
                {intl.formatMessage({ id: 'helpManage.unpublish' })}
              </Button>
            </>
          ) : (
            <>
              <Button type="link" onClick={() => handleEdit(record)}>
                {intl.formatMessage({ id: 'helpManage.edit' })}
              </Button>
              <Button type="link" onClick={() => handlePublishStatus(record)}>
                {intl.formatMessage({ id: 'helpManage.publish' })}
              </Button>
              <Button type="link" onClick={() => showDeleteConfirm(record)}>
                {intl.formatMessage({ id: 'helpManage.delete' })}
              </Button>
            </>
          )}
        </>
      ),
    },
  ];

  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: 'helpManage.title.label' })}>
            <Input
              placeholder={intl.formatMessage({ id: 'helpManage.searchTitlePlaceholder' })}
              allowClear
            />
          </Form.Item>
          <Form.Item name="type" label={intl.formatMessage({ id: 'helpManage.category' })}>
            <Select
              placeholder={intl.formatMessage({ id: 'helpManage.searchCategoryPlaceholder' })}
              allowClear
              style={{ width: 150 }}
            >
              {categoryOptions.map((option) => (
                <Option key={option.value} value={option.value}>
                  {typeof option.label === 'function' ? option.label() : option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="status" label={intl.formatMessage({ id: 'helpManage.status' })}>
            <Select
              placeholder={intl.formatMessage({ id: 'helpManage.searchStatusPlaceholder' })}
              allowClear
              style={{ width: 120 }}
            >
              <Option value={HelpStatus.DRAFT}>{HelpStatusText[HelpStatus.DRAFT]()}</Option>
              <Option value={HelpStatus.PUBLISHED}>{HelpStatusText[HelpStatus.PUBLISHED]()}</Option>
              <Option value={HelpStatus.UNPUBLISHED}>
                {HelpStatusText[HelpStatus.UNPUBLISHED]()}
              </Option>
            </Select>
          </Form.Item>
          <Form.Item className="filter-btns">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              {intl.formatMessage({ id: 'helpManage.search' })}
            </Button>
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                form.resetFields();
                fetchHelpList(1, pagination.pageSize, {});
              }}
            >
              {intl.formatMessage({ id: 'helpManage.reset' })}
            </Button>
          </Form.Item>
        </Form>

        <div className="right-buttons">
          <Button type="primary" ghost icon={<PlusOutlined />} onClick={handleAdd}>
            {intl.formatMessage({ id: 'helpManage.add' })}
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={handleBatchDelete}
            disabled={!hasSelected}
            loading={loading}
          >
            {intl.formatMessage({ id: 'helpManage.delete' })}
          </Button>
          {hasSelected && (
            <span className="selected-count">
              {intl.formatMessage(
                { id: 'helpManage.selectedCount' },
                { count: selectedRowKeys.length },
              )}
            </span>
          )}
        </div>
      </div>

      <div className="content-area">
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={helpData}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          rowKey="id"
          scroll={{ x: 1200 }}
        />
      </div>

      {/* 新增/编辑/查看模态框 */}
      <Modal
        title={
          isViewMode
            ? intl.formatMessage({ id: 'helpManage.view' })
            : isEdit
            ? intl.formatMessage({ id: 'helpManage.edit' })
            : intl.formatMessage({ id: 'helpManage.add' })
        }
        visible={modalVisible}
        onCancel={handleModalCancel}
        footer={null}
        width={800}
        destroyOnClose
        maskClosable={false}
      >
        {isViewMode ? (
          <HelpManageInfo data={viewData} />
        ) : (
          <HelpManageForm id={currentId} isEdit={isEdit} onSuccess={handleModalCancel} />
        )}
      </Modal>
    </div>
  );
};

export default HelpManage;
