import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Form, Input, DatePicker, Select, Drawer, Tag, message, Modal } from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  getInfoList,
  getInfoDataSource,
  createInfo,
  updateInfo,
  deleteInfo,
  deleteInfoByIds,
  findInfo,
} from '@/services/kratos/announcement';
import { formatDate } from '@/utils/format';
import './index.less';

interface Attachment {
  uid: string;
  name: string;
  url: string;
}

interface AnnouncementItem {
  ID: number;
  CreatedAt: string;
  title: string;
  content: string;
  userID: number;
  attachments: Attachment[];
}

interface DataSourceItem {
  label: string;
  value: number;
}

/**
 * 公告管理页面
 */
const AnnouncementPage: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState<AnnouncementItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editType, setEditType] = useState<'create' | 'update'>('create');
  const [dataSource, setDataSource] = useState<{ userID: DataSourceItem[] }>({ userID: [] });

  // 获取数据源
  const fetchDataSource = async () => {
    try {
      const res = await getInfoDataSource();
      if (res.code === 0) {
        setDataSource(res.data || { userID: [] });
      }
    } catch (error) {
      console.error('获取数据源失败:', error);
    }
  };

  // 获取表格数据
  const getTableData = async () => {
    setLoading(true);
    try {
      const searchValues = searchForm.getFieldsValue();
      const res = await getInfoList({
        page,
        pageSize,
        ...searchValues,
      });
      if (res.code === 0) {
        setTableData(res.data?.list || []);
        setTotal(res.data?.total || 0);
      }
    } catch (error) {
      console.error('获取公告列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDataSource();
  }, []);

  useEffect(() => {
    getTableData();
  }, [page, pageSize]);

  // 搜索
  const handleSearch = () => {
    setPage(1);
    getTableData();
  };

  // 重置
  const handleReset = () => {
    searchForm.resetFields();
    setPage(1);
    getTableData();
  };

  // 打开新增抽屉
  const openDrawer = () => {
    setEditType('create');
    editForm.resetFields();
    setDrawerVisible(true);
  };

  // 编辑
  const handleEdit = async (record: AnnouncementItem) => {
    try {
      const res = await findInfo({ ID: record.ID });
      if (res.code === 0) {
        setEditType('update');
        editForm.setFieldsValue(res.data);
        setDrawerVisible(true);
      }
    } catch (error) {
      message.error('获取公告信息失败');
    }
  };

  // 删除单条
  const handleDelete = (record: AnnouncementItem) => {
    Modal.confirm({
      title: '提示',
      content: '确定要删除吗?',
      onOk: async () => {
        try {
          const res = await deleteInfo({ ID: record.ID });
          if (res.code === 0) {
            message.success('删除成功');
            if (tableData.length === 1 && page > 1) {
              setPage(page - 1);
            } else {
              getTableData();
            }
          }
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除吗?',
      onOk: async () => {
        try {
          const res = await deleteInfoByIds({ IDs: selectedRowKeys as number[] });
          if (res.code === 0) {
            message.success('删除成功');
            setSelectedRowKeys([]);
            if (tableData.length === selectedRowKeys.length && page > 1) {
              setPage(page - 1);
            } else {
              getTableData();
            }
          }
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 关闭抽屉
  const closeDrawer = () => {
    setDrawerVisible(false);
    editForm.resetFields();
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await editForm.validateFields();
      let res;
      if (editType === 'create') {
        res = await createInfo(values);
      } else {
        res = await updateInfo(values);
      }
      if (res.code === 0) {
        message.success('操作成功');
        closeDrawer();
        getTableData();
      }
    } catch (error) {
      console.error('提交失败:', error);
    }
  };

  // 下载附件
  const downloadFile = (url: string) => {
    window.open(url.startsWith('http') ? url : `/api/${url}`, '_blank');
  };

  // 过滤数据源
  const filterDataSource = (source: DataSourceItem[], value: number) => {
    const item = source?.find((s) => s.value === value);
    return item?.label || value;
  };

  // 表格列定义
  const columns: ColumnsType<AnnouncementItem> = [
    { title: '日期', dataIndex: 'CreatedAt', key: 'CreatedAt', width: 180, render: (text) => formatDate(text) },
    { title: '标题', dataIndex: 'title', key: 'title', width: 200 },
    {
      title: '作者',
      dataIndex: 'userID',
      key: 'userID',
      width: 120,
      render: (value) => filterDataSource(dataSource.userID, value),
    },
    {
      title: '附件',
      dataIndex: 'attachments',
      key: 'attachments',
      width: 200,
      render: (attachments: Attachment[]) => (
        <div className="file-list">
          {attachments?.map((file) => (
            <Tag key={file.uid} className="file-tag" onClick={() => downloadFile(file.url)}>
              {file.name}
            </Tag>
          ))}
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>变更</Button>
          <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="announcement-container">
      <Card className="search-card">
        <Form form={searchForm} layout="inline" className="search-form">
          <Form.Item name="startCreatedAt" label="开始日期">
            <DatePicker showTime placeholder="开始日期" />
          </Form.Item>
          <Form.Item name="endCreatedAt" label="结束日期">
            <DatePicker showTime placeholder="结束日期" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>查询</Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card className="table-card">
        <div className="table-toolbar">
          <Button type="primary" icon={<PlusOutlined />} onClick={openDrawer}>新增</Button>
          <Button icon={<DeleteOutlined />} disabled={selectedRowKeys.length === 0} onClick={handleBatchDelete}>删除</Button>
        </div>

        <Table
          rowKey="ID"
          columns={columns}
          dataSource={tableData}
          loading={loading}
          rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
          pagination={{
            current: page, pageSize, total, showSizeChanger: true, showQuickJumper: true,
            showTotal: (t) => `共 ${t} 条`, pageSizeOptions: ['10', '30', '50', '100'],
            onChange: (p, ps) => { setPage(p); setPageSize(ps); },
          }}
        />
      </Card>

      <Drawer title={editType === 'create' ? '添加' : '修改'} open={drawerVisible} onClose={closeDrawer} width={800}
        extra={<Space><Button type="primary" onClick={handleSubmit}>确定</Button><Button onClick={closeDrawer}>取消</Button></Space>}>
        <Form form={editForm} layout="vertical" className="drawer-form">
          <Form.Item name="ID" hidden><Input /></Form.Item>
          <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入标题' }]}>
            <Input placeholder="请输入标题" />
          </Form.Item>
          <Form.Item name="content" label="内容">
            <Input.TextArea rows={6} placeholder="请输入内容" />
          </Form.Item>
          <Form.Item name="userID" label="作者">
            <Select placeholder="请选择作者" allowClear options={dataSource.userID?.map((item) => ({ label: item.label, value: item.value }))} />
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
};

export default AnnouncementPage;
