import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Button,
  Input,
  Space,
  Tooltip,
  List,
  Tag,
  Popconfirm,
  message,
  Drawer,
  Form,
  Switch,
  Select,
  Splitter,
  Modal,
  Upload,
  Alert,
} from 'antd';
import {
  PlusOutlined,
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined,
  UploadOutlined,
  RobotOutlined,
} from '@ant-design/icons';
import {
  getSysDictionaryList as getDictionaryList,
  createSysDictionary as createDictionary,
  updateSysDictionary as updateDictionary,
  deleteSysDictionary as deleteDictionary,
  findSysDictionary as findDictionary,
  exportSysDictionary,
  importSysDictionary,
} from '@/services/kratos/dictionary';
import { butler, eye } from '@/services/kratos/autoCode';
import DictionaryDetail from './detail';
import styles from './index.less';

interface DictionaryItem {
  ID: number;
  name: string;
  type: string;
  status: boolean;
  desc: string;
  parentID?: number;
}

const DictionaryPage: React.FC = () => {
  const [dictionaryList, setDictionaryList] = useState<DictionaryItem[]>([]);
  const [selectedId, setSelectedId] = useState<number>(0);
  const [searchName, setSearchName] = useState('');
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editType, setEditType] = useState<'create' | 'update'>('create');
  const [currentRecord, setCurrentRecord] = useState<DictionaryItem | null>(null);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  // 导入相关
  const [importDrawerVisible, setImportDrawerVisible] = useState(false);
  const [importJsonText, setImportJsonText] = useState('');
  const [importing, setImporting] = useState(false);
  const [jsonPreviewError, setJsonPreviewError] = useState('');
  const [isDragging, setIsDragging] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // AI相关
  const [aiDialogVisible, setAiDialogVisible] = useState(false);
  const [aiPrompt, setAiPrompt] = useState('');
  const [aiGenerating, setAiGenerating] = useState(false);

  // 获取字典列表
  const fetchDictionaryList = async () => {
    setLoading(true);
    try {
      const res = await getDictionaryList({ name: searchName.trim() });
      if (res.code === 0) {
        setDictionaryList(res.data || []);
        if (res.data?.length > 0 && !selectedId) {
          setSelectedId(res.data[0].ID);
        }
      }
    } finally {
      setLoading(false);
    }
  };

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

  // 监听JSON文本变化
  useEffect(() => {
    if (!importJsonText.trim()) {
      setJsonPreviewError('');
      return;
    }
    try {
      JSON.parse(importJsonText);
      setJsonPreviewError('');
    } catch (e: any) {
      setJsonPreviewError('JSON格式错误: ' + e.message);
    }
  }, [importJsonText]);

  // 搜索
  const handleSearch = () => {
    fetchDictionaryList();
  };

  // 打开新增抽屉
  const handleAdd = () => {
    setEditType('create');
    setCurrentRecord(null);
    form.resetFields();
    form.setFieldsValue({ status: true });
    setDrawerVisible(true);
  };

  // 打开编辑抽屉
  const handleEdit = async (record: DictionaryItem, e: React.MouseEvent) => {
    e.stopPropagation();
    setEditType('update');
    try {
      const res = await findDictionary({ ID: record.ID });
      if (res.code === 0) {
        setCurrentRecord(res.data.resysDictionary);
        form.setFieldsValue(res.data.resysDictionary);
        setDrawerVisible(true);
      }
    } catch (error) {
      message.error('获取字典详情失败');
    }
  };

  // 删除字典
  const handleDelete = async (record: DictionaryItem, e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      const res = await deleteDictionary({ ID: record.ID });
      if (res.code === 0) {
        message.success('删除成功');
        fetchDictionaryList();
        if (selectedId === record.ID) {
          setSelectedId(0);
        }
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 导出字典
  const handleExport = async (record: DictionaryItem, e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      const res = await exportSysDictionary({ ID: record.ID });
      if (res.code === 0) {
        const jsonStr = JSON.stringify(res.data, null, 2);
        const blob = new Blob([jsonStr], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `${record.type}_${record.name}_dictionary.json`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        message.success('导出成功');
      }
    } catch (error) {
      message.error('导出失败');
    }
  };

  // 关闭抽屉
  const handleCloseDrawer = () => {
    setDrawerVisible(false);
    form.resetFields();
    setCurrentRecord(null);
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      let res;
      if (editType === 'create') {
        res = await createDictionary(values);
      } else {
        res = await updateDictionary({ ...currentRecord, ...values });
      }
      if (res.code === 0) {
        message.success(editType === 'create' ? '创建成功' : '更新成功');
        handleCloseDrawer();
        fetchDictionaryList();
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 选择字典
  const handleSelectDictionary = (record: DictionaryItem) => {
    setSelectedId(record.ID);
  };

  // 获取可选的父级字典
  const getAvailableParentDictionaries = () => {
    if (editType === 'update' && currentRecord) {
      return dictionaryList.filter((dict) => dict.ID !== currentRecord.ID);
    }
    return dictionaryList;
  };

  // 打开导入抽屉
  const openImportDrawer = () => {
    setImportDrawerVisible(true);
    setImportJsonText('');
    setJsonPreviewError('');
    setIsDragging(false);
  };

  // 关闭导入抽屉
  const closeImportDrawer = () => {
    setImportDrawerVisible(false);
    setImportJsonText('');
    setJsonPreviewError('');
    setIsDragging(false);
  };

  // 处理拖拽
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      readJsonFile(files[0]);
    }
  };

  // 触发文件选择
  const triggerFileInput = () => {
    fileInputRef.current?.click();
  };

  // 处理文件选择
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files && files.length > 0) {
      readJsonFile(files[0]);
      e.target.value = '';
    }
  };

  // 读取JSON文件
  const readJsonFile = (file: File) => {
    if (!file.name.endsWith('.json')) {
      message.warning('请上传 JSON 文件');
      return;
    }
    const reader = new FileReader();
    reader.onload = (event) => {
      try {
        const content = event.target?.result as string;
        JSON.parse(content);
        setImportJsonText(content);
        message.success('文件读取成功');
      } catch (error) {
        message.error('文件内容不是有效的 JSON 格式');
      }
    };
    reader.onerror = () => {
      message.error('文件读取失败');
    };
    reader.readAsText(file);
  };

  // 处理导入
  const handleImport = async () => {
    if (!importJsonText.trim()) {
      message.warning('请输入JSON数据');
      return;
    }
    if (jsonPreviewError) {
      message.error('JSON格式错误，请检查后重试');
      return;
    }
    try {
      setImporting(true);
      const res = await importSysDictionary({ json: importJsonText });
      if (res.code === 0) {
        message.success('导入成功');
        closeImportDrawer();
        fetchDictionaryList();
      }
    } catch (error: any) {
      message.error('导入失败: ' + error.message);
    } finally {
      setImporting(false);
    }
  };

  // 打开AI对话框
  const openAiDialog = () => {
    setAiDialogVisible(true);
    setAiPrompt('');
  };

  // 关闭AI对话框
  const closeAiDialog = () => {
    setAiDialogVisible(false);
    setAiPrompt('');
  };

  // 处理AI生成
  const handleAiGenerate = async () => {
    if (!aiPrompt.trim()) {
      message.warning('请输入描述内容');
      return;
    }
    try {
      setAiGenerating(true);
      const aiRes = await butler({ prompt: aiPrompt, command: 'dict' });
      if (aiRes && aiRes.code === 0) {
        message.success('AI 生成成功');
        try {
          if (typeof aiRes.data === 'string') {
            setImportJsonText(aiRes.data);
          } else {
            setImportJsonText(JSON.stringify(aiRes.data, null, 2));
          }
          setJsonPreviewError('');
          setImportDrawerVisible(true);
          closeAiDialog();
        } catch (e: any) {
          message.error('处理 AI 返回结果失败: ' + (e.message || e));
        }
      } else {
        message.error(aiRes?.msg || 'AI 生成失败');
      }
    } catch (err: any) {
      message.error('AI 调用失败: ' + (err.message || err));
    } finally {
      setAiGenerating(false);
    }
  };

  // 处理粘贴图片
  const handlePaste = async (e: React.ClipboardEvent) => {
    const items = e.clipboardData.items;
    for (let i = 0; i < items.length; i++) {
      if (items[i].type.indexOf('image') !== -1) {
        const file = items[i].getAsFile();
        if (file) {
          const reader = new FileReader();
          reader.onload = async (event) => {
            const base64String = event.target?.result as string;
            try {
              const res = await eye({ picture: base64String, command: 'dictEye' });
              if (res.code === 0) {
                setAiPrompt(res.data);
              }
            } catch (error) {
              message.error('图片识别失败');
            }
          };
          reader.readAsDataURL(file);
        }
      }
    }
  };

  // 识图功能
  const handleEyeFunc = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = (event: any) => {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = async (e) => {
          const base64String = e.target?.result as string;
          try {
            const res = await eye({ picture: base64String, command: 'dictEye' });
            if (res.code === 0) {
              setAiPrompt(res.data);
            }
          } catch (error) {
            message.error('图片识别失败');
          }
        };
        reader.readAsDataURL(file);
      }
    };
    input.click();
  };

  return (
    <PageContainer>
      <div className={styles.warningBar}>
        获取字典且缓存方法已在前端 utils/dictionary 已经封装完成，不必自己书写，使用方法查看文件内注释
      </div>
      <Splitter style={{ height: 'calc(100vh - 220px)' }}>
        <Splitter.Panel defaultSize="300px" min="200px" max="500px" collapsible>
          <Card
            title="字典列表"
            className={styles.dictionaryCard}
            extra={
              <Space>
                <Tooltip title="搜索">
                  <Input
                    placeholder="搜索字典"
                    value={searchName}
                    onChange={(e) => setSearchName(e.target.value)}
                    onPressEnter={handleSearch}
                    suffix={<SearchOutlined onClick={handleSearch} />}
                    style={{ width: 120 }}
                    allowClear
                  />
                </Tooltip>
                <Tooltip title="导入字典">
                  <Button type="default" icon={<UploadOutlined />} onClick={openImportDrawer} />
                </Tooltip>
                <Tooltip title="AI 生成字典">
                  <Button type="default" icon={<RobotOutlined />} onClick={openAiDialog} />
                </Tooltip>
                <Tooltip title="新建字典">
                  <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd} />
                </Tooltip>
              </Space>
            }
          >
            <List
              loading={loading}
              dataSource={dictionaryList}
              renderItem={(item) => (
                <List.Item
                  className={`${styles.dictionaryItem} ${
                    selectedId === item.ID ? styles.selected : ''
                  } ${item.parentID ? styles.childItem : ''}`}
                  onClick={() => handleSelectDictionary(item)}
                  actions={[
                    <Tooltip title="导出" key="export">
                      <DownloadOutlined
                        className={styles.exportIcon}
                        onClick={(e) => handleExport(item, e)}
                      />
                    </Tooltip>,
                    <Tooltip title="编辑" key="edit">
                      <EditOutlined
                        className={styles.editIcon}
                        onClick={(e) => handleEdit(item, e)}
                      />
                    </Tooltip>,
                    <Popconfirm
                      key="delete"
                      title="确定要删除吗？"
                      onConfirm={(e) => handleDelete(item, e as any)}
                      onCancel={(e) => e?.stopPropagation()}
                    >
                      <DeleteOutlined
                        className={styles.deleteIcon}
                        onClick={(e) => e.stopPropagation()}
                      />
                    </Popconfirm>,
                  ]}
                >
                  <div className={styles.itemContent}>
                    {item.parentID && <span className={styles.childPrefix}>└─</span>}
                    <span className={styles.itemName}>{item.name}</span>
                    <Tag color="blue" className={styles.itemType}>
                      {item.type}
                    </Tag>
                  </div>
                </List.Item>
              )}
            />
          </Card>
        </Splitter.Panel>
        <Splitter.Panel min="400px">
          <Card title="字典详细内容" className={styles.detailCard}>
            {selectedId > 0 ? (
              <DictionaryDetail sysDictionaryID={selectedId} />
            ) : (
              <div className={styles.emptyTip}>请选择左侧字典查看详情</div>
            )}
          </Card>
        </Splitter.Panel>
      </Splitter>

      {/* 新增/编辑字典抽屉 */}
      <Drawer
        title={editType === 'create' ? '添加字典' : '修改字典'}
        open={drawerVisible}
        onClose={handleCloseDrawer}
        width={500}
        extra={
          <Space>
            <Button onClick={handleCloseDrawer}>取消</Button>
            <Button type="primary" onClick={handleSubmit}>
              确定
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item label="父级字典" name="parentID">
            <Select
              placeholder="请选择父级字典（可选）"
              allowClear
              showSearch
              optionFilterProp="label"
              options={getAvailableParentDictionaries().map((dict) => ({
                label: `${dict.name}（${dict.type}）`,
                value: dict.ID,
              }))}
            />
          </Form.Item>
          <Form.Item
            label="字典名（中）"
            name="name"
            rules={[{ required: true, message: '请输入字典名（中）' }]}
          >
            <Input placeholder="请输入字典名（中）" />
          </Form.Item>
          <Form.Item
            label="字典名（英）"
            name="type"
            rules={[{ required: true, message: '请输入字典名（英）' }]}
          >
            <Input placeholder="请输入字典名（英）" />
          </Form.Item>
          <Form.Item label="状态" name="status" valuePropName="checked">
            <Switch checkedChildren="开启" unCheckedChildren="停用" />
          </Form.Item>
          <Form.Item
            label="描述"
            name="desc"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <Input.TextArea placeholder="请输入描述" rows={3} />
          </Form.Item>
        </Form>
      </Drawer>

      {/* 导入字典抽屉 */}
      <Drawer
        title="导入字典JSON"
        open={importDrawerVisible}
        onClose={closeImportDrawer}
        width={600}
        extra={
          <Space>
            <Button onClick={closeImportDrawer}>取消</Button>
            <Button type="primary" onClick={handleImport} loading={importing}>
              确认导入
            </Button>
          </Space>
        }
      >
        <Alert
          message="请粘贴、编辑或拖拽JSON文件到下方区域"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
        <div
          className={`${styles.dragUploadArea} ${isDragging ? styles.isDragging : ''}`}
          onDrop={handleDrop}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onClick={triggerFileInput}
        >
          <UploadOutlined style={{ fontSize: 48, color: '#8c939d', marginBottom: 16 }} />
          <div>
            <p>将 JSON 文件拖到此处，或点击选择文件</p>
            <p style={{ fontSize: 12, color: '#909399' }}>也可以在下方文本框直接编辑</p>
          </div>
          <input
            ref={fileInputRef}
            type="file"
            accept=".json,application/json"
            style={{ display: 'none' }}
            onChange={handleFileSelect}
          />
        </div>
        <Input.TextArea
          value={importJsonText}
          onChange={(e) => setImportJsonText(e.target.value)}
          rows={15}
          placeholder={`请输入JSON数据，例如：
{
  "name": "性别",
  "type": "gender",
  "status": true,
  "desc": "性别字典",
  "sysDictionaryDetails": [
    {
      "label": "男",
      "value": "1",
      "status": true,
      "sort": 1
    },
    {
      "label": "女",
      "value": "2",
      "status": true,
      "sort": 2
    }
  ]
}`}
          style={{ marginTop: 16, fontFamily: 'monospace' }}
        />
        {jsonPreviewError && (
          <Alert
            message={jsonPreviewError}
            type="error"
            showIcon
            style={{ marginTop: 16 }}
          />
        )}
      </Drawer>

      {/* AI生成字典对话框 */}
      <Modal
        title="AI 生成字典"
        open={aiDialogVisible}
        onCancel={closeAiDialog}
        footer={[
          <Button key="cancel" onClick={closeAiDialog}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleAiGenerate} loading={aiGenerating}>
            确定
          </Button>,
        ]}
        width={520}
      >
        <div style={{ position: 'relative' }}>
          <Input.TextArea
            value={aiPrompt}
            onChange={(e) => setAiPrompt(e.target.value)}
            rows={6}
            maxLength={2000}
            placeholder={`请输入生成字典的描述，例如：生成一个用户状态字典（启用/禁用）
支持粘贴或上传图片后识图生成。`}
            onPaste={handlePaste}
            onKeyDown={(e) => {
              if (e.ctrlKey && e.key === 'Enter') {
                handleAiGenerate();
              }
            }}
          />
          <div style={{ position: 'absolute', right: 8, bottom: 8 }}>
            <Tooltip title="粘贴或上传图片后，识别图片内容生成字典">
              <Button type="primary" icon={<RobotOutlined />} onClick={handleEyeFunc}>
                识图
              </Button>
            </Tooltip>
          </div>
        </div>
      </Modal>
    </PageContainer>
  );
};

export default DictionaryPage;
