import React, { useState, useEffect, useMemo } from 'react';
import { CheckCircle, Eye, ShoppingCart, HelpCircle, PlayCircle, Clock, AlertCircle, Rocket } from 'lucide-react';
import { LineChart, Line, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { Card, Button, Table, Tag, message, Modal, Form as AntdForm, Input, Select, DatePicker, InputNumber, Switch, Radio, Checkbox, Cascader, Upload, Alert } from 'antd';
import { UploadOutlined, LockOutlined, CheckCircleOutlined } from '@ant-design/icons';
import { executorHomeApi, ExecutorNodeCountVO, ExecutorNodeVO, ExecutorDayCompletedVO } from '../api/executorHome';
import { myTaskApi, MyTaskNodeDetailVO } from '../api/mytask';
import { formatDateWithFormat, dateFormatter } from '../utils/formatTime';
import { toast } from 'sonner';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import dayjs, { Dayjs } from 'dayjs';
import { setConfAndFields2, FormCreateData } from '../utils/formCreate';
import { dictDataApi, DictDataVO } from '../api/DictData';
// @ts-ignore
import urgecy1Icon from '../assets/urgecy1.png';
// @ts-ignore
import urgecy2Icon from '../assets/urgecy2.png';
// @ts-ignore
import urgecy3Icon from '../assets/urgecy3.png';

// 辅助函数：安全地将值转换为 dayjs 对象
const safeToDayjs = (value: any): dayjs.Dayjs | null => {
  if (!value && value !== 0) {
    return null;
  }
  
  // 如果是数字（时间戳）
  if (typeof value === 'number') {
    let timestamp = value;
    if (timestamp > 0 && timestamp < 10000000000) {
      timestamp = timestamp * 1000;
    }
    const dayjsValue = dayjs(timestamp);
    if (dayjsValue.isValid()) {
      return dayjsValue;
    } else {
      return null;
    }
  }
  
  // 如果是字符串
  if (typeof value === 'string' && value.trim() !== '') {
    const numValue = Number(value);
    if (!isNaN(numValue) && numValue > 0 && numValue.toString() === value.trim()) {
      let timestamp = numValue;
      if (timestamp < 10000000000) {
        timestamp = timestamp * 1000;
      }
      const dayjsValue = dayjs(timestamp);
      if (dayjsValue.isValid()) {
        return dayjsValue;
      } else {
        return null;
      }
    } else {
      const dayjsValue = dayjs(value);
      return dayjsValue.isValid() ? dayjsValue : null;
    }
  }
  
  // 如果已经是 dayjs 对象
  if (value && typeof value === 'object' && typeof value.isValid === 'function') {
    try {
      return value.isValid() ? value : null;
    } catch (e) {
      // isValid 调用失败
    }
  }
  
  // 如果是对象，检查是否有 $d 属性
  if (value && typeof value === 'object') {
    try {
      if (value.$d) {
        const dayjsValue = dayjs(value.$d);
        return dayjsValue.isValid() ? dayjsValue : null;
      }
      if (value.valueOf && typeof value.valueOf === 'function') {
        const timestamp = value.valueOf();
        if (typeof timestamp === 'number') {
          const dayjsValue = dayjs(timestamp);
          return dayjsValue.isValid() ? dayjsValue : null;
        }
      }
    } catch (e) {
      return null;
    }
  }
  
  return null;
};

// 辅助函数：验证 dayjs 对象是否有效
const isValidDayjs = (value: any): boolean => {
  if (!value) return false;
  if (typeof value !== 'object') return false;
  if (typeof value.isValid !== 'function') return false;
  try {
    return value.isValid();
  } catch (e) {
    return false;
  }
};

// 辅助函数：将表单值中的日期字符串转换为 dayjs 对象
const convertDateValues = (formValues: any, fields: any[]): any => {
  const fieldTypeMap: { [key: string]: string } = {};
  
  // 建立字段名到类型的映射
  fields.forEach((field: any) => {
    try {
      const fieldObj = typeof field === 'string' ? JSON.parse(field) : field;
      const fieldName = fieldObj.name || fieldObj.field;
      if (fieldName) {
        fieldTypeMap[fieldName] = fieldObj.type;
      }
    } catch (e) {
      // 解析失败，跳过
    }
  });
  
  // 转换日期值
  const convertedValues: any = {};
  Object.keys(formValues).forEach((fieldName) => {
    const fieldType = fieldTypeMap[fieldName];
    const value = formValues[fieldName];
    
    if (fieldType === 'date' || fieldType === 'datetime' || fieldType === 'timepicker') {
      convertedValues[fieldName] = safeToDayjs(value) || undefined;
    } else if (fieldType === 'daterange') {
      if (Array.isArray(value) && value.length === 2) {
        const [start, end] = value;
        const startDayjs = safeToDayjs(start);
        const endDayjs = safeToDayjs(end);
        
        if (startDayjs && endDayjs) {
          convertedValues[fieldName] = [startDayjs, endDayjs];
        } else {
          convertedValues[fieldName] = undefined;
        }
      } else {
        convertedValues[fieldName] = undefined;
      }
    } else {
      convertedValues[fieldName] = value;
    }
  });
  
  return convertedValues;
};

export default function ExecutorDashboard() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [nodeList, setNodeList] = useState<ExecutorNodeVO[]>([]);
  const [nodeCount, setNodeCount] = useState<ExecutorNodeCountVO>({
    unreleasedCount: 0,
    runningCount: 0,
    completedCount: 0,
  });
  const [trendData, setTrendData] = useState<ExecutorDayCompletedVO[]>([]);
  
  // 字典数据状态
  const [workTypeDictList, setWorkTypeDictList] = useState<DictDataVO[]>([]);
  const [urgencyLevelDictList, setUrgencyLevelDictList] = useState<DictDataVO[]>([]);
  
  // 任务详情弹框相关状态
  const [taskDetailVisible, setTaskDetailVisible] = useState(false);
  const [taskDetailLoading, setTaskDetailLoading] = useState(false);
  const [taskDetailData, setTaskDetailData] = useState<MyTaskNodeDetailVO | null>(null);
  const [formData, setFormData] = useState<FormCreateData>({
    rule: [],
    option: {}
  });
  const [formLoading, setFormLoading] = useState(false);
  const [originalFields, setOriginalFields] = useState<string[]>([]);
  const [originalConf, setOriginalConf] = useState<string>('');
  const [taskDetailForm] = AntdForm.useForm();
  const [approvalComment, setApprovalComment] = useState('');
  
  // 获取字典数据
  const fetchDictData = async () => {
    try {
      // 并行获取作业类型和紧急程度字典
      const [workTypeRes, urgencyRes] = await Promise.all([
        dictDataApi.getDictDataPage({
          pageNo: 1,
          pageSize: -1,
          dictType: 'work_type',
        }),
        dictDataApi.getDictDataPage({
          pageNo: 1,
          pageSize: -1,
          dictType: 'urgency_level',
        }),
      ]);
      
      // 处理作业类型字典数据
      const workTypeData = (workTypeRes as any)?.data || workTypeRes;
      setWorkTypeDictList(workTypeData?.list || []);
      
      // 处理紧急程度字典数据
      const urgencyData = (urgencyRes as any)?.data || urgencyRes;
      setUrgencyLevelDictList(urgencyData?.list || []);
    } catch (error: any) {
      console.error('获取字典数据失败', error);
      setWorkTypeDictList([]);
      setUrgencyLevelDictList([]);
    }
  };
  
  // 获取所有数据
  const fetchAllData = async () => {
    setLoading(true);
    try {
      // 并行调用三个接口
      const [countData, completedList, nodeListData] = await Promise.all([
        executorHomeApi.getExecutorNodeCount(),
        executorHomeApi.getMyCompletedNodeList(),
        executorHomeApi.getMyNodeList({ pageNo: 1, pageSize: 10 }),
      ]);
      
      // 设置统计数据
      setNodeCount(countData || { unreleasedCount: 0, runningCount: 0, completedCount: 0 });
      
      // 设置趋势数据
      const formattedTrendData = (completedList || []).map(item => ({
        date: item.day ? (item.day.includes('日') ? item.day : `${item.day}日`) : '',
        completedCount: item.completedCount || 0,
      }));
      setTrendData(formattedTrendData);
      
      // 设置节点列表
      setNodeList(nodeListData || []);
    } catch (error: any) {
      console.error('获取数据失败', error);
      toast.error(error.message || '获取数据失败');
      setNodeCount({ unreleasedCount: 0, runningCount: 0, completedCount: 0 });
      setTrendData([]);
      setNodeList([]);
    } finally {
      setLoading(false);
    }
  };
  
  useEffect(() => {
    fetchDictData();
    fetchAllData();
  }, []);
  
  // 将 ExecutorNodeVO 转换为表格可用的格式
  const transformedNodeList = useMemo(() => {
    return nodeList.map((node) => ({
      ...node,
      // 映射字段以兼容表格显示
      id: (typeof node.id === 'number' ? node.id : undefined) || (typeof node.nodeId === 'number' ? node.nodeId : undefined),
      nodeId: node.nodeId || node.id || node.uuid,
      orderNo: node.orderNo || (node.workId ? String(node.workId) : String(node.id || '')),
      name: node.name || '未知任务',
      currentNodeName: node.currentNodeName || node.nodeName || '',
      currentNodeId: node.currentNodeId || node.nodeId,
      approvalStatus: node.approvalStatus,
      taskStatus: node.approvalStatus,
      status: node.approvalStatus,
      workTime: node.workTime || node.startTime,
      startTime: node.startTime || (node.workTime ? String(node.workTime) : undefined), // 使用 workTime 作为开始时间（转换为字符串）
      workerUserName: node.workerUserName || node.initiatorName || '',
      urgencyLevel: node.urgencyLevel !== undefined && node.urgencyLevel !== null ? node.urgencyLevel : '', // 从接口数据中获取（保留0值）
      workType: node.workType !== undefined && node.workType !== null ? node.workType : '', // 从接口数据中获取（保留0值）
    }));
  }, [nodeList]);
  
  // 获取任务状态文本（根据 approvalStatus 数字值判断）
  const getTaskStatusText = (status: string | number | undefined): string => {
    if (status === undefined || status === null) return '待执行';
    
    // 如果 status 是数字，根据接口文档：1-待执行，2-进行中，3-已完成
    const statusNum = typeof status === 'number' ? status : parseInt(String(status), 10);
    if (!isNaN(statusNum)) {
      if (statusNum === 1) return '待执行';
      if (statusNum === 2) return '进行中';
      if (statusNum === 3) return '已完成';
    }
    
    // 兼容字符串状态
    const statusStr = String(status).toLowerCase();
    if (statusStr === 'pending' || statusStr === '待执行' || statusStr === '待开始' || statusStr === '未开始' || statusStr === 'unaudited' || statusStr === '1') {
      return '待执行';
    }
    if (statusStr === 'running' || statusStr === '进行中' || statusStr === 'in_progress' || statusStr === '执行中' || statusStr === '2') {
      return '进行中';
    }
    if (statusStr === 'completed' || statusStr === '已完成' || statusStr === 'approved' || statusStr === '已通过' || statusStr === '3') {
      return '已完成';
    }
    return '待执行';
  };
  
  // 获取任务状态样式
  const getTaskStatusStyle = (status: string | number | undefined) => {
    const statusText = getTaskStatusText(status);
    if (statusText === '待执行') {
      return { backgroundColor: '#e5e5e5', color: '#333333' };
    }
    if (statusText === '进行中') {
      return { backgroundColor: '#1677ff', color: '#ffffff' };
    }
    if (statusText === '已完成') {
      return { backgroundColor: '#0acb57', color: '#ffffff' };
    }
    return { backgroundColor: '#e5e5e5', color: '#333333' };
  };
  
  // 获取紧急程度图标和样式（根据字典 value 判断：0=一般，1=紧急，2=非常紧急）
  const getUrgencyLevelIconAndStyle = (urgencyValue: string | number | undefined): { icon: React.ReactNode; style: React.CSSProperties } => {
    if (urgencyValue === null || urgencyValue === undefined || urgencyValue === '') {
      return {
        icon: null,
        style: {
          backgroundColor: '#e5e5e5',
          color: '#333333',
        },
      };
    }
    
    const value = Number(urgencyValue);
    
    // 0 = 一般：使用 urgecy1.png 图标 + 黑色文字
    if (value === 0) {
      return {
        icon: (
          <img 
            src={urgecy1Icon} 
            alt="一般" 
            className="w-5 h-5 flex-shrink-0 mr-1.5"
            style={{ objectFit: 'contain' }}
          />
        ),
        style: {
          backgroundColor: 'transparent',
          color: '#000000',
        },
      };
    }
    
    // 1 = 紧急：使用 urgecy2.png 图标 + 橙色加粗文字
    if (value === 1) {
      return {
        icon: (
          <img 
            src={urgecy2Icon} 
            alt="紧急" 
            className="w-5 h-5 flex-shrink-0 mr-1.5"
            style={{ objectFit: 'contain' }}
          />
        ),
        style: {
          backgroundColor: 'transparent',
          color: '#fa8c16',
          fontWeight: 'bold',
        },
      };
    }
    
    // 2 = 非常紧急：使用 urgecy3.png 图标 + 红色加粗文字
    if (value === 2) {
      return {
        icon: (
          <img 
            src={urgecy3Icon} 
            alt="非常紧急" 
            className="w-5 h-5 flex-shrink-0 mr-1.5"
            style={{ objectFit: 'contain' }}
          />
        ),
        style: {
          backgroundColor: 'transparent',
          color: '#ff4d4f',
          fontWeight: 'bold',
        },
      };
    }
    
    // 如果没有匹配到，默认灰色
    return {
      icon: null,
      style: {
        backgroundColor: '#e5e5e5',
        color: '#333333',
      },
    };
  };
  
  // 根据字典值获取作业类型文本
  const getWorkTypeText = (workType: string | number | undefined): string => {
    if (!workType && workType !== 0) {
      return '-';
    }
    const workTypeItem = workTypeDictList.find(item => String(item.value) === String(workType));
    return workTypeItem ? (workTypeItem.label || String(workType)) : String(workType);
  };
  
  // 根据字典值获取优先级文本
  const getPriorityText = (urgencyLevel: string | number | undefined): string => {
    if (!urgencyLevel && urgencyLevel !== 0) {
      return '-';
    }
    const urgencyItem = urgencyLevelDictList.find(item => String(item.value) === String(urgencyLevel));
    return urgencyItem ? (urgencyItem.label || String(urgencyLevel)) : String(urgencyLevel);
  };
  
  // 默认表单配置
  const defaultFormConfig = {
    name: '',
    labelPosition: 'right',
    formSize: 'middle',
    labelSuffix: '',
    labelWidth: 100,
    hideRequiredMark: false,
    showValidationError: true,
    inlineValidation: false,
    showSubmitButton: false,
    showResetButton: false,
  };

  // 渲染字段预览（支持嵌套结构）
  const renderFieldPreview = (field: any, parentSpanStyle?: React.CSSProperties): React.ReactNode => {
    const formConfig = formData.option?.formConfig || defaultFormConfig;
    const layoutColumns = formConfig.layoutColumns || 1;
    const spanStyle = parentSpanStyle || (layoutColumns > 1 ? { gridColumn: `span ${Math.min(layoutColumns, field.span || 1)}` } : undefined);

    // 处理容器类型（card 和 grid）
    if (field.type === 'card') {
      const children = field.children || [];
      const cardTitle = field.label || field.cardTitle || '卡片容器';
      return (
        <div key={field.id} style={spanStyle} className="mb-4">
          <Card title={cardTitle} className="w-full">
            <div className="space-y-4">
              {children.map((child: any) => renderFieldPreview(child))}
            </div>
          </Card>
        </div>
      );
    }

    if (field.type === 'grid') {
      const gridColumns = field.gridColumns || 2;
      const children = field.children || [];
      return (
        <div key={field.id} style={spanStyle} className="mb-4">
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: `repeat(${gridColumns}, minmax(0, 1fr))`,
              gap: '16px',
            }}
          >
            {children.map((child: any) => {
              const childSpanStyle = gridColumns > 1 
                ? { gridColumn: `span ${Math.min(gridColumns, child.span || 1)}` } 
                : undefined;
              return (
                <div key={child.id} style={childSpanStyle}>
                  {renderFieldPreview(child)}
                </div>
              );
            })}
          </div>
        </div>
      );
    }

    // 处理 alert 类型
    if (field.type === 'alert') {
      const themeClass =
        field.alertTheme === 'dark'
          ? 'bg-gray-800 text-white border-gray-700'
          : '';
      return (
        <div key={field.id} className="mb-4" style={spanStyle}>
          <Alert
            message={field.alertTitle || field.label}
            description={field.alertDescription}
            type={field.alertType || 'info'}
            showIcon={field.alertShowIcon !== false}
            closable={field.alertClosable}
            closeText={field.alertCloseText}
            className={`${field.alertCentered ? 'text-center' : ''} ${themeClass}`}
            banner
            style={field.style}
          />
          {field.hint && <div className="text-xs text-gray-400 mt-1">{field.hint}</div>}
        </div>
      );
    }

    // 处理普通字段
    switch (field.type) {
      case 'textarea':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请输入' }] : []}
              help={field.hint}
            >
              <Input.TextArea 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请输入'} 
                rows={4}
                allowClear={field.showClear}
                maxLength={field.maxLength}
                readOnly={field.readOnly}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'password':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请输入' }] : []}
              help={field.hint}
            >
              <Input.Password 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请输入'}
                allowClear={field.showClear}
                maxLength={field.maxLength}
                readOnly={field.readOnly}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'number':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请输入' }] : []}
              help={field.hint}
            >
              <InputNumber 
                style={{ width: '100%' }} 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请输入'}
                max={field.maxLength}
                readOnly={field.readOnly}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'select':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择' }] : []}
              help={field.hint}
            >
              <Select
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请选择'}
                allowClear={field.showClear}
                disabled={field.disabled}
                size={field.size || 'middle'}
              >
                {(field.options || []).map((opt: any, idx: number) => (
                  <Select.Option key={idx} value={opt.value}>{opt.label}</Select.Option>
                ))}
              </Select>
            </AntdForm.Item>
          </div>
        );
      case 'date':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择日期' }] : []}
              help={field.hint}
              getValueFromEvent={(value) => {
                if (!value) return undefined;
                if (value && typeof value === 'object' && 'valueOf' in value && typeof value.valueOf === 'function' && 'isValid' in value && typeof value.isValid === 'function') {
                  if (value.isValid()) {
                    return value.valueOf();
                  }
                  return undefined;
                }
                return value;
              }}
              normalize={(value) => {
                if (!value) return undefined;
                if (typeof value === 'number') {
                  const dayjsValue = dayjs(value);
                  return dayjsValue.isValid() ? dayjsValue : undefined;
                }
                if (typeof value === 'string') {
                  const numValue = Number(value);
                  if (!isNaN(numValue) && numValue > 0) {
                    const dayjsValue = dayjs(numValue);
                    return dayjsValue.isValid() ? dayjsValue : undefined;
                  }
                  const dayjsValue = dayjs(value);
                  return dayjsValue.isValid() ? dayjsValue : undefined;
                }
                if (value && typeof value === 'object' && 'isValid' in value && typeof value.isValid === 'function') {
                  return value.isValid() ? value : undefined;
                }
                return undefined;
              }}
            >
              <DatePicker 
                style={{ width: '100%' }} 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请选择日期'}
                allowClear={field.showClear}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'daterange':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择日期范围' }] : []}
              help={field.hint}
              getValueFromEvent={(value) => {
                if (!value || !Array.isArray(value) || value.length !== 2) return undefined;
                const [start, end] = value;
                if (start && typeof start === 'object' && 'valueOf' in start && typeof start.valueOf === 'function' && 'isValid' in start && typeof start.isValid === 'function' &&
                    end && typeof end === 'object' && 'valueOf' in end && typeof end.valueOf === 'function' && 'isValid' in end && typeof end.isValid === 'function') {
                  if (start.isValid() && end.isValid()) {
                    return [start.valueOf(), end.valueOf()];
                  }
                  return undefined;
                }
                return value;
              }}
              normalize={(value) => {
                if (!value) return undefined;
                if (Array.isArray(value) && value.length === 2) {
                  const [start, end] = value;
                  let startDayjs: any = null;
                  let endDayjs: any = null;
                  
                  if (typeof start === 'number') {
                    startDayjs = dayjs(start);
                    startDayjs = startDayjs.isValid() ? startDayjs : null;
                  } else if (typeof start === 'string') {
                    const numValue = Number(start);
                    if (!isNaN(numValue) && numValue > 0) {
                      startDayjs = dayjs(numValue);
                      startDayjs = startDayjs.isValid() ? startDayjs : null;
                    } else {
                      startDayjs = dayjs(start);
                      startDayjs = startDayjs.isValid() ? startDayjs : null;
                    }
                  } else if (start && typeof start === 'object' && 'isValid' in start && typeof start.isValid === 'function') {
                    startDayjs = start.isValid() ? start : null;
                  }
                  
                  if (typeof end === 'number') {
                    endDayjs = dayjs(end);
                    endDayjs = endDayjs.isValid() ? endDayjs : null;
                  } else if (typeof end === 'string') {
                    const numValue = Number(end);
                    if (!isNaN(numValue) && numValue > 0) {
                      endDayjs = dayjs(numValue);
                      endDayjs = endDayjs.isValid() ? endDayjs : null;
                    } else {
                      endDayjs = dayjs(end);
                      endDayjs = endDayjs.isValid() ? endDayjs : null;
                    }
                  } else if (end && typeof end === 'object' && 'isValid' in end && typeof end.isValid === 'function') {
                    endDayjs = end.isValid() ? end : null;
                  }
                  
                  if (startDayjs && endDayjs) {
                    return [startDayjs, endDayjs];
                  }
                }
                return undefined;
              }}
            >
              <DatePicker.RangePicker 
                style={{ width: '100%' }} 
                placeholder={Array.isArray(field.placeholder) ? field.placeholder as [string, string] : ['开始日期', '结束日期']}
                allowClear={field.showClear}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'datetime':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择日期时间' }] : []}
              help={field.hint}
              getValueFromEvent={(value) => {
                if (!value) return undefined;
                if (value && typeof value === 'object' && 'valueOf' in value) {
                  return value.valueOf();
                }
                return value;
              }}
              normalize={(value) => {
                if (!value) return undefined;
                if (typeof value === 'number') {
                  const dayjsValue = dayjs(value);
                  return dayjsValue.isValid() ? dayjsValue : undefined;
                }
                if (typeof value === 'string') {
                  const numValue = Number(value);
                  if (!isNaN(numValue) && numValue > 0) {
                    const dayjsValue = dayjs(numValue);
                    return dayjsValue.isValid() ? dayjsValue : undefined;
                  }
                  const dayjsValue = dayjs(value);
                  return dayjsValue.isValid() ? dayjsValue : undefined;
                }
                if (value && typeof value === 'object' && 'isValid' in value && typeof value.isValid === 'function') {
                  return value.isValid() ? value : undefined;
                }
                return undefined;
              }}
            >
              <DatePicker 
                style={{ width: '100%' }} 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请选择日期时间'}
                allowClear={field.showClear}
                showTime={{ format: 'HH:mm:ss' }}
                format="YYYY-MM-DD HH:mm:ss"
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'switch':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择' }] : []}
              help={field.hint}
              valuePropName="checked"
            >
              <Switch disabled={field.disabled} />
            </AntdForm.Item>
          </div>
        );
      case 'radio':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择' }] : []}
              help={field.hint}
            >
              <Radio.Group disabled={field.disabled}>
                {(field.options || []).map((opt: any, idx: number) => (
                  <Radio key={idx} value={opt.value}>{opt.label}</Radio>
                ))}
              </Radio.Group>
            </AntdForm.Item>
          </div>
        );
      case 'checkbox':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择' }] : []}
              help={field.hint}
            >
              <Checkbox.Group disabled={field.disabled}>
                {(field.options || []).map((opt: any, idx: number) => (
                  <Checkbox key={idx} value={opt.value}>{opt.label}</Checkbox>
                ))}
              </Checkbox.Group>
            </AntdForm.Item>
          </div>
        );
      case 'cascader':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择' }] : []}
              help={field.hint}
            >
              <Cascader
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请选择'}
                options={field.cascaderOptions || []}
                className="w-full"
                allowClear={field.showClear}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      case 'upload':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请上传' }] : []}
              help={field.hint}
            >
              <Upload
                disabled={field.disabled}
                maxCount={field.uploadType === 'single-image' ? 1 : field.maxCount || (field.uploadType === 'multiple-image' ? 9 : undefined)}
                accept={field.accept || (field.uploadType === 'single-image' || field.uploadType === 'multiple-image' ? 'image/*' : undefined)}
                listType={(field.uploadType === 'file' ? 'text' : 'picture-card') as 'text' | 'picture-card' | 'picture'}
                multiple={field.uploadType !== 'single-image'}
              >
                {field.uploadType === 'file' ? (
                  <Button icon={<UploadOutlined />}>上传文件</Button>
                ) : (
                  <div>
                    <UploadOutlined />
                    <div style={{ marginTop: 8 }}>上传</div>
                  </div>
                )}
              </Upload>
            </AntdForm.Item>
          </div>
        );
      case 'time':
      case 'timepicker':
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择时间' }] : []}
              help={field.hint}
            >
              <DatePicker 
                style={{ width: '100%' }} 
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请选择时间'}
                allowClear={field.showClear}
                picker="time"
                format="HH:mm:ss"
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
      default:
        // 检查 inputType 是否为时间类型
        const inputType = field.inputType || field.type;
        if (inputType === 'date' || inputType === 'datetime' || inputType === 'time' || inputType === 'timepicker') {
          if (inputType === 'datetime') {
            return (
              <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
                <AntdForm.Item
                  label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
                  name={field.name || field.field}
                  required={field.required && !formConfig.hideRequiredMark}
                  rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择日期时间' }] : []}
                  help={field.hint}
                >
                  <DatePicker 
                    style={{ width: '100%' }} 
                    placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请选择日期时间'}
                    allowClear={field.showClear}
                    showTime={{ format: 'HH:mm:ss' }}
                    format="YYYY-MM-DD HH:mm:ss"
                    disabled={field.disabled}
                    size={field.size || 'middle'}
                  />
                </AntdForm.Item>
              </div>
            );
          } else if (inputType === 'time' || inputType === 'timepicker') {
            return (
              <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
                <AntdForm.Item
                  label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
                  name={field.name || field.field}
                  required={field.required && !formConfig.hideRequiredMark}
                  rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择时间' }] : []}
                  help={field.hint}
                >
                  <DatePicker 
                    style={{ width: '100%' }} 
                    placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请选择时间'}
                    allowClear={field.showClear}
                    picker="time"
                    format="HH:mm:ss"
                    disabled={field.disabled}
                    size={field.size || 'middle'}
                  />
                </AntdForm.Item>
              </div>
            );
          } else {
            return (
              <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
                <AntdForm.Item
                  label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
                  name={field.name || field.field}
                  required={field.required && !formConfig.hideRequiredMark}
                  rules={field.required ? [{ required: true, message: field.requiredMessage || '请选择日期' }] : []}
                  help={field.hint}
                >
                  <DatePicker 
                    style={{ width: '100%' }} 
                    placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请选择日期'}
                    allowClear={field.showClear}
                    disabled={field.disabled}
                    size={field.size || 'middle'}
                  />
                </AntdForm.Item>
              </div>
            );
          }
        }
        
        // 其他类型使用 Input
        return (
          <div key={field.id} style={{ ...spanStyle, backgroundColor: '#f5f5f5', padding: '12px', borderRadius: '12px', marginBottom: '12px', border: '1px solid #e0e0e0' }}>
            <AntdForm.Item
              label={(field.label || field.title || '') + (formConfig.labelSuffix || '')}
              name={field.name || field.field}
              required={field.required && !formConfig.hideRequiredMark}
              rules={field.required ? [{ required: true, message: field.requiredMessage || '请输入' }] : []}
              help={field.hint}
            >
              <Input 
                type={field.inputType || 'text'}
                placeholder={typeof field.placeholder === 'string' ? field.placeholder : '请输入'}
                allowClear={field.showClear}
                maxLength={field.maxLength}
                readOnly={field.readOnly}
                disabled={field.disabled}
                size={field.size || 'middle'}
              />
            </AntdForm.Item>
          </div>
        );
    }
  };

  // 查看任务详情（完整复刻管理员驾驶舱的逻辑）
  const handleViewTaskDetail = async (node: ExecutorNodeVO) => {
    console.log('ExecutorDashboard: handleViewTaskDetail 被调用', node);
    
    const nodeId = node.id || node.uuid;
    if (!nodeId) {
      console.warn('ExecutorDashboard: 节点ID不存在', node);
      message.warning('节点ID不存在');
      return;
    }
    
    setTaskDetailLoading(true);
    setTaskDetailVisible(true);
    console.log('ExecutorDashboard: 弹框状态已设置为 true (加载中)');
    
    try {
      // 确保 nodeId 是 number 类型
      const numericNodeId = typeof nodeId === 'number' ? nodeId : (typeof nodeId === 'string' ? parseInt(nodeId, 10) : Number(nodeId));
      if (isNaN(numericNodeId)) {
        console.warn('ExecutorDashboard: 节点ID无效', nodeId);
        message.warning('节点ID无效');
        setTaskDetailLoading(false);
        return;
      }
      
      console.log('ExecutorDashboard: 开始获取节点详情', { nodeId: numericNodeId });
      const response = await myTaskApi.getMyWorkNodeDetail(numericNodeId);
      console.log('ExecutorDashboard: 节点详情响应', response);
      
      let data: any = response;
    
      // 直接从第一层 data.formId 获取 formId
      let extractedFormId: number | undefined = undefined;
      if (data?.formId !== undefined && data?.formId !== null) {
        const formIdValue = data.formId;
        if (typeof formIdValue === 'string') {
          const parsed = parseInt(formIdValue, 10);
          if (!isNaN(parsed)) {
            extractedFormId = parsed;
            console.log('ExecutorDashboard: ✅ 从 data.formId (字符串) 提取到 formId', extractedFormId);
          }
        } else if (typeof formIdValue === 'number') {
          extractedFormId = formIdValue;
          console.log('ExecutorDashboard: ✅ 从 data.formId (数字) 提取到 formId', extractedFormId);
        }
      }
      
      if (extractedFormId === undefined) {
        console.warn('ExecutorDashboard: ⚠️ 未能提取到 formId', {
          'data.formId': data?.formId,
          'data': data
        });
      }
      
      // 合并列表数据中的作业信息
      const detailDataWithWorkInfo: MyTaskNodeDetailVO = {
        ...(data || {}),
        workName: node.nodeName || data?.workName || data?.name,
        orderNo: node.workId ? String(node.workId) : String(node.id || ''),
        workerUserName: node.workerUserName || data?.workerUserName,
        initiatorName: node.initiatorName || data?.initiatorName || data?.initiator || '',
        workTime: node.startTime || data?.workTime,
        type: data?.type || data?.nodeType || '',
        nodeType: data?.nodeType || data?.type || '',
        formId: extractedFormId,
      };
      
      console.log('ExecutorDashboard: 合并后的详情数据', detailDataWithWorkInfo);
      
      // 先设置数据，确保弹框有内容显示
      setTaskDetailData(detailDataWithWorkInfo);
      setTaskDetailVisible(true);
      setTaskDetailLoading(false);
      
      // 根据节点类型决定是否需要获取表单
      const nodeType = detailDataWithWorkInfo.type || detailDataWithWorkInfo.nodeType || '';
      const isIsolation = nodeType === 'isolation' || nodeType === '隔离' || nodeType === '隔离/方案';
      const isReleaseIsolation = nodeType === 'releaseIsolation' || nodeType === '解除隔离';
      const isReturnLock = nodeType === 'returnLock';
      const isApproved = detailDataWithWorkInfo.approvalStatus === 'approved' || detailDataWithWorkInfo.approvalStatus === 3;
      const formId = detailDataWithWorkInfo.formId;
      const hasFormId = formId !== undefined && formId !== null && (
        typeof formId === 'number' || 
        (typeof formId === 'string' && formId !== '' && String(formId).trim() !== '')
      );
      const hasFormData = detailDataWithWorkInfo.formData && (
        (typeof detailDataWithWorkInfo.formData === 'string' && detailDataWithWorkInfo.formData.trim() !== '') ||
        (typeof detailDataWithWorkInfo.formData === 'object' && Object.keys(detailDataWithWorkInfo.formData).length > 0)
      );
      
      // 如果任务状态为"已通过"且有 formData，则从 formData 中解析表单结构
      if (isApproved && hasFormData) {
        console.log('ExecutorDashboard: ✅ 任务已通过，从 formData 中解析表单结构');
        setFormLoading(true);
        
        try {
          let parsedFormData: any;
          if (typeof detailDataWithWorkInfo.formData === 'string') {
            parsedFormData = JSON.parse(detailDataWithWorkInfo.formData);
          } else {
            parsedFormData = detailDataWithWorkInfo.formData;
          }
          
          const conf = parsedFormData.conf;
          const fields = parsedFormData.fields;
          
          if (conf && fields) {
            const confString = typeof conf === 'string' ? conf : JSON.stringify(conf);
            const fieldsArray = Array.isArray(fields) ? fields : [];
            const fieldsStringArray = fieldsArray.map((field: any) => {
              return typeof field === 'string' ? field : JSON.stringify(field);
            });
            
            setOriginalConf(confString);
            setOriginalFields(fieldsStringArray);
            
            // 解析字段值用于回显
            const formValues: any = {};
            const fieldTypeMap: { [key: string]: string } = {};
            
            fieldsStringArray.forEach((fieldString: string) => {
              try {
                const fieldObj = typeof fieldString === 'string' ? JSON.parse(fieldString) : fieldString;
                const fieldName = fieldObj.name || fieldObj.field;
                if (fieldName) {
                  fieldTypeMap[fieldName] = fieldObj.type;
                }
              } catch (e) {
                console.error('ExecutorDashboard: 解析字段 JSON 失败', e, fieldString);
              }
            });
            
            fieldsStringArray.forEach((fieldString: string) => {
              try {
                const fieldObj = typeof fieldString === 'string' ? JSON.parse(fieldString) : fieldString;
                const fieldName = fieldObj.name || fieldObj.field;
                if (fieldName && fieldObj.value !== undefined && fieldObj.value !== null) {
                  const fieldType = fieldTypeMap[fieldName];
                  let value = fieldObj.value;
                  
                  if (fieldType === 'date' || fieldType === 'datetime') {
                    if (typeof value === 'string' && value.trim() !== '') {
                      const dayjsValue = dayjs(value);
                      formValues[fieldName] = dayjsValue.isValid() ? dayjsValue : undefined;
                    } else {
                      formValues[fieldName] = undefined;
                    }
                  } else if (fieldType === 'daterange') {
                    if (Array.isArray(value) && value.length === 2) {
                      const [start, end] = value;
                      const startDayjs = typeof start === 'string' && start ? dayjs(start) : null;
                      const endDayjs = typeof end === 'string' && end ? dayjs(end) : null;
                      if (startDayjs && startDayjs.isValid() && endDayjs && endDayjs.isValid()) {
                        formValues[fieldName] = [startDayjs, endDayjs];
                      } else {
                        formValues[fieldName] = undefined;
                      }
                    } else {
                      formValues[fieldName] = undefined;
                    }
                  } else {
                    formValues[fieldName] = value;
                  }
                }
              } catch (e) {
                console.error('ExecutorDashboard: 解析字段 JSON 失败', e, fieldString);
              }
            });
            
            setConfAndFields2(setFormData, conf, fields);
            const convertedFormValues = convertDateValues(formValues, fieldsStringArray);
            
            setTimeout(() => {
              taskDetailForm.setFieldsValue(convertedFormValues);
              console.log('ExecutorDashboard: 表单数据已回填（从 formData）', convertedFormValues);
            }, 100);
          } else {
            console.warn('ExecutorDashboard: formData 中缺少 conf 或 fields', { conf: !!conf, fields: !!fields });
            message.warning('表单数据不完整');
          }
        } catch (e) {
          console.error('ExecutorDashboard: 解析 formData 失败', e);
          message.error('解析表单数据失败: ' + (e instanceof Error ? e.message : String(e)));
        } finally {
          setFormLoading(false);
        }
      }
      // 如果不是隔离类型，且有表单ID，且不是从 formData 获取，则从接口获取表单配置
      else if (!isIsolation && !isReleaseIsolation && !isReturnLock && hasFormId) {
        console.log('ExecutorDashboard: ✅ 满足条件，开始获取表单', { formId, nodeType });
        setFormData({ rule: [], option: {} });
        setOriginalFields([]);
        setOriginalConf('');
        setFormLoading(true);
        
        (async () => {
          try {
            const numericFormId = typeof formId === 'string' ? parseInt(formId, 10) : formId;
            if (isNaN(numericFormId)) {
              console.error('ExecutorDashboard: formId 不是有效数字', formId);
              message.error('表单ID无效');
              setFormLoading(false);
              return;
            }
            
            console.log('ExecutorDashboard: 🚀 开始调用表单接口', { formId: numericFormId, nodeType });
            const FormApi = await import('../api/bpm/form');
            const formDetailResponse = await FormApi.getForm(numericFormId);
            console.log('ExecutorDashboard: ✅ 表单接口调用成功', formDetailResponse);
            
            let formDetail: any = formDetailResponse;
            if (formDetailResponse && typeof formDetailResponse === 'object' && 'data' in formDetailResponse) {
              formDetail = (formDetailResponse as any).data || formDetailResponse;
            }
            
            const conf = formDetail?.conf || formDetail?.formConfig;
            const fields = formDetail?.fields || formDetail?.formFields;
            
            if (conf && fields) {
              const confString = typeof conf === 'string' ? conf : JSON.stringify(conf);
              const fieldsArray = Array.isArray(fields) ? fields : [];
              const fieldsStringArray = fieldsArray.map((field: any) => {
                return typeof field === 'string' ? field : JSON.stringify(field);
              });
              
              setOriginalConf(confString);
              setOriginalFields(fieldsStringArray);
              
              setConfAndFields2(setFormData, conf, fields);
              
              // 如果有表单数据值，回填到表单
              if (detailDataWithWorkInfo.formData) {
                try {
                  let formValues = typeof detailDataWithWorkInfo.formData === 'string' 
                    ? JSON.parse(detailDataWithWorkInfo.formData) 
                    : detailDataWithWorkInfo.formData;
                  
                  formValues = convertDateValues(formValues, fieldsArray);
                  
                  const cleanedFormValues: any = {};
                  Object.keys(formValues).forEach(key => {
                    const value = formValues[key];
                    const field = fieldsArray.find((f: any) => {
                      const fieldObj = typeof f === 'string' ? JSON.parse(f) : f;
                      return (fieldObj.name || fieldObj.field) === key;
                    });
                    
                    if (field) {
                      const fieldObj = typeof field === 'string' ? JSON.parse(field) : field;
                      const fieldType = fieldObj.type;
                      
                      if (fieldType === 'date' || fieldType === 'datetime' || fieldType === 'timepicker') {
                        if (isValidDayjs(value)) {
                          cleanedFormValues[key] = value;
                        } else if (value !== null && value !== undefined) {
                          const dayjsValue = safeToDayjs(value);
                          cleanedFormValues[key] = dayjsValue || undefined;
                        } else {
                          cleanedFormValues[key] = undefined;
                        }
                      } else if (fieldType === 'daterange') {
                        if (Array.isArray(value) && value.length === 2) {
                          const [start, end] = value;
                          let startDayjs: dayjs.Dayjs | null = null;
                          if (isValidDayjs(start)) {
                            startDayjs = start;
                          } else {
                            startDayjs = safeToDayjs(start);
                          }
                          let endDayjs: dayjs.Dayjs | null = null;
                          if (isValidDayjs(end)) {
                            endDayjs = end;
                          } else {
                            endDayjs = safeToDayjs(end);
                          }
                          cleanedFormValues[key] = (startDayjs && endDayjs) ? [startDayjs, endDayjs] : undefined;
                        } else {
                          cleanedFormValues[key] = undefined;
                        }
                      } else {
                        cleanedFormValues[key] = value;
                      }
                    } else {
                      cleanedFormValues[key] = value;
                    }
                  });
                  
                  setTimeout(() => {
                    try {
                      taskDetailForm.setFieldsValue(cleanedFormValues);
                      console.log('ExecutorDashboard: 表单数据已回填', cleanedFormValues);
                    } catch (e) {
                      console.error('ExecutorDashboard: 设置表单值失败', e);
                    }
                  }, 100);
                } catch (e) {
                  console.error('ExecutorDashboard: 解析表单数据失败', e);
                }
              }
            } else {
              console.warn('ExecutorDashboard: 表单详情缺少配置或字段', { conf: !!conf, fields: !!fields });
              message.warning('表单配置不完整');
            }
          } catch (e) {
            console.error('ExecutorDashboard: 获取表单详情失败', e);
            message.error('获取表单详情失败: ' + (e instanceof Error ? e.message : String(e)));
          } finally {
            setFormLoading(false);
          }
        })();
      } else {
        setFormLoading(false);
      }
      
      // 回显审核意见
      if (detailDataWithWorkInfo.approvalOpinion && detailDataWithWorkInfo.approvalOpinion !== 'pending') {
        setApprovalComment(detailDataWithWorkInfo.approvalOpinion);
      } else {
        setApprovalComment('');
      }
      
      console.log('ExecutorDashboard: 弹框已打开', { detailVisible: true, detailData: detailDataWithWorkInfo });
    } catch (error: any) {
      console.error('ExecutorDashboard: 获取节点详情失败', error);
      toast.error(error.message || '获取节点详情失败');
      if (!taskDetailData) {
        setTaskDetailData({
          id: nodeId,
          nodeId: nodeId,
          workId: node.workId,
          workName: node.nodeName,
          orderNo: node.workId ? String(node.workId) : String(node.id || ''),
          workerUserName: node.workerUserName || node.initiatorName || '',
          workTime: node.startTime,
          type: '',
        } as MyTaskNodeDetailVO);
      }
      setTaskDetailVisible(true);
    } finally {
      setTaskDetailLoading(false);
    }
  };

  // 处理查看任务（使用新的 handleViewTaskDetail）
  const handleViewTask = (node: ExecutorNodeVO) => {
    handleViewTaskDetail(node);
  };
  
  // 表格列定义
  const columns = [
    {
      title: '作业编号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 120,
      render: (_: any, record: ExecutorNodeVO) => {
        return record.orderNo || '-';
      },
    },
    {
      title: '作业名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
      render: (text: string) => {
        return text || '-';
      },
    },
    {
      title: '任务名称',
      dataIndex: 'currentNodeName',
      key: 'currentNodeName',
      width: 200,
      ellipsis: true,
      render: (text: string, record: ExecutorNodeVO) => {
        const urgencyValue = record.urgencyLevel;
        const priorityText = getPriorityText(urgencyValue);
        
        // 根据优先级值设置颜色样式
        const getPriorityStyle = (value: string | number | undefined): React.CSSProperties => {
          if (value === null || value === undefined || value === '') {
            return { color: '#6b7280' }; // 灰色
          }
          const numValue = Number(value);
          if (numValue === 1) {
            return { color: '#fa8c16' }; // 紧急：橙色
          }
          if (numValue === 2) {
            return { color: '#ff4d4f' }; // 非常紧急：红色
          }
          return { color: '#6b7280' }; // 一般：灰色
        };
        
        const nodeName = text || record.currentNodeName || record.nodeName || record.description || '未知任务';
        
        return (
          <div>
            <div>{nodeName}</div>
            {urgencyValue !== undefined && urgencyValue !== null && urgencyValue !== '' && (
              <div className="text-xs mt-1" style={getPriorityStyle(urgencyValue)}>
                优先级：{priorityText}
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: '作业类型',
      dataIndex: 'workType',
      key: 'workType',
      width: 120,
      render: (workType: string | number | undefined, record: ExecutorNodeVO) => {
        const workTypeValue = workType || record.workType;
        const workTypeText = getWorkTypeText(workTypeValue);
        return <span>{workTypeText}</span>;
      },
    },
    {
      title: '开始时间',
      dataIndex: 'workTime',
      key: 'workTime',
      width: 180,
      render: (text: any, record: ExecutorNodeVO) => {
        const timeValue = text || record.workTime || record.startTime;
        if (!timeValue) return '-';
        try {
          // 如果是数字（时间戳），需要处理
          if (typeof timeValue === 'number') {
            // 如果是秒级时间戳，转换为毫秒
            let timestamp = timeValue;
            if (timestamp < 10000000000) {
              timestamp = timestamp * 1000;
            }
            return formatDateWithFormat(timestamp, 'YYYY-MM-DD HH:mm:ss');
          }
          return formatDateWithFormat(timeValue, 'YYYY-MM-DD HH:mm:ss');
        } catch (e) {
          return String(timeValue);
        }
      },
    },
    {
      title: '状态',
      key: 'status',
      width: 100,
      render: (_: any, record: ExecutorNodeVO) => {
        const status = record.approvalStatus;
        const statusText = getTaskStatusText(status);
        const style = getTaskStatusStyle(status);
        return (
          <Tag style={style}>
            {statusText}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: ExecutorNodeVO) => {
        return (
          <Button
            type="primary"
            size="small"
            onClick={() => handleViewTask(record)}
          >
            查看
          </Button>
        );
      },
    },
  ];
  
  return (
    <div className="space-y-8">
      {/* 任务状态摘要 */}
      <div className="grid grid-cols-3 gap-4 mb-8">
        <Card className="border border-gray-200 shadow-sm">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-500 mb-1">待执行任务</div>
              <div className="text-2xl font-bold text-gray-700">{nodeCount.unreleasedCount || 0}</div>
            </div>
            <div className="w-12 h-12 rounded-lg bg-gray-100 flex items-center justify-center">
              <Clock className="w-6 h-6 text-gray-600" />
            </div>
          </div>
        </Card>
        
        <Card className="border border-blue-200 shadow-sm bg-blue-50">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-500 mb-1">进行中任务</div>
              <div className="text-2xl font-bold text-blue-600">{nodeCount.runningCount || 0}</div>
            </div>
            <div className="w-12 h-12 rounded-lg bg-blue-100 flex items-center justify-center">
              <PlayCircle className="w-6 h-6 text-blue-600" />
            </div>
          </div>
        </Card>
        
        <Card className="border border-green-200 shadow-sm bg-green-50">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-500 mb-1">已完成任务</div>
              <div className="text-2xl font-bold text-green-600">{nodeCount.completedCount || 0}</div>
            </div>
            <div className="w-12 h-12 rounded-lg bg-green-100 flex items-center justify-center">
              <CheckCircle className="w-6 h-6 text-green-600" />
            </div>
          </div>
        </Card>
      </div>
      
      {/* 我的作业任务 */}
      <Card className="border border-gray-200 shadow-sm mb-8" style={{marginBottom: '20px'}}>
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <AlertCircle className="w-5 h-5 text-orange-500" />
            <h3 className="text-lg font-semibold text-gray-900">我的作业任务</h3>
          </div>
          <div className="flex items-center gap-4">
            <span className="text-sm text-gray-500">请及时处理您的作业任务</span>
            <Button 
              type="link" 
              size="small" 
              onClick={() => {
                // 通过 sessionStorage 传递参数，让 Dashboard 自动切换到隔离作业下的我的任务菜单
                sessionStorage.setItem('navigateToMenu', JSON.stringify({
                  menu: 'isolationWork',
                  subMenu: 'myTask'
                }));
                
                // 如果当前已经在 dashboard 页面，触发自定义事件来切换菜单
                if (window.location.pathname === '/dashboard') {
                  // 触发自定义事件，通知 Dashboard 切换菜单
                  window.dispatchEvent(new CustomEvent('switchToMenu', {
                    detail: { menu: 'isolationWork', subMenu: 'myTask' }
                  }));
                } else {
                  // 如果不在 dashboard 页面，导航过去
                  navigate('/dashboard');
                }
              }}
            >
              查看全部
            </Button>
          </div>
        </div>
        <Table
          columns={columns}
          dataSource={transformedNodeList}
          rowKey={(record) => `${record.id || record.uuid || Math.random()}`}
          loading={loading}
          pagination={false}
          size="middle"
        />
      </Card>
      
      {/* 任务完成趋势 */}
      <Card className="border border-gray-200 shadow-sm mb-8" style={{marginBottom: '20px'}}>
        <h3 className="text-lg font-semibold text-gray-900 mb-6">
          任务完成趋势(最近30天)
        </h3>
        <div className="h-80">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart
              data={trendData}
              margin={{ top: 10, right: 30, left: 20, bottom: 20 }}
            >
              <defs>
                <linearGradient id="colorCompletedCount" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#1677ff" stopOpacity={0.3}/>
                  <stop offset="95%" stopColor="#1677ff" stopOpacity={0}/>
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
              <XAxis 
                dataKey="date" 
                stroke="#6b7280"
                tick={{ fontSize: 12, fill: '#6b7280' }}
                axisLine={{ stroke: '#e5e7eb' }}
              />
              <YAxis 
                stroke="#6b7280"
                tick={{ fontSize: 12, fill: '#6b7280' }}
                axisLine={{ stroke: '#e5e7eb' }}
                domain={[0, 'dataMax + 1']}
              />
              <Tooltip 
                contentStyle={{ 
                  backgroundColor: '#fff', 
                  border: '1px solid #e5e7eb',
                  borderRadius: '8px',
                  padding: '8px 12px'
                }}
              />
              <Legend />
              <Area 
                type="monotone" 
                dataKey="completedCount" 
                stroke="#1677ff" 
                strokeWidth={2}
                fill="url(#colorCompletedCount)"
                name="每日完成任务数"
                dot={{ fill: '#1677ff', r: 4 }}
                activeDot={{ r: 6 }}
              />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      </Card>
      
      {/* 快捷操作 */}
      <Card className="border border-gray-200 shadow-sm">
        <div className="flex items-center gap-2 mb-4">
          <Rocket className="w-5 h-5 text-gray-600" />
          <h3 className="text-lg font-semibold text-gray-900">快捷操作</h3>
        </div>
        <div className="flex gap-4">
          <button
            className="flex-1 bg-white border border-gray-200 rounded-lg p-4 hover:bg-gray-50 hover:border-gray-300 transition-all flex flex-col items-center justify-center gap-2"
            onClick={() => navigate('/my-task')}
          >
            <CheckCircle className="w-6 h-6 text-gray-600" />
            <span className="text-sm font-medium text-gray-700">提交任务完成</span>
          </button>
          <button
            className="flex-1 bg-white border border-gray-200 rounded-lg p-4 hover:bg-gray-50 hover:border-gray-300 transition-all flex flex-col items-center justify-center gap-2"
            onClick={() => navigate('/my-task')}
          >
            <Eye className="w-6 h-6 text-gray-600" />
            <span className="text-sm font-medium text-gray-700">查看我的作业</span>
          </button>
          <button
            className="flex-1 bg-white border border-gray-200 rounded-lg p-4 hover:bg-gray-50 hover:border-gray-300 transition-all flex flex-col items-center justify-center gap-2"
            onClick={() => message.info('功能开发中')}
          >
            <ShoppingCart className="w-6 h-6 text-gray-600" />
            <span className="text-sm font-medium text-gray-700">申领作业物料</span>
          </button>
          <button
            className="flex-1 bg-white border border-gray-200 rounded-lg p-4 hover:bg-gray-50 hover:border-gray-300 transition-all flex flex-col items-center justify-center gap-2"
            onClick={() => message.info('功能开发中')}
          >
            <HelpCircle className="w-6 h-6 text-gray-600" />
            <span className="text-sm font-medium text-gray-700">问题反馈</span>
          </button>
        </div>
      </Card>

      {/* 任务详情弹框 */}
      <Modal
        title={null}
        open={taskDetailVisible}
        onCancel={() => {
          setTaskDetailVisible(false);
          setTaskDetailData(null);
        }}
        footer={null}
        width={1000}
        destroyOnClose
        maskClosable={false}
        styles={{
          body: {
            minHeight: '600px',
            maxHeight: '700px',
            height: '700px',
            padding: 0,
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden'
          }
        }}
      >
        {taskDetailLoading ? (
          <div className="py-8 text-center text-gray-500">加载中...</div>
        ) : taskDetailData ? (
          <div style={{ 
            display: 'flex',
            flexDirection: 'column',
            height: '100%',
            overflow: 'hidden'
          }}>
            {/* 标题区域 */}
            <div className="mb-4" style={{ padding: '20px 24px 0' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                <div style={{ 
                  width: '3px', 
                  height: '24px', 
                  backgroundColor: '#025fff',
                  borderRadius: '2px',
                  flexShrink: 0
                }}></div>
                <h2 className="text-xl font-semibold mb-2" style={{ color: '#025fff', marginBottom: 0 }}>
                  {taskDetailData.workName || taskDetailData.name || '任务详情'}
                </h2>
                <span 
                  className="inline-flex px-3 py-1 rounded-full text-xs font-medium"
                  style={getTaskStatusStyle(taskDetailData.approvalStatus || taskDetailData.taskStatus || taskDetailData.status)}
                >
                  {getTaskStatusText(taskDetailData.approvalStatus || taskDetailData.taskStatus || taskDetailData.status)}
                </span>
              </div>
              <div className="text-sm flex gap-4" style={{ color: '#898f9a', marginTop: '12px' }}>
                <span>工单编号：{taskDetailData.orderNo || '-'}</span>
                <span>作业负责人：{taskDetailData.initiatorName || '-'}</span>
                <span>任务负责人：{taskDetailData.workerUserName || '-'}</span>
                <span>开始时间：{taskDetailData.workTime ? dateFormatter(taskDetailData.workTime) : '-'}</span>
              </div>
            </div>

            {/* 内容区域 - 可滚动 */}
            <div className="mt-6" style={{ 
              padding: '0 24px',
              flex: 1,
              overflowY: 'auto',
              minHeight: 0
            }}>
              {(() => {
                const isApproved = taskDetailData?.approvalStatus === 'approved' || taskDetailData?.approvalStatus === 3;
                const nodeType = String(taskDetailData?.type || taskDetailData?.nodeType || '').trim();
                const isReview = nodeType === 'review';
                const isIsolation = nodeType === 'isolation' || nodeType === '隔离' || nodeType === '隔离/方案';
                const isReleaseIsolation = nodeType === 'releaseIsolation' || nodeType === '解除隔离';
                const isReturnLock = nodeType === 'returnLock';

                // 隔离/方案节点、解除隔离节点和还锁节点
                if (isIsolation || isReleaseIsolation || isReturnLock) {
                  return (
                    <div 
                      style={{
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center',
                        minHeight: '400px',
                        padding: '40px 20px'
                      }}
                    >
                      <Card
                        style={{
                          width: '100%',
                          maxWidth: '500px',
                          textAlign: 'center',
                          borderRadius: '12px',
                          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
                          border: '1px solid #e8e8e8'
                        }}
                        bodyStyle={{
                          padding: '40px 30px'
                        }}
                      >
                        <div style={{ marginBottom: '24px' }}>
                          <LockOutlined 
                            style={{ 
                              fontSize: '64px', 
                              color: '#1890ff',
                              display: 'block'
                            }} 
                          />
                        </div>
                        <div
                          style={{
                            fontSize: '20px',
                            fontWeight: 500,
                            color: '#333',
                            lineHeight: '1.6'
                          }}
                        >
                          此节点需要在锁柜系统中进行操作
                        </div>
                      </Card>
                    </div>
                  );
                }

                // 审核类型节点 (review)
                if (isReview) {
                  return (
                    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
                      <div className="space-y-6" style={{ padding: '0 24px', flex: 1, overflowY: 'auto', minHeight: 0 }}>
                        {/* 自定义表单 */}
                        {formLoading ? (
                          <div className="py-8 text-center text-gray-500">表单加载中...</div>
                        ) : formData.rule && formData.rule.length > 0 ? (
                          <div>
                            {(() => {
                              const formConfig = formData.option?.formConfig || defaultFormConfig;
                              const layoutColumns = formConfig.layoutColumns || 1;
                              const gridStyle = layoutColumns > 1 ? {
                                display: 'grid',
                                gridTemplateColumns: `repeat(${layoutColumns}, minmax(0, 1fr))`,
                                gap: '12px',
                                rowGap: '16px',
                              } : undefined;
                              
                              return (
                                <AntdForm
                                  form={taskDetailForm}
                                  layout={formConfig.labelPosition === 'top' ? 'vertical' : formConfig.labelPosition === 'left' ? 'horizontal' : 'horizontal'}
                                  size={formConfig.formSize === 'default' ? 'middle' : formConfig.formSize}
                                  requiredMark={formConfig.hideRequiredMark ? false : undefined}
                                  labelCol={formConfig.labelWidth ? { 
                                    style: { 
                                      width: `${formConfig.labelWidth}px`,
                                      textAlign: formConfig.labelPosition === 'left' ? 'left' : formConfig.labelPosition === 'right' ? 'right' : 'left'
                                    } 
                                  } : undefined}
                                >
                                  <div 
                                    style={gridStyle} 
                                    className={layoutColumns === 1 ? 'space-y-4' : 'form-detail-grid'}
                                  >
                                    <style>{`
                                      .form-detail-grid .ant-form-item {
                                        margin-bottom: 12px;
                                      }
                                    `}</style>
                                    {(formData.rule || []).map((field: any) => {
                                      const fieldWithDisabled = isApproved ? { ...field, disabled: true, readOnly: true } : field;
                                      return renderFieldPreview(fieldWithDisabled);
                                    })}
                                  </div>
                                </AntdForm>
                              );
                            })()}
                          </div>
                        ) : (
                          <div 
                            style={{
                              display: 'flex',
                              justifyContent: 'center',
                              alignItems: 'center',
                              minHeight: '400px',
                              padding: '40px 20px'
                            }}
                          >
                            <Card
                              style={{
                                width: '100%',
                                maxWidth: '500px',
                                textAlign: 'center',
                                borderRadius: '12px',
                                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
                                border: '1px solid #e8e8e8'
                              }}
                              bodyStyle={{
                                padding: '40px 30px'
                              }}
                            >
                              <div style={{ marginBottom: '24px' }}>
                                <CheckCircleOutlined 
                                  style={{ 
                                    fontSize: '64px', 
                                    color: '#1890ff',
                                    display: 'block'
                                  }} 
                                />
                              </div>
                              <div
                                style={{
                                  fontSize: '20px',
                                  fontWeight: 500,
                                  color: '#333',
                                  lineHeight: '1.6'
                                }}
                              >
                                无需填写表单，直接点击底部按钮提交即可
                              </div>
                            </Card>
                          </div>
                        )}

                        {/* 审核意见 */}
                        <div className="flex items-start" style={{ gap: '16px', backgroundColor: '#f5f5f5', padding: '12px 12px 22px 12px', borderRadius: '12px', border: '1px solid #e0e0e0', marginBottom: '12px' }}>
                          <label 
                            className="text-sm font-medium text-gray-700 whitespace-nowrap pt-2"
                            style={{ 
                              width: defaultFormConfig.labelWidth ? `${defaultFormConfig.labelWidth - 20}px` : '80px',
                              textAlign: defaultFormConfig.labelPosition === 'left' ? 'left' : defaultFormConfig.labelPosition === 'right' ? 'right' : 'left',
                              flexShrink: 0
                            }}
                          >
                            审核意见
                          </label>
                          <div className="flex-1">
                            <Input.TextArea
                              rows={4}
                              value={approvalComment}
                              onChange={(e) => setApprovalComment(e.target.value)}
                              placeholder="请输入审核意见（可选）"
                              maxLength={500}
                              showCount
                              disabled={isApproved}
                              readOnly={isApproved}
                            />
                          </div>
                        </div>
                      </div>
                      {/* 底部按钮 - 审核节点不显示按钮（只读模式） */}
                    </div>
                  );
                }

                // 其他节点类型（需要根据 formId 获取表单）
                return (
                  <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
                    <div className="space-y-6" style={{ padding: '0 24px', flex: 1, overflowY: 'auto', minHeight: 0 }}>
                      {/* 自定义表单 */}
                      {formLoading ? (
                        <div className="py-8 text-center text-gray-500">表单加载中...</div>
                      ) : formData.rule && formData.rule.length > 0 ? (
                        <div>
                          {(() => {
                            const formConfig = formData.option?.formConfig || defaultFormConfig;
                            const layoutColumns = formConfig.layoutColumns || 1;
                            const gridStyle = layoutColumns > 1 ? {
                              display: 'grid',
                              gridTemplateColumns: `repeat(${layoutColumns}, minmax(0, 1fr))`,
                              gap: '12px',
                              rowGap: '16px',
                            } : undefined;
                            
                            return (
                              <AntdForm
                                form={taskDetailForm}
                                layout={formConfig.labelPosition === 'top' ? 'vertical' : formConfig.labelPosition === 'left' ? 'horizontal' : 'horizontal'}
                                size={formConfig.formSize === 'default' ? 'middle' : formConfig.formSize}
                                requiredMark={formConfig.hideRequiredMark ? false : undefined}
                                labelCol={formConfig.labelWidth ? { 
                                  style: { 
                                    width: `${formConfig.labelWidth}px`,
                                    textAlign: formConfig.labelPosition === 'left' ? 'left' : formConfig.labelPosition === 'right' ? 'right' : 'left'
                                  } 
                                } : undefined}
                              >
                                <div 
                                  style={gridStyle} 
                                  className={layoutColumns === 1 ? 'space-y-4' : 'form-detail-grid'}
                                >
                                  <style>{`
                                    .form-detail-grid .ant-form-item {
                                      margin-bottom: 12px;
                                    }
                                  `}</style>
                                  {(formData.rule || []).map((field: any) => {
                                    const fieldWithDisabled = isApproved ? { ...field, disabled: true, readOnly: true } : field;
                                    return renderFieldPreview(fieldWithDisabled);
                                  })}
                                </div>
                              </AntdForm>
                            );
                          })()}
                        </div>
                      ) : (
                        <div 
                          style={{
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            minHeight: '400px',
                            padding: '40px 20px'
                          }}
                        >
                          <Card
                            style={{
                              width: '100%',
                              maxWidth: '500px',
                              textAlign: 'center',
                              borderRadius: '12px',
                              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
                              border: '1px solid #e8e8e8'
                            }}
                            bodyStyle={{
                              padding: '40px 30px'
                            }}
                          >
                            <div style={{ marginBottom: '24px' }}>
                              <CheckCircleOutlined 
                                style={{ 
                                  fontSize: '64px', 
                                  color: '#1890ff',
                                  display: 'block'
                                }} 
                              />
                            </div>
                            <div
                              style={{
                                fontSize: '20px',
                                fontWeight: 500,
                                color: '#333',
                                lineHeight: '1.6'
                              }}
                            >
                              无需填写表单，直接点击底部按钮提交即可
                            </div>
                          </Card>
                        </div>
                      )}
                    </div>
                    {/* 底部按钮 - 其他节点类型不显示按钮（只读模式） */}
                  </div>
                );
              })()}
            </div>
          </div>
        ) : null}
      </Modal>
    </div>
  );
}
