import React, { useState, useEffect } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import {
  Button,
  Table,
  Space,
  Modal,
  message,
  Input,
  Select,
  Form,
  Tooltip,
  Tag,
  TablePaginationConfig,
  Tabs,
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import {
  getPolicyPage,
  deletePolicy,
  publishPolicy,
  unpublishPolicy,
  getPolicyDetail,
} from '@/servers/api/policy';
import {
  PolicyStatus,
  PolicyStatusText,
  PolicyStatusColor,
  TopStatus,
} from '@/dicts/policyManageDict';
import PolicyManageInfo from './PolicyManageInfo';
import PolicyManageForm from './PolicyManageForm';

const { Option } = Select;
const { TabPane } = Tabs;

// 扩展 API.PolicyRecord 类型，添加 key 属性
type PolicyType = API.PolicyRecord & {
  key: string;
};

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

const PolicyManage: React.FC = () => {
  const intl = useIntl();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  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.PolicyRecord | null>(null);
  const [policyData, setPolicyData] = useState<PolicyType[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<SearchParams>({});

  // 获取政策列表
  const fetchPolicyList = async (
    current = 1,
    pageSize = 10,
    params: SearchParams = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    try {
      // 构造请求参数
      const requestParams: API.PageRequest = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
        ...params, // 使用传入的参数，而不是依赖状态
      };

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

        // 只添加必要的 key 属性
        setPolicyData(
          records.map((item: API.PolicyRecord) => ({
            ...item,
            key: item.id,
          })),
        );
        setPagination({
          ...pagination,
          current: currentPage,
          pageSize: size,
          total: total,
        });
      } else {
        message.error(response.message || intl.formatMessage({ id: 'policyManage.fetchFailed' }));
      }
    } catch (error) {
      console.error('获取政策列表失败:', error);
      message.error(intl.formatMessage({ id: 'policyManage.fetchFailed' }));
    } finally {
      setLoading(false);
    }
  };

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

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

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

  // 处理编辑
  const handleEdit = (record: PolicyType) => {
    setIsEdit(true);
    setIsViewMode(false);
    setCurrentId(record.id);
    setModalVisible(true);
  };

  // 处理删除
  const showDeleteConfirm = (record: PolicyType) => {
    Modal.confirm({
      title: intl.formatMessage({ id: 'policyManage.confirmDelete' }),
      icon: <ExclamationCircleOutlined />,
      content: `${intl.formatMessage({ id: 'policyManage.deleteConfirmTitle' })}: ${record.title}`,
      okText: intl.formatMessage({ id: 'policyManage.submit' }),
      okType: 'danger',
      cancelText: intl.formatMessage({ id: 'policyManage.cancel' }),
      maskClosable: false,
      onOk: async () => {
        try {
          const response = await deletePolicy(record.id);
          if (response && response.success) {
            message.success(intl.formatMessage({ id: 'policyManage.deleteSuccess' }));
            fetchPolicyList(pagination.current, pagination.pageSize, searchParams); // 重新加载数据
          } else {
            message.error(response.message || intl.formatMessage({ id: 'policyManage.deleteFailed' }));
          }
        } catch (error) {
          console.error('删除政策失败:', error);
          message.error(intl.formatMessage({ id: 'policyManage.deleteFailed' }));
        }
      },
    });
  };

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

    Modal.confirm({
      title: intl.formatMessage({ id: confirmMsgId }),
      icon: <ExclamationCircleOutlined />,
      content: `${intl.formatMessage({ id: 'policyManage.deleteConfirmTitle' })}: ${record.title}`,
      okText: intl.formatMessage({ id: 'policyManage.submit' }),
      cancelText: intl.formatMessage({ id: 'policyManage.cancel' }),
      maskClosable: false,
      onOk: async () => {
        try {
          let response;
          if (isPublished) {
            response = await unpublishPolicy(record.id);
          } else {
            response = await publishPolicy(record.id);
          }

          if (response && response.success) {
            message.success(intl.formatMessage({ id: successMsgId }));
            fetchPolicyList(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 PolicyStatusText;
    const color = PolicyStatusColor[statusKey] || 'default';
    const getText = PolicyStatusText[statusKey];
    const text = typeof getText === 'function' ? getText() : intl.formatMessage({ id: 'policyManage.status.unknown' });
    return <Tag color={color}>{text}</Tag>;
  };

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

  const columns = [
    {
      title: intl.formatMessage({ id: 'policyManage.serialNumber' }),
      // pageNo *pageSize +
      render: (text: string, record: PolicyType, index: number) => index + 1,
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'policyManage.title.label' }),
      dataIndex: 'title',
      key: 'title',
      width: 300,
      ellipsis: {
        showTitle: false,
      },
      render: (title: string, record: PolicyType) => (
        <Tooltip placement="topLeft" title={title}>
          <span>
            {record.isTop === TopStatus.YES && (
              <Tag color="red" style={{ marginRight: 8 }}>
                {intl.formatMessage({ id: 'policyManage.top' })}
              </Tag>
            )}
            {title}
          </span>
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: 'policyManage.date' }),
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
    },
    {
      title: intl.formatMessage({ id: 'policyManage.status' }),
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => getStatusTag(status),
    },
    {
      title: intl.formatMessage({ id: 'policyManage.publisher' }),
      dataIndex: 'createBy',
      key: 'createBy',
      width: 120,
    },
    {
      title: intl.formatMessage({ id: 'policyManage.operation' }),
      key: 'action',
      width: 230,
      align: 'center' as const,
      render: (_: unknown, record: PolicyType) => (
        <>
          <Button type="link" onClick={() => handleView(record)}>
            {intl.formatMessage({ id: 'policyManage.view' })}
          </Button>
          {record.status === PolicyStatus.PUBLISHED ? (
            <Button type="link" onClick={() => handlePublishStatus(record)}>
              {intl.formatMessage({ id: 'policyManage.unpublish' })}
            </Button>
          ) : (
            <>
              <Button type="link" onClick={() => handlePublishStatus(record)}>
                {intl.formatMessage({ id: 'policyManage.publish' })}
              </Button>
              <Button type="link" onClick={() => handleEdit(record)}>
                {intl.formatMessage({ id: 'policyManage.edit' })}
              </Button>
              <Button type="link" onClick={() => showDeleteConfirm(record)}>
                {intl.formatMessage({ id: 'policyManage.delete' })}
              </Button>
            </>
          )}
        </>
      ),
    },
  ];

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

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

  const hasSelected = selectedRowKeys.length > 0;

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

  // 处理批量删除
  const handleBatchDelete = () => {
    Modal.confirm({
      title: intl.formatMessage({ id: 'policyManage.confirmDeleteBatch' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'policyManage.deleteConfirmContent' }),
      okText: intl.formatMessage({ id: 'policyManage.delete' }),
      okType: 'danger',
      cancelText: intl.formatMessage({ id: 'policyManage.cancel' }),
      maskClosable: false,
      onOk: async () => {
        setLoading(true);
        try {
          // 实际项目中应该使用批量删除API
          const deletePromises = selectedRowKeys.map((id) => deletePolicy(id.toString()));
          const results = await Promise.all(deletePromises);

          // 检查是否所有操作都成功
          const allSuccess = results.every((res) => res.success);

          if (allSuccess) {
            setSelectedRowKeys([]);
            message.success(intl.formatMessage({ id: 'policyManage.batchDeleteSuccess' }));
            fetchPolicyList(pagination.current, pagination.pageSize, searchParams); // 重新加载数据
          } else {
            message.error(intl.formatMessage({ id: 'policyManage.batchDeletePartialFailed' }));
          }
        } catch (error) {
          console.error('批量删除失败:', error);
          message.error(intl.formatMessage({ id: 'policyManage.batchDeleteFailed' }));
        } finally {
          setLoading(false);
        }
      },
    });
  };

  // 处理搜索
  const handleSearch = (values: SearchParams) => {
    fetchPolicyList(1, pagination.pageSize, values); // 搜索时重置为第一页，直接传入表单值
  };


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

  return (
    <div className="policy-manage-container 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: 'policyManage.title.label' })}>
            <Input placeholder={intl.formatMessage({ id: 'policyManage.searchTitlePlaceholder' })} allowClear />
          </Form.Item>
          <Form.Item name="status" label={intl.formatMessage({ id: 'policyManage.status' })}>
            <Select placeholder={intl.formatMessage({ id: 'policyManage.searchStatusPlaceholder' })} allowClear>
              <Option value={PolicyStatus.DRAFT}>
                {typeof PolicyStatusText[PolicyStatus.DRAFT] === 'function'
                  ? PolicyStatusText[PolicyStatus.DRAFT]()
                  : intl.formatMessage({ id: 'policyManage.status.draft' })}
              </Option>
              <Option value={PolicyStatus.PUBLISHED}>
                {typeof PolicyStatusText[PolicyStatus.PUBLISHED] === 'function'
                  ? PolicyStatusText[PolicyStatus.PUBLISHED]()
                  : intl.formatMessage({ id: 'policyManage.status.published' })}
              </Option>
              <Option value={PolicyStatus.UNPUBLISHED}>
                {typeof PolicyStatusText[PolicyStatus.UNPUBLISHED] === 'function'
                  ? PolicyStatusText[PolicyStatus.UNPUBLISHED]()
                  : intl.formatMessage({ id: 'policyManage.status.unpublished' })}
              </Option>
            </Select>
          </Form.Item>
          <Form.Item className="filter-btns">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              {intl.formatMessage({ id: 'policyManage.search' })}
            </Button>
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                form.resetFields();
                fetchPolicyList(1, pagination.pageSize, {});
              }}
            >
              {intl.formatMessage({ id: 'policyManage.reset' })}
            </Button>
          </Form.Item>
        </Form>

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

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

      {/* 新增/编辑/查看模态框 */}
      <Modal
        title={isViewMode
          ? intl.formatMessage({ id: 'policyManage.form.view' })
          : isEdit
          ? intl.formatMessage({ id: 'policyManage.form.edit' })
          : intl.formatMessage({ id: 'policyManage.form.add' })}
        visible={modalVisible}
        onCancel={handleModalCancel}
        width={900}
        maskClosable={false}
        destroyOnClose
        footer={
          isViewMode
            ? [
                <Button key="close" onClick={handleModalCancel}>
                  {intl.formatMessage({ id: 'policyManage.close' })}
                </Button>,
              ]
            : null
        }
      >
        {isViewMode && viewData ? (
          // 查看详情模式
          <PolicyManageInfo data={viewData} />
        ) : (
          // 编辑/新增模式
          <PolicyManageForm
            id={currentId}
            isEdit={isEdit}
            onSuccess={() => {
              setModalVisible(false);
              fetchPolicyList(1, pagination.pageSize, searchParams);
            }}
          />
        )}
      </Modal>
    </div>
  );
};

export default PolicyManage;
