import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Alert, Input, Tag, Tree, Dropdown, Modal, Form, message, Image } from 'antd';
import { UploadOutlined, SearchOutlined, DownloadOutlined, DeleteOutlined, PlusOutlined, MoreOutlined, EditOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { DataNode } from 'antd/es/tree';
import { getFileList, deleteFile, editFileName, importURL } from '@/services/kratos/fileUpload';
import { getCategoryList, addCategory, deleteCategory } from '@/services/kratos/attachmentCategory';
import { formatDate, createUUID } from '@/utils/format';
import './index.less';

interface FileItem {
  ID: number;
  UpdatedAt: string;
  name: string;
  url: string;
  tag: string;
  key: string;
}

interface Category {
  ID: number;
  name: string;
  pid: number;
  children?: Category[];
}

/**
 * 文件上传管理页面
 */
const UploadPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState<FileItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [keyword, setKeyword] = useState('');
  const [classId, setClassId] = useState(0);
  const [categories, setCategories] = useState<Category[]>([]);
  const [categoryModalVisible, setCategoryModalVisible] = useState(false);
  const [categoryFormData, setCategoryFormData] = useState({ ID: 0, pid: 0, name: '' });

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const res = await getCategoryList();
      if (res.code === 0) {
        const data = res.data || [];
        setCategories([{ ID: 0, name: '全部分类', pid: 0, children: [] }, ...data]);
      }
    } catch (error) {
      console.error('获取分类失败:', error);
    }
  };

  // 获取文件列表
  const getTableData = async () => {
    setLoading(true);
    try {
      const res = await getFileList({ page, pageSize, keyword, classId });
      if (res.code === 0) {
        setTableData(res.data?.list || []);
        setTotal(res.data?.total || 0);
      }
    } catch (error) {
      console.error('获取文件列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

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

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

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

  // 上传成功回调
  const onUploadSuccess = () => {
    setKeyword('');
    setPage(1);
    getTableData();
  };

  // 删除文件
  const handleDeleteFile = (record: FileItem) => {
    Modal.confirm({
      title: '提示',
      content: '此操作将永久删除文件, 是否继续?',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await deleteFile(record);
          if (res.code === 0) {
            message.success('删除成功!');
            if (tableData.length === 1 && page > 1) {
              setPage(page - 1);
            } else {
              getTableData();
            }
          }
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 下载文件
  const handleDownload = (record: FileItem) => {
    const url = record.url.startsWith('http') ? record.url : `${process.env.NODE_ENV === 'development' ? '/api' : ''}/${record.url}`;
    const a = document.createElement('a');
    a.href = url;
    a.download = record.name;
    a.target = '_blank';
    a.click();
  };

  // 编辑文件名
  const handleEditFileName = (record: FileItem) => {
    Modal.confirm({
      title: '编辑',
      content: (
        <Input
          defaultValue={record.name}
          placeholder="请输入文件名或者备注"
          onChange={(e) => { record.name = e.target.value; }}
        />
      ),
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        if (!record.name?.trim()) {
          message.error('文件名不能为空');
          return Promise.reject();
        }
        try {
          const res = await editFileName(record);
          if (res.code === 0) {
            message.success('编辑成功!');
            getTableData();
          }
        } catch (error) {
          message.error('编辑失败');
        }
      },
    });
  };

  // 导入URL
  const handleImportUrl = () => {
    let inputValue = '';
    Modal.confirm({
      title: '导入',
      content: (
        <div>
          <p style={{ marginBottom: 8, color: '#666' }}>格式：文件名|链接或者仅链接。</p>
          <Input.TextArea
            rows={4}
            placeholder={'我的图片|https://my-oss.com/my.png\nhttps://my-oss.com/my_1.png'}
            onChange={(e) => { inputValue = e.target.value; }}
          />
        </div>
      ),
      okText: '确定',
      cancelText: '取消',
      width: 500,
      onOk: async () => {
        if (!inputValue?.trim()) {
          message.error('内容不能为空');
          return Promise.reject();
        }
        const lines = inputValue.split('\n');
        const importData = lines.map((line) => {
          const parts = line.trim().split('|');
          let url: string, name: string;
          if (parts.length > 1) {
            name = parts[0].trim();
            url = parts[1].trim();
          } else {
            url = parts[0].trim();
            const str = url.substring(url.lastIndexOf('/') + 1);
            name = str.substring(0, str.lastIndexOf('.')) || str;
          }
          if (url) {
            return {
              name,
              url,
              classId,
              tag: url.substring(url.lastIndexOf('.') + 1),
              key: createUUID(),
            };
          }
          return null;
        }).filter(Boolean);

        if (importData.length === 0) {
          message.error('没有有效的URL');
          return Promise.reject();
        }

        try {
          const res = await importURL(importData);
          if (res.code === 0) {
            message.success('导入成功!');
            getTableData();
          }
        } catch (error) {
          message.error('导入失败');
        }
      },
    });
  };

  // 点击分类节点
  const handleCategoryClick = (selectedKeys: React.Key[]) => {
    if (selectedKeys.length > 0) {
      setKeyword('');
      setClassId(Number(selectedKeys[0]));
      setPage(1);
    }
  };

  // 添加分类
  const handleAddCategory = (parentId: number) => {
    setCategoryFormData({ ID: 0, pid: parentId, name: '' });
    setCategoryModalVisible(true);
  };

  // 编辑分类
  const handleEditCategory = (category: Category) => {
    setCategoryFormData({ ID: category.ID, pid: category.pid, name: category.name });
    setCategoryModalVisible(true);
  };

  // 删除分类
  const handleDeleteCategory = async (id: number) => {
    try {
      const res = await deleteCategory({ id });
      if (res.code === 0) {
        message.success('删除成功');
        fetchCategories();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 确认添加/编辑分类
  const handleConfirmCategory = async () => {
    try {
      const values = await form.validateFields();
      const res = await addCategory({ ...categoryFormData, ...values });
      if (res.code === 0) {
        message.success('操作成功');
        fetchCategories();
        setCategoryModalVisible(false);
        form.resetFields();
      }
    } catch (error) {
      console.error('操作失败:', error);
    }
  };

  // 转换分类为树形数据
  const convertToTreeData = (data: Category[]): DataNode[] => {
    return data.map((item) => ({
      key: item.ID,
      title: (
        <div className="tree-node">
          <span className={`node-title ${classId === item.ID ? 'active' : ''}`}>{item.name}</span>
          <Dropdown
            menu={{
              items: item.ID > 0 ? [
                { key: 'add', label: '添加分类', onClick: () => handleAddCategory(item.ID) },
                { key: 'edit', label: '编辑分类', onClick: () => handleEditCategory(item) },
                { key: 'delete', label: '删除分类', onClick: () => handleDeleteCategory(item.ID) },
              ] : [
                { key: 'add', label: '添加分类', onClick: () => handleAddCategory(item.ID) },
              ],
            }}
            trigger={['click']}
          >
            {item.ID > 0 ? <MoreOutlined /> : <PlusOutlined />}
          </Dropdown>
        </div>
      ),
      children: item.children ? convertToTreeData(item.children) : undefined,
    }));
  };

  // 表格列定义
  const columns: ColumnsType<FileItem> = [
    {
      title: '预览',
      dataIndex: 'url',
      key: 'preview',
      width: 100,
      render: (url) => (
        <Image src={url.startsWith('http') ? url : `/api/${url}`} width={60} height={60} style={{ objectFit: 'cover' }} />
      ),
    },
    { title: '日期', dataIndex: 'UpdatedAt', key: 'UpdatedAt', width: 180, render: (text) => formatDate(text) },
    {
      title: '文件名/备注',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      render: (text, record) => (
        <span className="file-name" onClick={() => handleEditFileName(record)}>{text}</span>
      ),
    },
    { title: '链接', dataIndex: 'url', key: 'url', ellipsis: true },
    {
      title: '标签',
      dataIndex: 'tag',
      key: 'tag',
      width: 100,
      render: (tag) => <Tag color={tag?.toLowerCase() === 'jpg' ? 'default' : 'success'}>{tag}</Tag>,
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<DownloadOutlined />} onClick={() => handleDownload(record)}>下载</Button>
          <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDeleteFile(record)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="upload-container">
      <div className="upload-layout">
        <div className="category-panel">
          <div className="category-tree">
            <Tree
              treeData={convertToTreeData(categories)}
              defaultExpandAll
              selectedKeys={[classId]}
              onSelect={handleCategoryClick}
            />
          </div>
        </div>

        <Card className="file-panel">
          <Alert message="点击'文件名'可以编辑；选择的类别即是上传的类别。" type="info" showIcon className="upload-alert" />
          
          <div className="upload-toolbar">
            <Button icon={<UploadOutlined />}>通用上传</Button>
            <Button icon={<UploadOutlined />}>裁剪上传</Button>
            <Button icon={<UploadOutlined />}>扫码上传</Button>
            <Button icon={<UploadOutlined />}>压缩上传</Button>
            <Button type="primary" icon={<UploadOutlined />} onClick={handleImportUrl}>导入URL</Button>
            <Input
              className="search-input"
              placeholder="请输入文件名或备注"
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
              onPressEnter={handleSearch}
            />
            <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>查询</Button>
          </div>

          <Table rowKey="ID" columns={columns} dataSource={tableData} loading={loading}
            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>
      </div>

      <Modal title={categoryFormData.ID === 0 ? '添加分类' : '编辑分类'} open={categoryModalVisible}
        onOk={handleConfirmCategory} onCancel={() => { setCategoryModalVisible(false); form.resetFields(); }}>
        <Form form={form} layout="vertical" initialValues={categoryFormData}>
          <Form.Item name="name" label="分类名称" rules={[{ required: true, message: '请输入分类名称' }, { max: 20, message: '最多20位字符' }]}>
            <Input placeholder="分类名称" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UploadPage;
