/**
 * KRA - Export Template Page
 * 导出模板管理页面
 */
import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Form,
  Input,
  Select,
  Row,
  Col,
  Drawer,
  Tooltip,
  message,
  Modal,
  DatePicker,
  InputNumber,
  Divider,
  Switch,
  Tabs,
  Spin,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  SearchOutlined,
  ReloadOutlined,
  QuestionCircleOutlined,
  CopyOutlined,
  CodeOutlined,
  EyeOutlined,
  RobotOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import {
  createSysExportTemplate,
  deleteSysExportTemplate,
  deleteSysExportTemplateByIds,
  updateSysExportTemplate,
  findSysExportTemplate,
  getSysExportTemplateList,
  previewSQL,
} from '@/services/kratos/exportTemplate';
import { getDB, getTable, getColumn, butler } from '@/services/kratos/autoCode';
import { formatDate } from '@/utils/date';
import WarningBar from '@/components/WarningBar';
import styles from './index.less';

const { TextArea } = Input;
const { RangePicker } = DatePicker;

// 模板信息占位符
const templatePlaceholder = `模板信息格式：key标识数据库column列名称（在join模式下需要写为 table.column），value标识导出excel列名称，如key为数据库关键字或函数，请按照关键字的处理模式处理，当前以mysql为例，如下：
{
  "table_column1":"第一列",
  "table_column3":"第三列",
  "table_column4":"第四列",
  "\`rows\`":"我属于数据库关键字或函数",
}
如果增加了JOINS导出key应该列为 {table_name1.table_column1:"第一列",table_name2.table_column2:"第二列"}
如果有重复的列名导出格式应为 {table_name1.table_column1 as key:"第一列",table_name2.table_column2 as key2:"第二列"}
JOINS模式下不支持导入
`;

// 搜索条件选项
const typeSearchOptions = [
  { label: '=', value: '=' },
  { label: '<>', value: '<>' },
  { label: '>', value: '>' },
  { label: '<', value: '<' },
  { label: 'LIKE', value: 'LIKE' },
  { label: 'BETWEEN', value: 'BETWEEN' },
  { label: 'NOT BETWEEN', value: 'NOT BETWEEN' },
  { label: 'IN', value: 'IN' },
  { label: 'NOT IN', value: 'NOT IN' },
];

interface ExportTemplateItem {
  ID: number;
  CreatedAt: string;
  name: string;
  tableName: string;
  dbName: string;
  templateID: string;
  templateInfo: string;
  limit: number;
  order: string;
  conditions: ConditionItem[];
  joinTemplate: JoinItem[];
}

interface ConditionItem {
  from: string;
  column: string;
  operator: string;
  templateID?: string;
}

interface JoinItem {
  joins: string;
  table: string;
  on: string;
  templateID?: string;
}

