import React, { useState } from 'react';
import { useIntl } from 'umi';
import { Button, Table, Space, Modal, message, Input, Select, Form, Tooltip, Switch, Upload, Tag } from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  SearchOutlined,
  InboxOutlined,
} from '@ant-design/icons';
import { validateFileSize } from '@/utils/utils';
import styles from './downloadManage.less';
import type { UploadFile } from 'antd/es/upload/interface';

const { Option } = Select;
const { Dragger } = Upload;

type DownloadType = API.DownloadRecord & {
  key: string;
};

const DownloadManage: 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 [currentId, setCurrentId] = useState<string>('');
  const [modalForm] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [thumbnailList, setThumbnailList] = useState<UploadFile[]>([]);
  const [downloadData, setDownloadData] = useState<DownloadType[]>([
    {
      key: '1',
      id: '1',
      name: '采购申请模板',
      category: '模板文件',
      keyword: '采购,申请,模板',
      createTime: '2023-06-15 10:30:00',
      createBy: 'admin',
      status: '1', // 已发布
      thumbnail: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    },
    {
      key: '2',
      id: '2',
      name: '系统操作手册V1.0',
      category: '操作手册',
      keyword: '系统,操作,手册',
      createTime: '2023-06-20 14:45:00',
      createBy: 'admin',
      status: '0', // 草稿
      thumbnail: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    },
    {
      key: '3',
      id: '3',
      name: '发票申请指南',
      category: '操作手册',
      keyword: '发票,申请,指南',
      createTime: '2023-06-25 09:15:00',
      createBy: 'admin',
      status: '1', // 已发布
      thumbnail: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    },
  ]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 3,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<API.DownloadSearchParams>({});

  // 获取下载中心列表（模拟数据）
  const fetchDownloadList = (current: number = 1, pageSize: number = 10) => {
    setLoading(true);
    // 模拟API请求延迟
    setTimeout(() => {
      setLoading(false);
    }, 500);
  };

  // 处理编辑
  const handleEdit = (record: DownloadType) => {
    // 检查是否为已发布状态
    if (record.status === '1') {
      message.warning('已发布的文件不能编辑');
      return;
    }

    setIsEdit(true);
    setCurrentId(record.id);
    setModalVisible(true);

    // 填充表单数据
    modalForm.setFieldsValue({
      name: record.name,
      category: record.category,
      keyword: record.keyword,
    });

    // 重置文件列表和缩略图
    setFileList([]);
    if (record.thumbnail) {
      setThumbnailList([
        {
          uid: '-1',
          name: 'thumbnail.png',
          status: 'done',
          url: record.thumbnail,
          type: 'image/png',
          size: 0,
        } as UploadFile
      ]);
    } else {
      setThumbnailList([]);
    }
  };

  // 处理删除
  const showDeleteConfirm = (record: DownloadType) => {
    // 检查是否为已发布状态
    if (record.status === '1') {
      message.warning('已发布的文件不能删除');
      return;
    }

    Modal.confirm({
      title: '确定要删除该文件吗?',
      icon: <ExclamationCircleOutlined />,
      content: `名称: ${record.name}`,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      maskClosable: false,
      onOk: async () => {
        try {
          // 模拟删除操作
          const newData = downloadData.filter(item => item.id !== record.id);
          setDownloadData(newData);
          message.success('删除成功');
        } catch (error) {
          console.error('删除文件失败:', error);
          message.error('删除失败');
        }
      },
    });
  };

  // 处理发布/下架
  const handlePublishStatus = async (record: DownloadType) => {
    // 状态: 0-草稿，1-已发布
    const isPublished = record.status === '1';
    const actionText = isPublished ? '下架' : '发布';
    const newStatus = isPublished ? '0' : '1';

    try {
      // 模拟API请求
      const newData = downloadData.map(item =>
        item.id === record.id ? { ...item, status: newStatus } : item
      );
      setDownloadData(newData);
      message.success(`${actionText}成功`);
    } catch (error) {
      console.error(`${actionText}失败:`, error);
      message.error(`${actionText}失败`);
    }
  };

  // 获取栏目标签
  const getCategoryTag = (category: string) => {
    switch (category) {
      case '模板文件':
        return <Tag color="blue">模板文件</Tag>;
      case '操作手册':
        return <Tag color="green">操作手册</Tag>;
      default:
        return <Tag color="default">其他</Tag>;
    }
  };

  // 获取状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case '0':
        return <Tag color="default">草稿</Tag>;
      case '1':
        return <Tag color="green">已发布</Tag>;
      default:
        return <Tag color="default">未知</Tag>;
    }
  };

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

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '缩略图',
      dataIndex: 'thumbnail',
      key: 'thumbnail',
      render: (thumbnail: string) => (
        thumbnail ? <img src={thumbnail} alt="缩略图" style={{ width: 50, height: 50, objectFit: 'cover' }} /> : '无'
      ),
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: {
        showTitle: false,
      },
      render: (name: string) => (
        <Tooltip placement="topLeft" title={name}>
          {name}
        </Tooltip>
      ),
    },
    {
      title: '栏目',
      dataIndex: 'category',
      key: 'category',
      render: (category: string) => getCategoryTag(category),
    },
    {
      title: '关键词',
      dataIndex: 'keyword',
      key: 'keyword',
      ellipsis: {
        showTitle: false,
      },
      render: (keyword: string) => (
        <Tooltip placement="topLeft" title={keyword}>
          {keyword}
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '上传时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '上传人',
      dataIndex: 'createBy',
      align: 'center' as const,
      key: 'createBy',
    },
    {
      title: '操作',
      key: 'action',
      width: 300,
      align: 'center' as const,
      render: (_: unknown, record: DownloadType) => (
        <>
          <Button type="link" onClick={() => window.open('#')}>
            下载
          </Button>
          {record.status === '1' ? (
            <Button type="link" onClick={() => handlePublishStatus(record)}>
              下架
            </Button>
          ) : (
            <>
              <Button type="link" onClick={() => handleEdit(record)}>
                编辑
              </Button>
              <Button
                type="link"
                onClick={() => handlePublishStatus(record)}
              >
                发布
              </Button>
            </>
          )}
          {record.status !== '1' && (
            <Button
              type="link"
              danger
              onClick={() => showDeleteConfirm(record)}
            >
              删除
            </Button>
          )}
        </>
      ),
    },
  ];

  // 行选择限制
  const checkSelectable = (record: DownloadType) => {
    return record.status !== '1'; // 已发布的不能选择
  };

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

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

  const hasSelected = selectedRowKeys.length > 0;

  // 处理添加
  const handleAdd = () => {
    setIsEdit(false);
    setCurrentId('');
    modalForm.resetFields();
    setFileList([]);
    setThumbnailList([]);
    setModalVisible(true);
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    Modal.confirm({
      title: '确定要删除选中的文件吗?',
      icon: <ExclamationCircleOutlined />,
      content: '删除后无法恢复',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      maskClosable: false,
      onOk: async () => {
        setLoading(true);
        try {
          // 模拟批量删除，过滤掉已发布的文件
          const deleteIds = selectedRowKeys.filter(key => {
            const record = downloadData.find(item => item.key === key);
            return record && record.status !== '1';
          });

          const newData = downloadData.filter(item => !deleteIds.includes(item.key));
          setDownloadData(newData);
          setSelectedRowKeys([]);
          message.success('删除成功');
        } catch (error) {
          console.error('批量删除失败:', error);
          message.error('批量删除失败');
        } finally {
          setLoading(false);
        }
      },
    });
  };

  // 处理搜索
  const handleSearch = (values: API.DownloadSearchParams) => {
    console.log('搜索条件:', values);
    setSearchParams(values);

    // 模拟搜索，实际项目中应调用API
    const initialData = [
      {
        key: '1',
        id: '1',
        name: '采购申请模板',
        category: '模板文件',
        keyword: '采购,申请,模板',
        createTime: '2023-06-15 10:30:00',
        createBy: 'admin',
        status: '1', // 已发布
        thumbnail: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      },
      {
        key: '2',
        id: '2',
        name: '系统操作手册V1.0',
        category: '操作手册',
        keyword: '系统,操作,手册',
        createTime: '2023-06-20 14:45:00',
        createBy: 'admin',
        status: '0', // 草稿
        thumbnail: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      },
      {
        key: '3',
        id: '3',
        name: '发票申请指南',
        category: '操作手册',
        keyword: '发票,申请,指南',
        createTime: '2023-06-25 09:15:00',
        createBy: 'admin',
        status: '1', // 已发布
        thumbnail: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      },
    ];

    if (values.name || values.category || values.status) {
      const filteredData = initialData.filter(item => {
        const nameMatch = values.name ? item.name.includes(values.name) : true;
        const categoryMatch = values.category ? item.category === values.category : true;
        const statusMatch = values.status ? item.status === values.status : true;
        return nameMatch && categoryMatch && statusMatch;
      });
      setDownloadData(filteredData);
    } else {
      setDownloadData(initialData);
    }
  };

  // 处理文件上传变化
  const handleFileChange = (info: any) => {
    setFileList(info.fileList.slice(-1)); // 只保留最后一个文件
  };

  // 处理缩略图上传变化
  const handleThumbnailChange = (info: any) => {
    setThumbnailList(info.fileList.slice(-1)); // 只保留最后一个文件

    // 如果上传成功，模拟获取URL
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    }
  };

  // 处理模态框提交
  const handleModalSubmit = () => {
    modalForm.validateFields().then(values => {
      try {
        // 检查是否有文件上传
        if (!isEdit && fileList.length === 0) {
          message.error('请上传文件');
          return;
        }

        const thumbnailUrl = thumbnailList.length > 0
          ? thumbnailList[0].url || 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
          : undefined;

        const newItem: DownloadType = {
          key: isEdit ? currentId : (downloadData.length + 1).toString(),
          id: isEdit ? currentId : (downloadData.length + 1).toString(),
          name: values.name,
          category: values.category,
          keyword: values.keyword,
          createTime: new Date().toLocaleString(),
          createBy: 'admin',
          status: '0', // 默认为草稿状态
          thumbnail: thumbnailUrl,
        };

        if (isEdit) {
          // 编辑模式，更新数据
          const newData = downloadData.map(item =>
            item.id === currentId ? newItem : item
          );
          setDownloadData(newData);
          message.success('更新成功');
        } else {
          // 新增模式，添加数据
          setDownloadData([...downloadData, newItem]);
          message.success('添加成功');
        }

        setModalVisible(false);
        modalForm.resetFields();
        setFileList([]);
        setThumbnailList([]);
      } catch (error) {
        console.error(isEdit ? '更新文件失败:' : '添加文件失败:', error);
        message.error(isEdit ? '更新失败' : '添加失败');
      }
    }).catch(info => {
      console.log('校验失败:', info);
    });
  };

  // 处理模态框取消
  const handleModalCancel = () => {
    setModalVisible(false);
    modalForm.resetFields();
    setFileList([]);
    setThumbnailList([]);
  };

  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="name" label="名称">
            <Input placeholder="请输入名称关键词" allowClear />
          </Form.Item>
          <Form.Item name="category" label="栏目">
            <Select placeholder="请选择栏目" allowClear>
              <Option value="模板文件">模板文件</Option>
              <Option value="操作手册">操作手册</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" allowClear>
              <Option value="0">草稿</Option>
              <Option value="1">已发布</Option>
            </Select>
          </Form.Item>
          <Form.Item className="filter-btns">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                form.resetFields();
                setSearchParams({});
                handleSearch({});
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>

        <div className="right-buttons">
          <Button
            type="primary"
            ghost
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={handleBatchDelete}
            disabled={!hasSelected}
            loading={loading}
          >
            删除
          </Button>
          {hasSelected && (
            <span className="selected-count">
              已选择 {selectedRowKeys.length} 项
            </span>
          )}
        </div>
      </div>

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

      {/* 新增/编辑模态框 */}
      <Modal
        title={isEdit ? "编辑文件" : "新增文件"}
        visible={modalVisible}
        onOk={handleModalSubmit}
        onCancel={handleModalCancel}
        width={600}
        maskClosable={false}
        destroyOnClose
      >
        <Form
          form={modalForm}
          layout="vertical"
          name="downloadForm"
          preserve={false}
        >
          <Form.Item
            name="name"
            label="名称"
            rules={[{ required: true, message: '请输入名称' }]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>

          <Form.Item
            name="category"
            label="栏目"
            rules={[{ required: true, message: '请选择栏目' }]}
          >
            <Select placeholder="请选择栏目">
              <Option value="模板文件">模板文件</Option>
              <Option value="操作手册">操作手册</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="keyword"
            label="关键词"
            rules={[{ required: true, message: '请输入关键词' }]}
          >
            <Input placeholder="请输入关键词，多个关键词用逗号分隔" />
          </Form.Item>

          <Form.Item
            name="file"
            label="文件上传"
            rules={[{ required: !isEdit, message: '请上传文件' }]}
          >
            <Dragger
              name="file"
              fileList={fileList}
              beforeUpload={(file) => validateFileSize(file, 20, ['pdf', 'zip', 'rar', 'doc', 'docx'])}
              onChange={handleFileChange}
              action="/"
              maxCount={1}
            >
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className={styles.uploadHint}>支持格式：.rar .zip .doc .docx .pdf，单个文件不能超过20MB</p>
            </Dragger>
          </Form.Item>

          <Form.Item
            name="thumbnail"
            label="缩略图"
            extra="支持jpg、png、gif等图片格式，大小不超过2MB"
          >
            <Upload
              name="thumbnail"
              listType="picture-card"
              fileList={thumbnailList}
              beforeUpload={(file) => validateFileSize(file, 2, ['jpg', 'png', 'gif'])}
              onChange={handleThumbnailChange}
              action="/"
              maxCount={1}
            >
              {thumbnailList.length >= 1 ? null : (
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传</div>
                </div>
              )}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DownloadManage;
