import React, { useState, useEffect, useRef } from 'react';
import {
  Layout,
  Button,
  Input,
  Upload,
  message,
  Card,
  Modal,
  Table,
  Space,
  Pagination,
} from 'antd';
import {
  PlusOutlined,
  VideoCameraOutlined,
  PictureOutlined,
  LoadingOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { uploadVideo, uploadImage, generateReplication, getReplicationList,getone, getReplicationDetail } from '../api';

const { Header, Content } = Layout;
const { TextArea } = Input;

const GenerateConver: React.FC = () => {
  const navigate = useNavigate();

  const [tableData, setTableData] = useState<any[]>(
    []
  );

  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);

  // 卡片列表专用状态
  const [cardData, setCardData] = useState<any[]>([]);
  const [cardCurrentPage, setCardCurrentPage] = useState(1);
  const [cardPageSize, setCardPageSize] = useState(8);
  const [cardTotal, setCardTotal] = useState(0);

  // 表单数据
  const [originalProductName, setOriginalProductName] = useState<string>('');
  const [ownProductName, setOwnProductName] = useState<string>('');
  const [productSellingPoints, setProductSellingPoints] = useState<string>('');

  // 文件状态
  const [videoFile, setVideoFile] = useState<File | null>(null);
  const [videoUrl, setVideoUrl] = useState<string>('');
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imageUrl, setImageUrl] = useState<string>('');
  const [videoUploading, setVideoUploading] = useState(false);
  const [imageUploading, setImageUploading] = useState(false);

  // 弹窗状态
  const [isModalOpen, setIsModalOpen] = useState(false);

  // 卡片列表轮询定时器（使用 ref 避免闭包问题）
  const cardPollingTimer = useRef<any>(null);
  
  // 表格轮询定时器（使用 ref 避免闭包问题）
  const tablePollingTimer = useRef<any>(null);

  // 获取卡片列表数据（独立于表格）
  const fetchCardList = (page: number, size: number, isPolling = false) => {
    getReplicationList(page, size).then((res: any) => {
      if (res.items) {
        if (isPolling) {
          // 轮询时：增量更新，只更新状态发生变化的项目
          setCardData(prevData => {
            return prevData.map(existingItem => {
              const newItem = res.items.find((item: any) => item.id === existingItem.id);
              if (newItem && newItem.status !== existingItem.status) {
                return newItem;
              }
              return existingItem;
            });
          });
        } else {
          // 首次加载或分页变化时：直接替换
          setCardData(res.items);
        }
        
        // 检查是否有 processing 状态
        const hasProcessing = res.items.some(item => item.status === 'processing');
        
        
        // 如果有 processing 状态且轮询未启动，启动轮询
        if (hasProcessing && !cardPollingTimer.current) {
          cardPollingTimer.current = setInterval(() => {
            fetchCardList(cardCurrentPage, cardPageSize, true);
          }, 5000);
        }
        // 如果没有 processing 状态且轮询正在运行，停止轮询
        else if (!hasProcessing && cardPollingTimer.current) {
          clearInterval(cardPollingTimer.current);
          cardPollingTimer.current = null;
        } else {
        }
      }
      if (res.total !== undefined) {
        setCardTotal(res.total);
      }
    }).catch((error: any) => {
    });
  };

  // 卡片列表分页变化处理
  const handleCardPageChange = (page: number) => {
    setCardCurrentPage(page);
    fetchCardList(page, cardPageSize);
  };

  // 获取列表数据的函数
  const fetchList = (page: number, size: number, isPolling = false) => {
    getReplicationList(page, size).then((res: any) => {
      if (res.items) {
        if (isPolling) {
          // 轮询时：增量更新，只更新状态发生变化的项目
          setTableData(prevData => {
            return prevData.map(existingItem => {
              const newItem = res.items.find((item: any) => item.id === existingItem.id);
              if (newItem && newItem.status !== existingItem.status) {
                return newItem;
              }
              return existingItem;
            });
          });
        } else {
          // 首次加载或分页变化时：直接替换
          setTableData(res.items);
        }
        
        // 检查是否有 processing 状态
        const hasProcessing = res.items.some(item => item.status === 'processing');
        
        // 如果有 processing 状态且轮询未启动，启动轮询
        if (hasProcessing && !tablePollingTimer.current) {
          tablePollingTimer.current = setInterval(() => {
            fetchList(currentPage, pageSize, true);
          }, 5000);
        }
        // 如果没有 processing 状态且轮询正在运行，停止轮询
        else if (!hasProcessing && tablePollingTimer.current) {
          clearInterval(tablePollingTimer.current);
          tablePollingTimer.current = null;
        }
      }
      if (res.total !== undefined) {
        setTotal(res.total);
      }
    }).catch((error: any) => {
    });
  };

  // 组件挂载时获取复刻列表
  useEffect(() => {
    fetchList(currentPage, pageSize);
    fetchCardList(cardCurrentPage, cardPageSize);

    // 组件卸载时清理定时器
    return () => {
      if (cardPollingTimer.current) {
        clearInterval(cardPollingTimer.current);
        cardPollingTimer.current = null;
      }
      if (tablePollingTimer.current) {
        clearInterval(tablePollingTimer.current);
        tablePollingTimer.current = null;
      }
    };
  }, []);

  // 分页变化处理
  const handlePageChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
    fetchList(page, size);
  };

  // 文件上传前校验
  const beforeVideoUpload = async (file: File): Promise<boolean> => {
    const isVideo = file.type.startsWith('video/');
    if (!isVideo) {
      message.error('只能上传视频文件');
      return false;
    }
    const isLt50M = file.size / 1024 / 1024 < 50;
    if (!isLt50M) {
      message.error('视频大小不能超过50MB');
      return false;
    }

    // 检查视频时长
    const video = document.createElement('video');
    video.preload = 'metadata';

    return new Promise((resolve) => {
      video.onloadedmetadata = async () => {
        if (video.duration < 2) {
          message.error('视频时长不能少于2秒');
          URL.revokeObjectURL(video.src);
          resolve(false);
          return;
        }
        if (video.duration > 15) {
          message.error('视频时长不能超过15秒');
          URL.revokeObjectURL(video.src);
          resolve(false);
          return;
        }

        // 调用上传接口
        setVideoUploading(true);
        try {
          const res = await uploadVideo(file);
          setVideoFile(file);
          setVideoUrl(`${import.meta.env.VITE_API_BASE || 'http://localhost:8000'}${res.url}`);
          message.success('视频上传成功');
          resolve(false);
        } catch (error) {
          // 获取接口返回的错误信息
          let errorMsg = '';
          if (error instanceof Error) {
            try {
              const errorData = JSON.parse(error.message);
              errorMsg = errorData.detail || error.message;
            } catch {
              errorMsg = error.message;
            }
          }
          message.error(errorMsg || '视频上传失败');
          resolve(false);
        } finally {
          setVideoUploading(false);
          URL.revokeObjectURL(video.src);
        }
      };
      video.onerror = () => {
        message.error('视频文件无效');
        URL.revokeObjectURL(video.src);
        resolve(false);
      };
      video.src = URL.createObjectURL(file);
    });
  };

  const beforeImageUpload = async (file: File): Promise<boolean> => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件');
      return false;
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('图片大小不能超过10MB');
      return false;
    }

    // 检查图片比例
    const img = new Image();

    return new Promise((resolve) => {
      img.onload = async () => {
        const ratio = img.width / img.height;
        const isRatioValid = Math.abs(ratio - 0.75) < 0.1 || Math.abs(ratio - 0.5625) < 0.1;
        // if (!isRatioValid) {
        //   message.warning('建议使用3:4或9:16比例的图片以获得最佳效果');
        // }

        // 调用上传接口
        setImageUploading(true);
        try {
          const res = await uploadImage(file);
          setImageFile(file);
          setImageUrl(`${import.meta.env.VITE_API_BASE || 'http://localhost:8000'}${res.url}`);
          message.success('图片上传成功');
          resolve(false);
        } catch (error) {
          // 获取接口返回的错误信息
          let errorMsg = '';
          if (error instanceof Error) {
            try {
              const errorData = JSON.parse(error.message);
              errorMsg = errorData.detail || error.message;
            } catch {
              errorMsg = error.message;
            }
          }
          message.error(errorMsg || '图片上传失败');
          resolve(false);
        } finally {
          setImageUploading(false);
          URL.revokeObjectURL(img.src);
        }
      };
      img.onerror = () => {
        message.error('图片文件无效');
        URL.revokeObjectURL(img.src);
        resolve(false);
      };
      img.src = URL.createObjectURL(file);
    });
  };

  // 删除视频
  const handleRemoveVideo = () => {
    if (videoUrl) {
      URL.revokeObjectURL(videoUrl);
    }
    setVideoFile(null);
    setVideoUrl('');
  };

  // 删除图片
  const handleRemoveImage = () => {
    if (imageUrl) {
      URL.revokeObjectURL(imageUrl);
    }
    setImageFile(null);
    setImageUrl('');
  };

  // 处理生成
  const handleGenerate = () => {
    if (!videoUrl) {
      message.warning('请上传复刻视频');
      return;
    }
    if (!imageUrl) {
      message.warning('请上传产品图片');
      return;
    }
    if (!originalProductName.trim()) {
      message.warning('请输入原视频产品名称');
      return;
    }
    if (!ownProductName.trim()) {
      message.warning('请输入自有产品名称');
      return;
    }
    if (!productSellingPoints.trim()) {
      message.warning('请输入产品卖点');
      return;
    }
    // message.success('正在生成爆款开头复刻视频...');
    // console.log('生成参数:', {
    //   videoUrl,
    //   imageUrl,
    //   originalProductName,
    //   ownProductName,
    //   productSellingPoints,
    // });
    let params = {
      material_video_url: videoUrl,
      material_image_url: imageUrl,
      source_project_name: originalProductName,
      target_project_name: ownProductName,
      core_content_point: productSellingPoints,
      idempotency_key: Date.now().toString(),
    }

    // 在这里调用生成视频的API，并传递上述参数
    generateReplication(params).then((res) => {


      let projectId = '';
      let childId = '';
      // console.log('生成视频成功:', res);
      message.success('任务开始');

      // 清空上传的媒体和文本
      setVideoUrl('');
      setImageUrl('');
      setOriginalProductName('');
      setOwnProductName('');
      setProductSellingPoints('');
      
      fetchCardList(1,8);

      // 获取第一个的id直接进行下一步
      getReplicationList(1,20).then((res: any) => {
        if (res.items) {
          setTableData(res.items);
          // childId = res.items[0].child_id;
          getReplicationDetail(res.items[0].id).then((res: any) => {
            projectId = res.id;
            childId = res.steps[0].id;
            getone(projectId, childId).then((res: any) => {
            })
          }).catch((error: any) => {
          });
        }
      }).catch((error: any) => {
      });
      




    }).catch((error) => {
      message.error('视频开头复刻失败');
    });
  };

  return (
    <div className="replication-container" style={{ overflow: 'auto', height: '94vh', display: 'flex', justifyContent: 'space-between', gap: '2%' }}>

      <div className="replication-preview" style={{ width: '70%', height: '100%', background: '#fff', display: 'flex', flexDirection: 'column', borderRadius: 15, overflow: 'hidden' }}>



        {/* 顶部标题栏 */}
        <Header
          style={{
            background: '#fff',
            padding: '0 24px',
            borderBottom: '1px solid #e8e8e8',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <h2 style={{ margin: 0, fontSize: 16, fontWeight: 500, color: '#333' }}>
            爆款开头复刻
          </h2>
          <Button
            type="primary"
            ghost
            style={{ borderRadius: 6, padding: '4px 12px', fontSize: 12 }}
            onClick={() => setIsModalOpen(true)}
          >
            创作记录
          </Button>
        </Header>

        {/* 左侧预览区域 */}
        <div style={{ flex: 1, background: '#f5f5f5', borderRight: '1px solid #e8e8e8', overflow: 'hidden' }}>
          {cardData.length > 0 ? (
            <div style={{ height: '100%', padding: '20px', overflowY: 'auto' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
                <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: '#1f2937' }}>历史生成作品</h2>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 16 }}>
                {cardData.map((item) => (
                  <div
                    key={item.id}
                    style={{
                      background: '#fff',
                      borderRadius: 12,
                      overflow: 'hidden',
                      boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                      cursor: 'pointer',
                      transition: 'transform 0.2s, box-shadow 0.2s',
                    }}
                    onClick={() => navigate(`/initial/${item.id}/initialinfo`)}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.transform = 'translateY(-4px)';
                      e.currentTarget.style.boxShadow = '0 8px 24px rgba(0,0,0,0.12)';
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.transform = 'translateY(0)';
                      e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.06)';
                    }}
                  >
                    <div style={{ position: 'relative', aspectRatio: '1/1', background: '#f8fafc' }}>
                      {item.finalVideoUrl ? (

                        
                        
                        <img
                          src={`${import.meta.env.VITE_API_BASE || "http://localhost:8000"}${item.finalVideoCoverUrl}`}
                          alt={item.targetProjectName}
                          style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                        />
                      ) : (
                        <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          <div style={{ width: 60, height: 60, borderRadius: '50%', background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                            <VideoCameraOutlined style={{ fontSize: 24, color: '#fff' }} />
                          </div>
                        </div>
                      )}
                      <div style={{ position: 'absolute', bottom: 8, right: 8, padding: '4px 12px', background: 'rgba(0,0,0,0.6)', borderRadius: 12, fontSize: 10, color: '#fff' }}>
                        {(() => {
                          const status = item.status;
                          const currentStepCode = item.current_step_code || item.currentStepCode;
                          
                          if (currentStepCode === 'image_prompt_optimize') {
                            switch (status) {
                              case 'waiting_user':
                                return '等待融合图生成';
                              case 'processing':
                                return '图片提示词生成中';
                              case 'completed':
                                return '图片提示词生成成功';
                              case 'failed':
                                return '图片提示词生成失败';
                              default:
                                return status || '待处理';
                            }
                          } else if (currentStepCode === 'image_generate') {
                            switch (status) {
                              case 'waiting_user':
                                return '等待生成视频提示词';
                              case 'processing':
                                return '融合图生成中';
                              case 'completed':
                                return '融合图生成成功';
                              case 'failed':
                                return '融合图生成失败';
                              default:
                                return status || '待处理';
                            }
                          } else if (currentStepCode === 'video_prompt_optimize') {
                            switch (status) {
                              case 'waiting_user':
                                return '等待最终视频生成';
                              case 'processing':
                                return '视频提示词生成中';
                              case 'completed':
                                return '视频提示词生成成功';
                              case 'failed':
                                return '视频提示词生成失败';
                              default:
                                return status || '待处理';
                            }
                          } else if (currentStepCode === 'video_generate') {
                            switch (status) {
                              case 'waiting_user':
                                return '';
                              case 'processing':
                                return '最终视频生成中';
                              case 'completed':
                                return '最终视频生成成功';
                              case 'failed':
                                return '最终视频生成失败';
                              default:
                                return status || '待处理';
                            }
                          } else if (currentStepCode === 'material_input') {
                            switch (status) {
                              case 'waiting_user':
                                return '等待生成图片提示词';
                              case 'processing':
                                return '素材处理中';
                              case 'completed':
                                return '素材上传成功';
                              case 'failed':
                                return '素材上传失败';
                              default:
                                return status || '待处理';
                            }
                          } else {
                            const statusMap: Record<string, string> = {
                              'pending': '子任务待处理',
                              'waiting_user': '等待用户确认或触发',
                              'processing': '子任务处理中',
                              'completed': '子任务完成',
                              'failed': '子任务失败',
                              'cancelled': '子任务取消',
                            };
                            return statusMap[status] || status || '待处理';
                          }
                        })()}
                      </div>
                    </div>
                    <div style={{ padding: 12 }}>
                      <h4 style={{ margin: 0, fontSize: 13, fontWeight: 500, color: '#1f2937', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {item.targetProjectName || '未命名作品'}
                      </h4>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 4 }}>
                        <p style={{ margin: 0, fontSize: 11, color: '#9ca3af' }}>
                          {item.createdAt ? new Date(item.createdAt).toLocaleDateString('zh-CN') : ''}
                        </p>
                        {(() => {
                          const status = item.status;
                          if (status === 'waiting_user') {
                            return <span style={{ fontSize: 11, color: '#f59e0b' }}>等待下一步</span>;
                          } else if (status === 'processing') {
                            return (
                              <span style={{ fontSize: 11, color: '#6366f1', display: 'flex', alignItems: 'center' }}>
                                <span>进行中</span>
                                <span style={{ animation: 'dots 1s infinite' }}>...</span>
                                <style>{`
                                  @keyframes dots {
                                    0%, 20% { opacity: 0; }
                                    50% { opacity: 1; }
                                    100% { opacity: 0; }
                                  }
                                `}</style>
                              </span>
                            );
                          } else if (status === 'failed') {
                            return <span style={{ fontSize: 11, color: '#ef4444' }}>失败</span>;
                          } else if (status === 'completed' && item.finalVideoUrl) {
                            return <span style={{ fontSize: 11, color: '#10b981' }}>任务完成</span>;
                          }
                          return null;
                        })()}
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              <div style={{ paddingTop: 20, paddingBottom: 20, display: 'flex', justifyContent: 'center' }}>
                <Pagination
                  current={cardCurrentPage}
                  pageSize={cardPageSize}
                  total={cardTotal}
                  onChange={handleCardPageChange}
                  showSizeChanger={false}
                  showQuickJumper={false}
                  showTotal={(total) => `共 ${total} 条`}
                  itemRender={(current, type, originalElement) => {
                    if (type === 'prev') {
                      return (
                        <button
                          style={{
                            minWidth: 32,
                            height: 32,
                            border: '1px solid #e5e7eb',
                            borderRadius: 6,
                            background: cardCurrentPage === 1 ? '#f9fafb' : '#fff',
                            cursor: cardCurrentPage === 1 ? 'not-allowed' : 'pointer',
                            color: cardCurrentPage === 1 ? '#d1d5db' : '#6b7280',
                            fontSize: 14,
                          }}
                          disabled={cardCurrentPage === 1}
                        >
                          ‹
                        </button>
                      );
                    }
                    if (type === 'next') {
                      return (
                        <button
                          style={{
                            minWidth: 32,
                            height: 32,
                            border: '1px solid #e5e7eb',
                            borderRadius: 6,
                            background: cardCurrentPage >= Math.ceil(cardTotal / cardPageSize) ? '#f9fafb' : '#fff',
                            cursor: cardCurrentPage >= Math.ceil(cardTotal / cardPageSize) ? 'not-allowed' : 'pointer',
                            color: cardCurrentPage >= Math.ceil(cardTotal / cardPageSize) ? '#d1d5db' : '#6b7280',
                            fontSize: 14,
                          }}
                          disabled={cardCurrentPage >= Math.ceil(cardTotal / cardPageSize)}
                        >
                          ›
                        </button>
                      );
                    }
                    if (type === 'page') {
                      return (
                        <button
                          style={{
                            minWidth: 32,
                            height: 32,
                            border: 'none',
                            borderRadius: 6,
                            background: current === cardCurrentPage ? '#6366f1' : '#fff',
                            color: current === cardCurrentPage ? '#fff' : '#374151',
                            fontWeight: current === cardCurrentPage ? 500 : 400,
                            cursor: 'pointer',
                            fontSize: 14,
                          }}
                        >
                          {current}
                        </button>
                      );
                    }
                    return originalElement;
                  }}
                />
              </div>
            </div>
          ) : (
            <div
              style={{
                width: '100%',
                height: '100%',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <div
                style={{
                  width: 100,
                  height: 100,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginBottom: 20,
                  position: 'relative',
                }}
              >
                <div
                  style={{
                    width: 55,
                    height: 65,
                    background: 'linear-gradient(135deg, #6366f1 0%, #a78bfa 100%)',
                    borderRadius: 10,
                    position: 'absolute',
                    bottom: 0,
                    right: 5,
                  }}
                />
                <div
                  style={{
                    width: 45,
                    height: 52,
                    border: '2px solid #c7d2fe',
                    borderRadius: 8,
                    position: 'absolute',
                    top: 0,
                    left: 5,
                  }}
                />
              </div>
              <h3 style={{ margin: 0, fontSize: 14, fontWeight: 500, color: '#333', marginBottom: 8 }}>
                暂无生成内容
              </h3>
              <p style={{ margin: 0, fontSize: 12, color: '#999', textAlign: 'center', padding: '0 20px' }}>
                请完善素材与卖点，生成专属爆款开头复刻视频
              </p>
            </div>
          )}
        </div>
      </div>


      <div className="replication-form" style={{ width: '28%', height: '100%', background: '#fff', borderRadius: 15, overflow: 'hidden' }}>
        {/* 右侧表单区域 */}
        <div className="replication-form-content" style={{ width: '100%', height: '100%', background: '#fff', padding: 20, overflowY: 'auto' }}>
          {/* 上传视频 */}
          <div style={{ marginBottom: 16 }}>
            <p style={{ margin: 0, fontSize: 13, fontWeight: 500, color: '#333', marginBottom: 8 }}>
              上传复刻视频
            </p>
            {videoUrl ? (
              <div style={{ position: 'relative' }}>
                <video
                  src={videoUrl}
                  controls
                  style={{ width: '100%', borderRadius: 8, maxHeight: 200 }}
                />
                <button
                  onClick={handleRemoveVideo}
                  style={{
                    position: 'absolute',
                    top: 8,
                    right: 8,
                    width: 24,
                    height: 24,
                    border: 'none',
                    background: '#ff4d4f',
                    borderRadius: '50%',
                    cursor: 'pointer',
                    color: '#fff',
                    fontSize: 14,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 10,
                  }}
                >
                  ×
                </button>
                <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <VideoCameraOutlined style={{ color: '#f59e0b', fontSize: 14 }} />
                  <span style={{ fontSize: 12, color: '#666' }}>
                    {videoFile?.name}
                  </span>
                  <span style={{ fontSize: 11, color: '#999' }}>
                    ({(videoFile?.size ? (videoFile.size / 1024 / 1024).toFixed(2) : 0)}MB)
                  </span>
                </div>
              </div>
            ) : (
              <Upload
                beforeUpload={beforeVideoUpload}
                showUploadList={false}
                accept="video/mp4,video/quicktime,.mp4,.mov"
              >
                <div
                  style={{
                    border: '1px dashed #d9d9d9',
                    borderRadius: 8,
                    padding: 20,
                    textAlign: 'center',
                    cursor: 'pointer',
                    transition: 'all 0.2s',
                  }}
                  onMouseEnter={(e) => {
                    (e.currentTarget as HTMLElement).style.borderColor = '#6366f1';
                  }}
                  onMouseLeave={(e) => {
                    (e.currentTarget as HTMLElement).style.borderColor = '#d9d9d9';
                  }}
                >
                  {videoUploading ? (
                    <div>
                      <LoadingOutlined style={{ fontSize: 18, color: '#6366f1', marginBottom: 6 }} />
                      <p style={{ margin: 0, fontSize: 12, color: '#666' }}>
                        上传中...
                      </p>
                      <p style={{ margin: 0, fontSize: 11, color: '#bbb', marginTop: 4 }}>
                        支持的文件类型：MP4、MOV|视频最大时长：15 秒 | 最大大小：50M
                      </p>
                    </div>
                  ) : (
                    <>
                      <VideoCameraOutlined style={{ fontSize: 18, color: '#999', marginBottom: 6 }} />
                      <p style={{ margin: 0, fontSize: 12, color: '#666' }}>
                        您可以通过点击或拖拽上传视频
                      </p>
                      <p style={{ margin: 0, fontSize: 11, color: '#bbb', marginTop: 4 }}>
                        支持的文件类型：MP4、MOV|视频最大时长：15 秒 | 最大大小：50M
                      </p>
                    </>
                  )}
                </div>
              </Upload>
            )}
          </div>

          {/* 上传产品图片 */}
          <div style={{ marginBottom: 16 }}>
            <p style={{ margin: 0, fontSize: 13, fontWeight: 500, color: '#333', marginBottom: 8 }}>
              上传产品图片
            </p>
            {imageUrl ? (
              <div style={{ position: 'relative' }}>
                <img
                  src={imageUrl}
                  alt="产品图片"
                  style={{ width: '100%', borderRadius: 8, maxHeight: 200, objectFit: 'contain' }}
                />
                <button
                  onClick={handleRemoveImage}
                  style={{
                    position: 'absolute',
                    top: 8,
                    right: 8,
                    width: 24,
                    height: 24,
                    border: 'none',
                    background: '#ff4d4f',
                    borderRadius: '50%',
                    cursor: 'pointer',
                    color: '#fff',
                    fontSize: 14,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 10,
                  }}
                >
                  ×
                </button>
                <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <PictureOutlined style={{ color: '#3b82f6', fontSize: 14 }} />
                  <span style={{ fontSize: 12, color: '#666' }}>
                    {imageFile?.name}
                  </span>
                  <span style={{ fontSize: 11, color: '#999' }}>
                    ({(imageFile?.size ? (imageFile.size / 1024 / 1024).toFixed(2) : 0)}MB)
                  </span>
                </div>
              </div>
            ) : (
              <Upload
                beforeUpload={beforeImageUpload}
                showUploadList={false}
                accept="image/jpeg,image/jpg,image/png,.jpg,.jpeg,.png"
              >
                <div
                  style={{
                    border: '1px dashed #d9d9d9',
                    borderRadius: 8,
                    padding: 16,
                    textAlign: 'center',
                    cursor: 'pointer',
                    transition: 'all 0.2s',
                  }}
                  onMouseEnter={(e) => {
                    (e.currentTarget as HTMLElement).style.borderColor = '#6366f1';
                  }}
                  onMouseLeave={(e) => {
                    (e.currentTarget as HTMLElement).style.borderColor = '#d9d9d9';
                  }}
                >
                  {imageUploading ? (
                    <div>
                      <LoadingOutlined style={{ fontSize: 14, color: '#6366f1', marginBottom: 6 }} />
                      <p style={{ margin: 0, fontSize: 12, color: '#666' }}>
                        上传中...
                      </p>
                      <p style={{ margin: 0, fontSize: 11, color: '#bbb', marginTop: 4 }}>
                        支持 JPG,JPEG,PNG 格式，图片比例为 3:4 或 9:16 效果最佳
                      </p>
                    </div>
                  ) : (
                    <>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
                        <PictureOutlined style={{ fontSize: 14, color: '#999' }} />
                        <span style={{ fontSize: 12, color: '#666' }}>+ 点击上传</span>
                      </div>
                      <p style={{ margin: 0, fontSize: 11, color: '#bbb', marginTop: 4 }}>
                        支持 JPG,JPEG,PNG 格式，图片比例为 3:4 或 9:16 效果最佳
                      </p>
                    </>
                  )}
                </div>
              </Upload>
            )}
          </div>

          {/* 原视频产品名称 */}
          <div style={{ marginBottom: 12 }}>
            <p style={{ margin: 0, fontSize: 12, color: '#666', marginBottom: 6 }}>
              原视频产品名称
            </p>
            <Input
              value={originalProductName}
              onChange={(e) => setOriginalProductName(e.target.value)}
              placeholder="请输入原视频产品名称"
              style={{ borderRadius: 6, height: 32, fontSize: 12 }}
              maxLength={10}
              suffix={<span style={{ color: '#ccc', fontSize: 11 }}>{originalProductName.length}/10</span>}
            />
          </div>

          {/* 自有产品名称 */}
          <div style={{ marginBottom: 12 }}>
            <p style={{ margin: 0, fontSize: 12, color: '#666', marginBottom: 6 }}>
              自有产品名称
            </p>
            <Input
              value={ownProductName}
              onChange={(e) => setOwnProductName(e.target.value)}
              placeholder="请输入自有产品名称"
              style={{ borderRadius: 6, height: 32, fontSize: 12 }}
              maxLength={10}
              suffix={<span style={{ color: '#ccc', fontSize: 11 }}>{ownProductName.length}/10</span>}
            />
          </div>

          {/* 产品卖点 */}
          <div style={{ marginBottom: 16 }}>
            <p style={{ margin: 0, fontSize: 12, color: '#666', marginBottom: 6 }}>
              产品卖点
            </p>
            <div style={{ position: 'relative' }}>
              <TextArea
                value={productSellingPoints}
                onChange={(e) => setProductSellingPoints(e.target.value)}
                placeholder="请输入产品卖点"
                style={{ borderRadius: 6, fontSize: 12 }}
                rows={2}
                maxLength={30}
              />
              <span style={{ position: 'absolute', right: 8, bottom: 6, color: '#ccc', fontSize: 11 }}>
                {productSellingPoints.length}/30
              </span>
            </div>
          </div>

          {/* 立即生成按钮 */}
          <Button
            type="primary"
            block
            size="large"
            onClick={handleGenerate}
            style={{
              borderRadius: 8,
              height: 40,
              fontWeight: 500,
              background: 'linear-gradient(135deg, #6366f1 0%, #a78bfa 100%)',
              border: 'none',
              fontSize: 14,
            }}
          >
            立即生成+
          </Button>
        </div>
      </div>

      {/* 创作记录弹窗 */}
      <Modal
        title="创作记录"
        open={isModalOpen}
        onCancel={() => setIsModalOpen(false)}
        width={800}
        footer={null}
        style={{ borderRadius: 12 }}
        styles={{ body: { height: 550, display: 'flex', flexDirection: 'column' } }}
      >
        {/* 搜索区域 */}
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16, flexShrink: 0 }}>
          <Input
            placeholder="搜索产品名称"
            style={{ width: 200, borderRadius: 6, marginRight: 8 }}
          />
          <Button type="primary" style={{ borderRadius: 6 }}>
            搜索
          </Button>
        </div>

        {/* 表格容器 */}
        <div style={{ flex: 1, overflow: 'auto' }}>
          <Table
            columns={[
              {
                title: '产品名称',
                dataIndex: 'targetProjectName',
                key: 'targetProjectName',
                align: 'center',
              },
              {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                align: 'center',
                render: (text: string, record: any) => {
                  const status = text;
                  const currentStepCode = record.current_step_code || record.currentStepCode;
                  
                  const getStatusText = () => {
                    if (currentStepCode === 'image_prompt_optimize') {
                      switch (status) {
                        case 'waiting_user':
                          return '等待融合图生成';
                        case 'processing':
                          return '图片提示词生成中';
                        case 'completed':
                          return '图片提示词生成成功';
                        case 'failed':
                          return '图片提示词生成失败';
                        default:
                          return status || '-';
                      }
                    } else if (currentStepCode === 'image_generate') {
                      switch (status) {
                        case 'waiting_user':
                          return '等待生成视频提示词';
                        case 'processing':
                          return '融合图生成中';
                        case 'completed':
                          return '融合图生成成功';
                        case 'failed':
                          return '融合图生成失败';
                        default:
                          return status || '-';
                      }
                    } else if (currentStepCode === 'video_prompt_optimize') {
                      switch (status) {
                        case 'waiting_user':
                          return '等待最终视频生成';
                        case 'processing':
                          return '视频提示词生成中';
                        case 'completed':
                          return '视频提示词生成成功';
                        case 'failed':
                          return '视频提示词生成失败';
                        default:
                          return status || '-';
                      }
                    } else if (currentStepCode === 'video_generate') {
                      switch (status) {
                        case 'waiting_user':
                          return '';
                        case 'processing':
                          return '最终视频生成中';
                        case 'completed':
                          return '最终视频生成成功';
                        case 'failed':
                          return '最终视频生成失败';
                        default:
                          return status || '-';
                      }
                    } else if (currentStepCode === 'material_input') {
                      switch (status) {
                        case 'waiting_user':
                          return '等待生成图片提示词';
                        case 'processing':
                          return '素材处理中';
                        case 'completed':
                          return '素材上传成功';
                        case 'failed':
                          return '素材上传失败';
                        default:
                          return status || '-';
                      }
                    } else {
                      const statusMap: Record<string, string> = {
                        'pending': '子任务待处理',
                        'waiting_user': '等待用户确认或触发',
                        'processing': '子任务处理中',
                        'completed': '子任务完成',
                        'failed': '子任务失败',
                        'cancelled': '子任务取消',
                      };
                      return statusMap[status] || status || '-';
                    }
                  };
                  
                  return getStatusText();
                },
              },
              {
                title: '创建时间',
                dataIndex: 'createdAt',
                key: 'createdAt',
                align: 'center',

                render: (text: string) => {
                  if (!text) return '-';
                  const date = new Date(text);
                  const year = date.getFullYear();
                  const month = String(date.getMonth() + 1).padStart(2, '0');
                  const day = String(date.getDate()).padStart(2, '0');
                  const hours = String(date.getHours()).padStart(2, '0');
                  const minutes = String(date.getMinutes()).padStart(2, '0');
                  const seconds = String(date.getSeconds()).padStart(2, '0');
                  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                },
              },
              {
                title: '操作',
                key: 'action',
                align: 'center',

                render: (_, record) => (
                  <button
                    onClick={() => navigate(`/initial/${record.id}/initialinfo`)}
                    style={{ color: '#6366f1', textDecoration: 'none', fontSize: 12, border: 'none', background: 'none', cursor: 'pointer' }}
                  >
                    查看详情
                  </button>
                ),
              },
            ]}
            dataSource={tableData}
            rowKey="id"
            pagination={{
              current: currentPage,
              pageSize: pageSize,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
              onChange: handlePageChange,
            }}
            style={{ fontSize: 13 }}
            scroll={{ y: 350 }}
          />
        </div>
      </Modal>

    </div>
  );
};

export default GenerateConver;