const ExportTemplatePage: React.FC = () => {
  // 表格数据
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState<ExportTemplateItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  
  // 搜索条件
  const [searchInfo, setSearchInfo] = useState<any>({});
  
  // 弹窗控制
  const [dialogVisible, setDialogVisible] = useState(false);
  const [dialogType, setDialogType] = useState<'create' | 'update'>('create');
  const [aiLoading, setAiLoading] = useState(false);
  
  // 表单数据
  const [formData, setFormData] = useState<Partial<ExportTemplateItem>>({
    name: '',
    tableName: '',
    dbName: '',
    templateID: '',
    templateInfo: '',
    limit: 0,
    order: '',
    conditions: [],
    joinTemplate: [],
  });
  
  // AI相关
  const [prompt, setPrompt] = useState('');
  const [tables, setTables] = useState<string[]>([]);
  
  // 数据库选项
  const [dbList, setDbList] = useState<any[]>([]);
  const [tableOptions, setTableOptions] = useState<any[]>([]);
  
  // 代码预览
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('code');
  const [webCode, setWebCode] = useState('');
  
  // SQL预览
  const [previewForm, setPreviewForm] = useState<any>({
    filterDeleted: true,
    order: '',
    limit: 0,
    offset: 0,
  });
  const [previewSQLCode, setPreviewSQLCode] = useState('');
  const [previewTemplate, setPreviewTemplate] = useState<ExportTemplateItem | null>(null);
  const [previewConditions, setPreviewConditions] = useState<ConditionItem[]>([]);

  // 初始化
  useEffect(() => {
    getTableData();
    getDbFunc();
    getTableFunc();
  }, []);

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

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

  // 获取数据库列表
  const getDbFunc = async () => {
    try {
      const res = await getDB({});
      if (res.code === 0 && res.data) {
        setDbList(res.data.dbList || []);
      }
    } catch (error) {
      console.error('获取数据库列表失败:', error);
    }
  };

  // 获取表列表
  const getTableFunc = async (businessDB?: string) => {
    try {
      const res = await getTable({ businessDB: businessDB || formData.dbName || '' });
      if (res.code === 0 && res.data) {
        setTableOptions(res.data.tables || []);
      }
    } catch (error) {
      console.error('获取表列表失败:', error);
    }
  };

  // 业务库变更
  const dbNameChange = (value: string) => {
    setFormData(prev => ({
      ...prev,
      dbName: value,
      tableName: '',
      templateInfo: '',
    }));
    setTables([]);
    getTableFunc(value);
  };

  // 获取表字段并生成模板
  const getColumnFunc = async (aiFlag: boolean) => {
    if (!formData.tableName) {
      message.error('请先选择业务库及选择表后再进行操作');
      return;
    }
    
    setAiLoading(true);
    try {
      const res = await getColumn({
        businessDB: formData.dbName || '',
        tableName: formData.tableName,
        dbName: '',
      });
      
      if (res.code === 0 && res.data) {
        if (aiFlag) {
          // AI自动补全
          const aiRes = await butler({
            data: res.data.columns,
            command: 'exportCompletion',
          });
          if (aiRes.code === 0) {
            const aiData = JSON.parse(aiRes.data);
            setFormData(prev => ({
              ...prev,
              templateInfo: JSON.stringify(aiData.templateInfo, null, 2),
              name: aiData.name,
              templateID: aiData.templateID,
            }));
            setAiLoading(false);
            return;
          }
          message.warning('AI自动补全失败，已调整为逻辑填写');
        }
        
        // 手动生成模板
        const templateInfo: Record<string, string> = {};
        res.data.columns?.forEach((item: any) => {
          templateInfo[item.columnName] = item.columnComment || item.columnName;
        });
        setFormData(prev => ({
          ...prev,
          templateInfo: JSON.stringify(templateInfo, null, 2),
        }));
      }
    } catch (error) {
      message.error('获取字段失败');
    } finally {
      setAiLoading(false);
    }
  };

  // AI帮写
  const autoExport = async () => {
    if (tables.length === 0) {
      message.error('请先选择需要参与导出的表');
      return;
    }
    
    setAiLoading(true);
    try {
      // 获取所有选中表的字段
      const tableMap: Record<string, any[]> = {};
      for (const tableName of tables) {
        const res = await getColumn({
          businessDB: formData.dbName || '',
          tableName,
          dbName: '',
        });
        if (res.code === 0 && res.data) {
          tableMap[tableName] = res.data.columns;
        }
      }
      
      const aiRes = await butler({
        prompt,
        businessDB: formData.dbName || '',
        tableMap,
        command: 'autoExportTemplate',
      });
      
      if (aiRes.code === 0) {
        const aiData = JSON.parse(aiRes.data);
        setFormData(prev => ({
          ...prev,
          name: aiData.name,
          tableName: aiData.tableName,
          templateID: aiData.templateID,
          templateInfo: JSON.stringify(aiData.templateInfo, null, 2),
          joinTemplate: aiData.joinTemplate || [],
        }));
      }
    } catch (error) {
      message.error('AI生成失败');
    } finally {
      setAiLoading(false);
    }
  };

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

  // 重置
  const onReset = () => {
    setSearchInfo({});
    setPage(1);
    getTableData();
  };

  // 打开新增弹窗
  const openDialog = () => {
    setDialogType('create');
    setFormData({
      name: '',
      tableName: '',
      dbName: '',
      templateID: '',
      templateInfo: '',
      limit: 0,
      order: '',
      conditions: [],
      joinTemplate: [],
    });
    setDialogVisible(true);
  };

  // 关闭弹窗
  const closeDialog = () => {
    setDialogVisible(false);
    setFormData({
      name: '',
      tableName: '',
      dbName: '',
      templateID: '',
      templateInfo: '',
      limit: 0,
      order: '',
      conditions: [],
      joinTemplate: [],
    });
  };

  // 编辑
  const updateRow = async (row: ExportTemplateItem) => {
    try {
      const res = await findSysExportTemplate({ ID: row.ID });
      if (res.code === 0 && res.data) {
        const data = res.data.reSysExportTemplate || res.data.resysExportTemplate;
        setDialogType('update');
        setFormData({
          ...data,
          conditions: data.conditions || [],
          joinTemplate: data.joinTemplate || [],
        });
        setDialogVisible(true);
      }
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  // 复制
  const copyRow = async (row: ExportTemplateItem) => {
    try {
      const res = await findSysExportTemplate({ ID: row.ID });
      if (res.code === 0 && res.data) {
        const data = res.data.reSysExportTemplate || res.data.resysExportTemplate;
        setDialogType('create');
        setFormData({
          ...data,
          ID: undefined,
          templateID: data.templateID + '_copy',
          name: data.name + '_copy',
          conditions: data.conditions || [],
          joinTemplate: data.joinTemplate || [],
        });
        setDialogVisible(true);
      }
    } catch (error) {
      message.error('获取详情失败');
    }
  };

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

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

  // 提交表单
  const enterDialog = async () => {
    // 验证模板信息是否为有效JSON
    try {
      JSON.parse(formData.templateInfo || '{}');
    } catch (e) {
      message.error('模板信息格式不正确，请检查');
      return;
    }

    // 验证必填字段
    if (!formData.name || !formData.tableName || !formData.templateID || !formData.templateInfo) {
      message.error('请填写完整的必填信息');
      return;
    }

    const reqData = JSON.parse(JSON.stringify(formData));
    
    // 验证条件
    for (let i = 0; i < (reqData.conditions || []).length; i++) {
      const cond = reqData.conditions[i];
      if (!cond.from || !cond.column || !cond.operator) {
        message.error('请填写完整的导出条件');
        return;
      }
      cond.templateID = reqData.templateID;
    }

    // 验证关联
    for (let i = 0; i < (reqData.joinTemplate || []).length; i++) {
      const join = reqData.joinTemplate[i];
      if (!join.joins || !join.on) {
        message.error('请填写完整的关联');
        return;
      }
      join.templateID = reqData.templateID;
    }

    try {
      let res;
      if (dialogType === 'create') {
        res = await createSysExportTemplate(reqData);
      } else {
        res = await updateSysExportTemplate(reqData as any);
      }
      if (res.code === 0) {
        message.success('操作成功');
        closeDialog();
        getTableData();
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 添加条件
  const addCondition = () => {
    setFormData(prev => ({
      ...prev,
      conditions: [...(prev.conditions || []), { from: '', column: '', operator: '' }],
    }));
  };

  // 删除条件
  const removeCondition = (index: number) => {
    setFormData(prev => ({
      ...prev,
      conditions: (prev.conditions || []).filter((_, i) => i !== index),
    }));
  };

  // 添加关联
  const addJoin = () => {
    setFormData(prev => ({
      ...prev,
      joinTemplate: [...(prev.joinTemplate || []), { joins: 'LEFT JOIN', table: '', on: '' }],
    }));
  };

  // 删除关联
  const removeJoin = (index: number) => {
    setFormData(prev => ({
      ...prev,
      joinTemplate: (prev.joinTemplate || []).filter((_, i) => i !== index),
    }));
  };

  // 生成代码模板
  const getCode = (templateID: string) => {
    return `<template>
  <ExportExcel templateID="${templateID}" />
</template>

<script setup>
import ExportExcel from '@/components/exportExcel/exportExcel.vue'
</script>`;
  };

  // 显示代码预览
  const showCode = (row: ExportTemplateItem) => {
    setWebCode(getCode(row.templateID));
    setActiveTab('code');
    setDrawerVisible(true);
  };

  // 打开SQL预览
  const openPreview = async (row: ExportTemplateItem) => {
    try {
      const res = await findSysExportTemplate({ ID: row.ID });
      if (res.code === 0 && res.data) {
        const data = res.data.reSysExportTemplate || res.data.resysExportTemplate;
        setPreviewTemplate(data);
        setPreviewConditions((data.conditions || []).map((c: ConditionItem) => ({
          from: c.from,
          column: c.column,
          operator: c.operator,
        })));
        setPreviewForm({
          filterDeleted: true,
          order: data.order || '',
          limit: data.limit || 0,
          offset: 0,
        });
        setPreviewSQLCode('');
        setActiveTab('sql');
        setDrawerVisible(true);
      }
    } catch (error) {
      message.error('获取详情失败');
    }
  };

  // 运行SQL预览
  const runPreview = async () => {
    if (!previewTemplate) return;
    
    const paramsCopy = JSON.parse(JSON.stringify(previewForm));
    if (paramsCopy.filterDeleted) paramsCopy.filterDeleted = 'true';
    
    const entries = Object.entries(paramsCopy).filter(([key, v]) => {
      if (v === '' || v === null || v === undefined) return false;
      if ((key === 'limit' || key === 'offset') && Number(v) === 0) return false;
      return true;
    });
    
    const params = entries
      .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
      .join('&');

    try {
      const res = await previewSQL({ templateID: previewTemplate.templateID, params });
      if (res.code === 0 && res.data) {
        setPreviewSQLCode(res.data.sql || '');
      }
    } catch (error) {
      message.error('预览失败');
    }
  };

  // 表格列定义
  const columns: ColumnsType<ExportTemplateItem> = [
    {
      title: '日期',
      dataIndex: 'CreatedAt',
      width: 180,
      render: (val) => formatDate(val),
    },
    {
      title: '数据库',
      dataIndex: 'dbName',
      width: 120,
      render: (val) => val || 'KRA库',
    },
    {
      title: '模板标识',
      dataIndex: 'templateID',
      width: 120,
    },
    {
      title: '模板名称',
      dataIndex: 'name',
      width: 120,
    },
    {
      title: '表名称',
      dataIndex: 'tableName',
      width: 120,
    },
    {
      title: '模板信息',
      dataIndex: 'templateInfo',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 300,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button type="link" size="small" icon={<CopyOutlined />} onClick={() => copyRow(record)}>
            复制
          </Button>
          <Button type="link" size="small" icon={<CodeOutlined />} onClick={() => showCode(record)}>
            代码和SQL预览
          </Button>
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => updateRow(record)}>
            变更
          </Button>
          <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => deleteRow(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      {/* 警告栏 */}
      <WarningBar
        title="本功能提供同步的表格导出功能，大数据量的异步表格导出功能，可以选择点我定制"
        href="https://flipped-aurora.feishu.cn/docx/KwjxdnvatozgwIxGV0rcpkZSn4d"
      />

      {/* 搜索区域 */}
      <Card className={styles.searchCard}>
        <Form layout="inline">
          <Form.Item label="创建日期">
            <RangePicker
              showTime
              onChange={(dates) => {
                if (dates) {
                  setSearchInfo((prev: any) => ({
                    ...prev,
                    startCreatedAt: dates[0]?.toISOString(),
                    endCreatedAt: dates[1]?.toISOString(),
                  }));
                } else {
                  setSearchInfo((prev: any) => ({
                    ...prev,
                    startCreatedAt: undefined,
                    endCreatedAt: undefined,
                  }));
                }
              }}
            />
          </Form.Item>
          <Form.Item label="模板名称">
            <Input
              placeholder="搜索条件"
              value={searchInfo.name}
              onChange={(e) => setSearchInfo((prev: any) => ({ ...prev, name: e.target.value }))}
            />
          </Form.Item>
          <Form.Item label="表名称">
            <Input
              placeholder="搜索条件"
              value={searchInfo.tableName}
              onChange={(e) => setSearchInfo((prev: any) => ({ ...prev, tableName: e.target.value }))}
            />
          </Form.Item>
          <Form.Item label="模板标识">
            <Input
              placeholder="搜索条件"
              value={searchInfo.templateID}
              onChange={(e) => setSearchInfo((prev: any) => ({ ...prev, templateID: e.target.value }))}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} onClick={onSubmit}>
                查询
              </Button>
              <Button icon={<ReloadOutlined />} onClick={onReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      {/* 表格区域 */}
      <Card className={styles.tableCard}>
        <div className={styles.toolbar}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={openDialog}>
              新增
            </Button>
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedRowKeys.length === 0}
              onClick={onDelete}
            >
              删除
            </Button>
          </Space>
        </div>
        <Table
          rowKey="ID"
          columns={columns}
          dataSource={tableData}
          loading={loading}
          scroll={{ x: 1200 }}
          rowSelection={{
            selectedRowKeys,
            onChange: (keys) => setSelectedRowKeys(keys as number[]),
          }}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (t) => `共 ${t} 条`,
            onChange: (p, ps) => {
              setPage(p);
              setPageSize(ps);
            },
          }}
        />
      </Card>

      {/* 新增/编辑抽屉 */}
      <Drawer
        title={dialogType === 'create' ? '添加' : '修改'}
        open={dialogVisible}
        onClose={closeDialog}
        width="60%"
        extra={
          <Space>
            <Button onClick={closeDialog}>取消</Button>
            <Button type="primary" onClick={enterDialog}>确定</Button>
          </Space>
        }
      >
        <Spin spinning={aiLoading} tip="小淼正在思考...">
          <Form layout="vertical">
            <Form.Item
              label={
                <Tooltip title="需要提前到db-list自行配置多数据库，如未配置需配置后重启服务方可使用">
                  业务库 <QuestionCircleOutlined />
                </Tooltip>
              }
            >
              <Select
                value={formData.dbName}
                placeholder="选择业务库"
                allowClear
                onChange={dbNameChange}
              >
                {dbList.map((db) => (
                  <Select.Option key={db.aliasName} value={db.aliasName} disabled={db.disable}>
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <span>{db.aliasName}</span>
                      <span style={{ color: '#8492a6', fontSize: 13 }}>{db.dbName}</span>
                    </div>
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="需用到的表">
              <Select
                mode="multiple"
                value={tables}
                placeholder="使用AI的情况下请选择"
                allowClear
                onChange={setTables}
              >
                {tableOptions.map((t: any) => (
                  <Select.Option key={t.tableName} value={t.tableName}>
                    {t.tableName}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="AI帮写">
              <div style={{ position: 'relative' }}>
                <TextArea
                  value={prompt}
                  onChange={(e) => setPrompt(e.target.value)}
                  rows={5}
                  placeholder="试试描述你要做的导出功能让AI帮你完成，在此之前请选择你需要导出的表所在的业务库，如不做选择，则默认使用kra库"
                />
                <Button
                  type="primary"
                  icon={<RobotOutlined />}
                  style={{ position: 'absolute', bottom: 8, right: 8 }}
                  onClick={autoExport}
                >
                  帮写
                </Button>
              </div>
            </Form.Item>

            <Form.Item label="表名称" required>
              <Space.Compact style={{ width: '100%' }}>
                <Select
                  value={formData.tableName}
                  placeholder="请选择表"
                  showSearch
                  style={{ flex: 1 }}
                  onChange={(val) => setFormData(prev => ({ ...prev, tableName: val }))}
                >
                  {tableOptions.map((t: any) => (
                    <Select.Option key={t.tableName} value={t.tableName}>
                      {t.tableName}
                    </Select.Option>
                  ))}
                </Select>
                <Button
                  type="primary"
                  icon={<RobotOutlined />}
                  disabled={!formData.tableName}
                  onClick={() => getColumnFunc(true)}
                >
                  自动补全
                </Button>
                <Button
                  type="primary"
                  disabled={!formData.tableName}
                  onClick={() => getColumnFunc(false)}
                >
                  自动生成模板
                </Button>
              </Space.Compact>
            </Form.Item>

            <Form.Item label="模板名称" required>
              <Input
                value={formData.name}
                placeholder="请输入模板名称"
                onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
              />
            </Form.Item>

            <Form.Item label="模板标识" required>
              <Input
                value={formData.templateID}
                placeholder="模板标识为前端组件需要挂在的标识属性"
                onChange={(e) => setFormData(prev => ({ ...prev, templateID: e.target.value }))}
              />
            </Form.Item>

            <Form.Item label="关联条件">
              {(formData.joinTemplate || []).map((join, index) => (
                <Row key={index} gutter={8} style={{ marginBottom: 8 }}>
                  <Col span={5}>
                    <Select
                      value={join.joins}
                      placeholder="请选择关联方式"
                      onChange={(val) => {
                        const newJoins = [...(formData.joinTemplate || [])];
                        newJoins[index].joins = val;
                        setFormData(prev => ({ ...prev, joinTemplate: newJoins }));
                      }}
                    >
                      <Select.Option value="LEFT JOIN">LEFT JOIN</Select.Option>
                      <Select.Option value="INNER JOIN">INNER JOIN</Select.Option>
                      <Select.Option value="RIGHT JOIN">RIGHT JOIN</Select.Option>
                    </Select>
                  </Col>
                  <Col span={6}>
                    <Input
                      value={join.table}
                      placeholder="请输入关联表"
                      onChange={(e) => {
                        const newJoins = [...(formData.joinTemplate || [])];
                        newJoins[index].table = e.target.value;
                        setFormData(prev => ({ ...prev, joinTemplate: newJoins }));
                      }}
                    />
                  </Col>
                  <Col span={9}>
                    <Input
                      value={join.on}
                      placeholder="关联条件 table1.a = table2.b"
                      onChange={(e) => {
                        const newJoins = [...(formData.joinTemplate || [])];
                        newJoins[index].on = e.target.value;
                        setFormData(prev => ({ ...prev, joinTemplate: newJoins }));
                      }}
                    />
                  </Col>
                  <Col span={4}>
                    <Button danger icon={<DeleteOutlined />} onClick={() => removeJoin(index)}>
                      删除
                    </Button>
                  </Col>
                </Row>
              ))}
              <div style={{ textAlign: 'right' }}>
                <Button type="primary" icon={<PlusOutlined />} onClick={addJoin}>
                  添加条件
                </Button>
              </div>
            </Form.Item>

            <Form.Item label="模板信息" required>
              <TextArea
                value={formData.templateInfo}
                rows={12}
                placeholder={templatePlaceholder}
                onChange={(e) => setFormData(prev => ({ ...prev, templateInfo: e.target.value }))}
              />
            </Form.Item>

            <Form.Item label="默认导出条数">
              <InputNumber
                value={formData.limit}
                min={0}
                precision={0}
                onChange={(val) => setFormData(prev => ({ ...prev, limit: val || 0 }))}
              />
            </Form.Item>

            <Form.Item label="默认排序条件">
              <Input
                value={formData.order}
                placeholder="例:id desc"
                onChange={(e) => setFormData(prev => ({ ...prev, order: e.target.value }))}
              />
            </Form.Item>

            <Form.Item label="导出条件">
              {(formData.conditions || []).map((cond, index) => (
                <Row key={index} gutter={8} style={{ marginBottom: 8 }}>
                  <Col span={6}>
                    <Input
                      value={cond.from}
                      placeholder="需要从查询条件取的json key"
                      onChange={(e) => {
                        const newConds = [...(formData.conditions || [])];
                        newConds[index].from = e.target.value;
                        setFormData(prev => ({ ...prev, conditions: newConds }));
                      }}
                    />
                  </Col>
                  <Col span={6}>
                    <Input
                      value={cond.column}
                      placeholder="表对应的column"
                      onChange={(e) => {
                        const newConds = [...(formData.conditions || [])];
                        newConds[index].column = e.target.value;
                        setFormData(prev => ({ ...prev, conditions: newConds }));
                      }}
                    />
                  </Col>
                  <Col span={6}>
                    <Select
                      value={cond.operator}
                      placeholder="请选择查询条件"
                      onChange={(val) => {
                        const newConds = [...(formData.conditions || [])];
                        newConds[index].operator = val;
                        setFormData(prev => ({ ...prev, conditions: newConds }));
                      }}
                    >
                      {typeSearchOptions.map(opt => (
                        <Select.Option key={opt.value} value={opt.value}>
                          {opt.label}
                        </Select.Option>
                      ))}
                    </Select>
                  </Col>
                  <Col span={6}>
                    <Button danger icon={<DeleteOutlined />} onClick={() => removeCondition(index)}>
                      删除
                    </Button>
                  </Col>
                </Row>
              ))}
              <div style={{ textAlign: 'right' }}>
                <Button type="primary" icon={<PlusOutlined />} onClick={addCondition}>
                  添加条件
                </Button>
              </div>
            </Form.Item>
          </Form>
        </Spin>
      </Drawer>

      {/* 代码和SQL预览抽屉 */}
      <Drawer
        title="模板与预览"
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        width="70%"
        extra={
          <Space>
            <Button onClick={() => setDrawerVisible(false)}>关闭</Button>
            {activeTab === 'sql' && (
              <Button type="primary" onClick={runPreview}>生成</Button>
            )}
          </Space>
        }
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab} type="card">
          <Tabs.TabPane tab="代码模板" key="code">
            <pre style={{
              background: '#1e1e1e',
              color: '#d4d4d4',
              padding: 16,
              borderRadius: 4,
              overflow: 'auto',
              minHeight: 400,
            }}>
              {webCode}
            </pre>
          </Tabs.TabPane>
          <Tabs.TabPane tab="SQL预览" key="sql">
            <Form layout="horizontal" labelCol={{ span: 4 }}>
              <Form.Item label="过滤已删除">
                <Switch
                  checked={previewForm.filterDeleted}
                  onChange={(val) => setPreviewForm((prev: any) => ({ ...prev, filterDeleted: val }))}
                />
              </Form.Item>
              <Form.Item label="默认排序">
                <Input
                  value={previewForm.order}
                  placeholder="例如: id desc"
                  onChange={(e) => setPreviewForm((prev: any) => ({ ...prev, order: e.target.value }))}
                />
              </Form.Item>
              <Form.Item label="限制条数">
                <InputNumber
                  value={previewForm.limit}
                  min={0}
                  onChange={(val) => setPreviewForm((prev: any) => ({ ...prev, limit: val }))}
                />
              </Form.Item>
              <Form.Item label="偏移量">
                <InputNumber
                  value={previewForm.offset}
                  min={0}
                  onChange={(val) => setPreviewForm((prev: any) => ({ ...prev, offset: val }))}
                />
              </Form.Item>
              
              <Divider>查询条件</Divider>
              {previewConditions.length === 0 ? (
                <div style={{ color: '#999' }}>该模板暂无条件</div>
              ) : (
                previewConditions.map((cond, idx) => (
                  <Form.Item key={idx} label={`${cond.column} ${cond.operator}`}>
                    {cond.operator === 'BETWEEN' ? (
                      <Space>
                        <Input
                          placeholder={`开始值: start${cond.from}`}
                          onChange={(e) => setPreviewForm((prev: any) => ({
                            ...prev,
                            [`start${cond.from}`]: e.target.value,
                          }))}
                        />
                        <Input
                          placeholder={`结束值: end${cond.from}`}
                          onChange={(e) => setPreviewForm((prev: any) => ({
                            ...prev,
                            [`end${cond.from}`]: e.target.value,
                          }))}
                        />
                      </Space>
                    ) : (
                      <Input
                        placeholder={`变量: ${cond.from}`}
                        onChange={(e) => setPreviewForm((prev: any) => ({
                          ...prev,
                          [cond.from]: e.target.value,
                        }))}
                      />
                    )}
                  </Form.Item>
                ))
              )}
            </Form>
            <pre style={{
              background: '#1e1e1e',
              color: '#d4d4d4',
              padding: 16,
              borderRadius: 4,
              overflow: 'auto',
              minHeight: 300,
              marginTop: 16,
            }}>
              {previewSQLCode || '点击"生成"按钮预览SQL'}
            </pre>
          </Tabs.TabPane>
        </Tabs>
      </Drawer>
    </PageContainer>
  );
};

export default ExportTemplatePage;
