'use client';

import { useState, useCallback } from 'react';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Modal, toast, Button } from '@/components/common';
import { PageContainer } from '@/components/layout';
import { cn } from '@/utils/helpers';
import { formatDateTime } from '@/utils/formatters';
import {
  usePendingActions,
  useCreatePendingAction,
  useBatchCreatePendingActions,
  useUpdatePendingAction,
  useCancelPendingAction,
  useDeletePendingAction,
} from '@/hooks/usePendingActions';
import {
  PendingAction,
  PendingActionStatus,
  ACTION_CODE_OPTIONS,
  ACTION_CODES,
  STATUS_OPTIONS,
  getStatusInfo,
  getActionCodeLabel,
} from '@/types/pending-action.types';
import styles from './pending-actions.module.scss';

/** 可排序的操作项组件 */
interface SortableActionItemProps {
  id: string;
  label: string;
  index: number;
  onRemove: () => void;
}

function SortableActionItem({ id, label, index, onRemove }: SortableActionItemProps) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={styles.pendingActions__sortableItem}
    >
      <span
        className={styles.pendingActions__dragHandle}
        {...attributes}
        {...listeners}
      >
        &#x2630;
      </span>
      <span className={styles.pendingActions__sortableIndex}>{index + 1}</span>
      <span className={styles.pendingActions__sortableLabel}>{label}</span>
      <button
        type="button"
        className={styles.pendingActions__sortableRemove}
        onClick={onRemove}
      >
        &times;
      </button>
    </div>
  );
}

/**
 * 用户待办操作管理页面
 */
export default function PendingActionsPage() {
  // 筛选状态
  const [filters, setFilters] = useState({
    userId: '',
    actionCode: '',
    status: '' as PendingActionStatus | '',
    page: 1,
    limit: 20,
  });

  // 弹窗状态
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showBatchModal, setShowBatchModal] = useState(false);
  const [editingAction, setEditingAction] = useState<PendingAction | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
  const [viewingAction, setViewingAction] = useState<PendingAction | null>(null);

  // 表单状态 - 支持多选操作
  const [formData, setFormData] = useState({
    userId: '',
    selectedActions: [] as string[], // 按顺序存储已选择的 actionCode
    actionParamsMap: {} as Record<string, string>, // 每个 actionCode 对应的参数
    expiresAt: '',
  });

  // 特殊扣减表单状态
  const [specialDeductionForm, setSpecialDeductionForm] = useState({
    amount: '',
    reason: '',
    isOfflineSettlement: true,  // 默认为全额线下结算模式
  });

  // 单个操作编辑时使用的表单
  const [editFormData, setEditFormData] = useState({
    actionParams: '',
    priority: 0,
    expiresAt: '',
  });

  // 拖拽排序 sensors
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  // 批量创建表单
  const [batchFormData, setBatchFormData] = useState({
    userIds: '',
    actionCode: 'ADOPTION_WIZARD',
    actionParams: '',
    priority: 0,
    expiresAt: '',
  });

  // 数据查询
  const { data, isLoading, error, refetch } = usePendingActions({
    userId: filters.userId || undefined,
    actionCode: filters.actionCode || undefined,
    status: filters.status || undefined,
    page: filters.page,
    limit: filters.limit,
  });

  // Mutations
  const createMutation = useCreatePendingAction();
  const batchCreateMutation = useBatchCreatePendingActions();
  const updateMutation = useUpdatePendingAction();
  const cancelMutation = useCancelPendingAction();
  const deleteMutation = useDeletePendingAction();

  // 打开创建弹窗
  const handleCreate = () => {
    setEditingAction(null);
    setFormData({
      userId: '',
      selectedActions: [],
      actionParamsMap: {},
      expiresAt: '',
    });
    setSpecialDeductionForm({ amount: '', reason: '', isOfflineSettlement: true });
    setShowCreateModal(true);
  };

  // 打开编辑弹窗
  const handleEdit = (action: PendingAction) => {
    setEditingAction(action);
    setEditFormData({
      actionParams: action.actionParams ? JSON.stringify(action.actionParams, null, 2) : '',
      priority: action.priority,
      expiresAt: action.expiresAt ? action.expiresAt.slice(0, 16) : '',
    });
    setShowCreateModal(true);
  };

  // 切换选择操作
  const handleToggleAction = (actionCode: string) => {
    setFormData((prev) => {
      const isSelected = prev.selectedActions.includes(actionCode);
      if (isSelected) {
        // 取消选择
        const newSelected = prev.selectedActions.filter((code) => code !== actionCode);
        const newParamsMap = { ...prev.actionParamsMap };
        delete newParamsMap[actionCode];
        return { ...prev, selectedActions: newSelected, actionParamsMap: newParamsMap };
      } else {
        // 添加选择（追加到末尾）
        return {
          ...prev,
          selectedActions: [...prev.selectedActions, actionCode],
        };
      }
    });
  };

  // 拖拽排序结束
  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (over && active.id !== over.id) {
      setFormData((prev) => {
        const oldIndex = prev.selectedActions.indexOf(active.id as string);
        const newIndex = prev.selectedActions.indexOf(over.id as string);
        return {
          ...prev,
          selectedActions: arrayMove(prev.selectedActions, oldIndex, newIndex),
        };
      });
    }
  };

  // 移除已选择的操作
  const handleRemoveAction = (actionCode: string) => {
    setFormData((prev) => {
      const newSelected = prev.selectedActions.filter((code) => code !== actionCode);
      const newParamsMap = { ...prev.actionParamsMap };
      delete newParamsMap[actionCode];
      return { ...prev, selectedActions: newSelected, actionParamsMap: newParamsMap };
    });
  };

  // 打开批量创建弹窗
  const handleBatchCreate = () => {
    setBatchFormData({
      userIds: '',
      actionCode: 'ADOPTION_WIZARD',
      actionParams: '',
      priority: 0,
      expiresAt: '',
    });
    setShowBatchModal(true);
  };

  // 提交创建/编辑表单
  const handleSubmit = async () => {
    // 编辑模式
    if (editingAction) {
      let actionParams: Record<string, unknown> | undefined;
      if (editFormData.actionParams.trim()) {
        try {
          actionParams = JSON.parse(editFormData.actionParams);
        } catch {
          toast.error('操作参数格式错误，请输入有效的 JSON');
          return;
        }
      }

      try {
        await updateMutation.mutateAsync({
          id: editingAction.id,
          data: {
            actionParams,
            priority: editFormData.priority,
            expiresAt: editFormData.expiresAt ? new Date(editFormData.expiresAt).toISOString() : undefined,
          },
        });
        toast.success('操作已更新');
        setShowCreateModal(false);
      } catch (err) {
        toast.error((err as Error).message || '更新失败');
      }
      return;
    }

    // 创建模式 - 支持多选
    if (!formData.userId.trim()) {
      toast.error('请输入用户ID');
      return;
    }

    if (formData.selectedActions.length === 0) {
      toast.error('请至少选择一个操作类型');
      return;
    }

    // 解析每个操作的参数
    const actionParamsMap: Record<string, Record<string, unknown> | undefined> = {};
    for (const actionCode of formData.selectedActions) {
      // 特殊扣减有专用表单
      if (actionCode === ACTION_CODES.SPECIAL_DEDUCTION) {
        // 全额线下结算模式
        if (specialDeductionForm.isOfflineSettlement) {
          // 全额模式下，金额留空或为0，reason 使用默认或自定义
          const reason = specialDeductionForm.reason.trim() || '该收益已由用户与上级间线下完成现金收付';
          actionParamsMap[actionCode] = {
            amount: 0,  // 0 表示全额扣减模式
            reason,
            createdBy: 'admin', // TODO: 从登录状态获取
            isOfflineSettlement: true,
          };
          continue;
        }

        // 普通特殊扣减模式 - 需要输入金额
        const amount = parseFloat(specialDeductionForm.amount);
        if (isNaN(amount) || amount <= 0) {
          toast.error('特殊扣减金额必须大于 0');
          return;
        }
        if (!specialDeductionForm.reason.trim()) {
          toast.error('特殊扣减必须填写原因/备注');
          return;
        }
        actionParamsMap[actionCode] = {
          amount,
          reason: specialDeductionForm.reason.trim(),
          createdBy: 'admin', // TODO: 从登录状态获取
          isOfflineSettlement: false,
        };
        continue;
      }

      const paramsStr = formData.actionParamsMap[actionCode];
      if (paramsStr?.trim()) {
        try {
          actionParamsMap[actionCode] = JSON.parse(paramsStr);
        } catch {
          toast.error(`${getActionCodeLabel(actionCode)} 的参数格式错误，请输入有效的 JSON`);
          return;
        }
      }
    }

    try {
      // 按顺序创建多个操作，优先级递减（第一个最高）
      const basePriority = formData.selectedActions.length * 10; // 例如 3 个操作: 30, 20, 10
      let successCount = 0;

      for (let i = 0; i < formData.selectedActions.length; i++) {
        const actionCode = formData.selectedActions[i];
        const priority = basePriority - i * 10;

        await createMutation.mutateAsync({
          userId: formData.userId.trim(),
          actionCode,
          actionParams: actionParamsMap[actionCode],
          priority,
          expiresAt: formData.expiresAt ? new Date(formData.expiresAt).toISOString() : undefined,
        });
        successCount++;
      }

      toast.success(`成功创建 ${successCount} 个待办操作`);
      setShowCreateModal(false);
    } catch (err) {
      toast.error((err as Error).message || '创建失败');
    }
  };

  // 提交批量创建
  const handleBatchSubmit = async () => {
    const userIds = batchFormData.userIds
      .split(/[\n,，]/)  // 支持换行、英文逗号、中文逗号
      .map((id) => id.trim())
      .filter(Boolean);

    if (userIds.length === 0) {
      toast.error('请输入用户ID');
      return;
    }

    let actionParams: Record<string, unknown> | undefined;

    // 特殊扣减的特殊处理
    if (batchFormData.actionCode === ACTION_CODES.SPECIAL_DEDUCTION) {
      // 尝试解析已有参数
      let parsedParams: Record<string, unknown> = {};
      if (batchFormData.actionParams.trim()) {
        try {
          parsedParams = JSON.parse(batchFormData.actionParams);
        } catch {
          toast.error('操作参数格式错误，请输入有效的 JSON');
          return;
        }
      }

      const amount = typeof parsedParams.amount === 'number' ? parsedParams.amount : parseFloat(String(parsedParams.amount || '0'));
      const reason = String(parsedParams.reason || '').trim();

      // 金额为空、NaN 或 <= 0 时，自动切换为全额线下结算模式
      if (isNaN(amount) || amount <= 0) {
        actionParams = {
          amount: 0,
          reason: reason || '该收益已由用户与上级间线下完成现金收付',
          createdBy: 'admin',
          isOfflineSettlement: true,
        };
      } else {
        // 普通模式需要填写原因
        if (!reason) {
          toast.error('特殊扣减必须填写原因/备注');
          return;
        }
        actionParams = {
          amount,
          reason,
          createdBy: 'admin',
          isOfflineSettlement: false,
        };
      }
    } else if (batchFormData.actionParams.trim()) {
      try {
        actionParams = JSON.parse(batchFormData.actionParams);
      } catch {
        toast.error('操作参数格式错误，请输入有效的 JSON');
        return;
      }
    }

    try {
      const result = await batchCreateMutation.mutateAsync({
        userIds,
        actionCode: batchFormData.actionCode,
        actionParams,
        priority: batchFormData.priority,
        expiresAt: batchFormData.expiresAt
          ? new Date(batchFormData.expiresAt).toISOString()
          : undefined,
      });
      toast.success(`成功创建 ${result.successCount} 个操作${result.failedCount > 0 ? `，${result.failedCount} 个失败` : ''}`);
      setShowBatchModal(false);
    } catch (err) {
      toast.error((err as Error).message || '操作失败');
    }
  };

  // 取消操作
  const handleCancel = async (id: string) => {
    try {
      await cancelMutation.mutateAsync(id);
      toast.success('操作已取消');
    } catch (err) {
      toast.error((err as Error).message || '取消失败');
    }
  };

  // 删除操作
  const handleDelete = async (id: string) => {
    try {
      await deleteMutation.mutateAsync(id);
      toast.success('操作已删除');
      setDeleteConfirm(null);
    } catch (err) {
      toast.error((err as Error).message || '删除失败');
    }
  };

  // 搜索处理
  const handleSearch = useCallback(() => {
    setFilters((prev) => ({ ...prev, page: 1 }));
    refetch();
  }, [refetch]);

  // 翻页
  const handlePageChange = (page: number) => {
    setFilters((prev) => ({ ...prev, page }));
  };

  return (
    <PageContainer title="用户待办操作">
      <div className={styles.pendingActions}>
        {/* 页面标题 */}
        <div className={styles.pendingActions__header}>
          <h1 className={styles.pendingActions__title}>用户待办操作管理</h1>
          <p className={styles.pendingActions__subtitle}>
            配置指定用户登录后需要执行的特定操作，如认种向导、结算奖励等
          </p>
        </div>

        {/* 主内容卡片 */}
        <div className={styles.pendingActions__card}>
          {/* 筛选区域 */}
          <div className={styles.pendingActions__filters}>
            <input
              type="text"
              className={styles.pendingActions__input}
              placeholder="用户ID"
              value={filters.userId}
              onChange={(e) => setFilters({ ...filters, userId: e.target.value })}
            />
            <select
              className={styles.pendingActions__select}
              value={filters.actionCode}
              onChange={(e) => setFilters({ ...filters, actionCode: e.target.value })}
            >
              <option value="">全部操作类型</option>
              {ACTION_CODE_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
            <select
              className={styles.pendingActions__select}
              value={filters.status}
              onChange={(e) => setFilters({ ...filters, status: e.target.value as PendingActionStatus | '' })}
            >
              <option value="">全部状态</option>
              {STATUS_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
            <Button variant="outline" size="sm" onClick={handleSearch}>
              搜索
            </Button>
            <Button variant="outline" size="sm" onClick={() => refetch()}>
              刷新
            </Button>
            <div style={{ flex: 1 }} />
            <Button variant="outline" onClick={handleBatchCreate}>
              批量创建
            </Button>
            <Button variant="primary" onClick={handleCreate}>
              + 新建操作
            </Button>
          </div>

          {/* 列表 */}
          <div className={styles.pendingActions__list}>
            {isLoading ? (
              <div className={styles.pendingActions__loading}>加载中...</div>
            ) : error ? (
              <div className={styles.pendingActions__error}>
                <span>{(error as Error).message || '加载失败'}</span>
                <Button variant="outline" size="sm" onClick={() => refetch()}>
                  重试
                </Button>
              </div>
            ) : !data || data.items.length === 0 ? (
              <div className={styles.pendingActions__empty}>
                暂无数据，点击"新建操作"创建第一条待办操作
              </div>
            ) : (
              <>
                {/* 表格 */}
                <table className={styles.pendingActions__table}>
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>用户</th>
                      <th>操作类型</th>
                      <th>状态</th>
                      <th>优先级</th>
                      <th>创建时间</th>
                      <th>过期时间</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.items.map((action) => {
                      const statusInfo = getStatusInfo(action.status);
                      return (
                        <tr key={action.id}>
                          <td>{action.id}</td>
                          <td>
                            {action.accountSequence && (
                              <div className={styles.pendingActions__accountSequence}>
                                {action.accountSequence}
                              </div>
                            )}
                            <div className={styles.pendingActions__userId}>
                              ID: {action.userId}
                            </div>
                          </td>
                          <td>
                            <span className={styles.pendingActions__codeTag}>
                              {getActionCodeLabel(action.actionCode)}
                            </span>
                          </td>
                          <td>
                            <span
                              className={styles.pendingActions__statusTag}
                              style={{ backgroundColor: statusInfo.color, color: 'white' }}
                            >
                              {statusInfo.label}
                            </span>
                          </td>
                          <td>{action.priority}</td>
                          <td>{formatDateTime(action.createdAt)}</td>
                          <td>{action.expiresAt ? formatDateTime(action.expiresAt) : '-'}</td>
                          <td>
                            <div className={styles.pendingActions__actions}>
                              <button
                                className={styles.pendingActions__actionBtn}
                                onClick={() => setViewingAction(action)}
                              >
                                查看
                              </button>
                              {action.status === 'PENDING' && (
                                <>
                                  <button
                                    className={styles.pendingActions__actionBtn}
                                    onClick={() => handleEdit(action)}
                                  >
                                    编辑
                                  </button>
                                  <button
                                    className={cn(styles.pendingActions__actionBtn, styles['pendingActions__actionBtn--warning'])}
                                    onClick={() => handleCancel(action.id)}
                                  >
                                    取消
                                  </button>
                                </>
                              )}
                              <button
                                className={cn(styles.pendingActions__actionBtn, styles['pendingActions__actionBtn--danger'])}
                                onClick={() => setDeleteConfirm(action.id)}
                              >
                                删除
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>

                {/* 分页 */}
                {data.total > filters.limit && (
                  <div className={styles.pendingActions__pagination}>
                    <span>
                      共 {data.total} 条，第 {data.page} / {Math.ceil(data.total / data.limit)} 页
                    </span>
                    <div className={styles.pendingActions__pageButtons}>
                      <Button
                        variant="outline"
                        size="sm"
                        disabled={data.page <= 1}
                        onClick={() => handlePageChange(data.page - 1)}
                      >
                        上一页
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        disabled={data.page >= Math.ceil(data.total / data.limit)}
                        onClick={() => handlePageChange(data.page + 1)}
                      >
                        下一页
                      </Button>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </div>

        {/* 创建/编辑弹窗 */}
        <Modal
          visible={showCreateModal}
          title={editingAction ? '编辑操作' : '新建待办操作'}
          onClose={() => setShowCreateModal(false)}
          footer={
            <div className={styles.pendingActions__modalFooter}>
              <Button variant="outline" onClick={() => setShowCreateModal(false)}>
                取消
              </Button>
              <Button
                variant="primary"
                onClick={handleSubmit}
                loading={createMutation.isPending || updateMutation.isPending}
              >
                {editingAction ? '保存' : `创建${formData.selectedActions.length > 0 ? ` (${formData.selectedActions.length})` : ''}`}
              </Button>
            </div>
          }
          width={700}
        >
          {editingAction ? (
            /* 编辑模式 - 单个操作 */
            <div className={styles.pendingActions__form}>
              <div className={styles.pendingActions__formGroup}>
                <label>操作类型</label>
                <input
                  type="text"
                  value={getActionCodeLabel(editingAction.actionCode)}
                  disabled
                  className={styles.pendingActions__disabledInput}
                />
              </div>

              <div className={styles.pendingActions__formGroup}>
                <label>操作参数 (JSON格式，可选)</label>
                <textarea
                  value={editFormData.actionParams}
                  onChange={(e) => setEditFormData({ ...editFormData, actionParams: e.target.value })}
                  placeholder='{"key": "value"}'
                  rows={4}
                />
              </div>

              <div className={styles.pendingActions__formRow}>
                <div className={styles.pendingActions__formGroup}>
                  <label>优先级</label>
                  <input
                    type="number"
                    value={editFormData.priority}
                    onChange={(e) => setEditFormData({ ...editFormData, priority: parseInt(e.target.value) || 0 })}
                    min={0}
                  />
                </div>

                <div className={styles.pendingActions__formGroup}>
                  <label>过期时间</label>
                  <input
                    type="datetime-local"
                    value={editFormData.expiresAt}
                    onChange={(e) => setEditFormData({ ...editFormData, expiresAt: e.target.value })}
                  />
                </div>
              </div>
            </div>
          ) : (
            /* 创建模式 - 多选操作 */
            <div className={styles.pendingActions__form}>
              <div className={styles.pendingActions__formGroup}>
                <label>用户ID *</label>
                <input
                  type="text"
                  value={formData.userId}
                  onChange={(e) => setFormData({ ...formData, userId: e.target.value })}
                  placeholder="请输入目标用户ID"
                />
              </div>

              <div className={styles.pendingActions__formGroup}>
                <label>选择操作类型 (可多选)</label>
                <div className={styles.pendingActions__checkboxGrid}>
                  {ACTION_CODE_OPTIONS.map((opt) => {
                    const isSelected = formData.selectedActions.includes(opt.value);
                    return (
                      <label
                        key={opt.value}
                        className={cn(
                          styles.pendingActions__checkboxItem,
                          isSelected && styles['pendingActions__checkboxItem--selected']
                        )}
                      >
                        <input
                          type="checkbox"
                          checked={isSelected}
                          onChange={() => handleToggleAction(opt.value)}
                        />
                        <span>{opt.label}</span>
                      </label>
                    );
                  })}
                </div>
              </div>

              {formData.selectedActions.length > 0 && (
                <div className={styles.pendingActions__formGroup}>
                  <label>执行顺序 (拖拽排序，顶部优先执行)</label>
                  <DndContext
                    sensors={sensors}
                    collisionDetection={closestCenter}
                    onDragEnd={handleDragEnd}
                  >
                    <SortableContext
                      items={formData.selectedActions}
                      strategy={verticalListSortingStrategy}
                    >
                      <div className={styles.pendingActions__sortableList}>
                        {formData.selectedActions.map((actionCode, index) => (
                          <SortableActionItem
                            key={actionCode}
                            id={actionCode}
                            label={getActionCodeLabel(actionCode)}
                            index={index}
                            onRemove={() => handleRemoveAction(actionCode)}
                          />
                        ))}
                      </div>
                    </SortableContext>
                  </DndContext>
                  <span className={styles.pendingActions__formHint}>
                    将创建 {formData.selectedActions.length} 个待办操作，用户登录后按此顺序依次执行
                  </span>
                </div>
              )}

              {/* 特殊扣减专用表单 */}
              {formData.selectedActions.includes(ACTION_CODES.SPECIAL_DEDUCTION) && (
                <div className={styles.pendingActions__specialDeduction}>
                  <div className={styles.pendingActions__specialDeductionTitle}>
                    特殊扣减设置
                  </div>

                  {/* 扣减模式选择 */}
                  <div className={styles.pendingActions__formGroup}>
                    <label>扣减模式</label>
                    <div className={styles.pendingActions__radioGroup}>
                      <label className={styles.pendingActions__radioItem}>
                        <input
                          type="radio"
                          name="deductionMode"
                          checked={!specialDeductionForm.isOfflineSettlement}
                          onChange={() => setSpecialDeductionForm({ ...specialDeductionForm, isOfflineSettlement: false })}
                        />
                        <span>指定金额扣减</span>
                      </label>
                      <label className={styles.pendingActions__radioItem}>
                        <input
                          type="radio"
                          name="deductionMode"
                          checked={specialDeductionForm.isOfflineSettlement}
                          onChange={() => setSpecialDeductionForm({ ...specialDeductionForm, isOfflineSettlement: true, amount: '' })}
                        />
                        <span>全额线下结算扣减</span>
                      </label>
                    </div>
                  </div>

                  {/* 全额线下结算模式说明 */}
                  {specialDeductionForm.isOfflineSettlement && (
                    <div className={styles.pendingActions__modeHint}>
                      <div className={styles.pendingActions__modeHintIcon}>&#9432;</div>
                      <div className={styles.pendingActions__modeHintText}>
                        <strong>全额线下结算模式</strong>
                        <p>系统将自动查询该用户所有已结算到钱包的绿积分收益，逐笔扣减并标记为"线下已结算"。</p>
                        <p>适用场景：用户已在线下与上级完成现金收付，需要将系统中的收益记录清零。</p>
                      </div>
                    </div>
                  )}

                  {/* 指定金额模式 - 显示金额输入框 */}
                  {!specialDeductionForm.isOfflineSettlement && (
                    <div className={styles.pendingActions__formRow}>
                      <div className={styles.pendingActions__formGroup}>
                        <label>扣减金额 (绿积分) *</label>
                        <input
                          type="number"
                          value={specialDeductionForm.amount}
                          onChange={(e) => setSpecialDeductionForm({ ...specialDeductionForm, amount: e.target.value })}
                          placeholder="请输入扣减金额"
                          min={0}
                          step={0.01}
                        />
                      </div>
                    </div>
                  )}

                  <div className={styles.pendingActions__formGroup}>
                    <label>
                      {specialDeductionForm.isOfflineSettlement ? '扣减原因/备注 (可选，留空使用默认)' : '扣减原因/备注 *'}
                    </label>
                    <textarea
                      value={specialDeductionForm.reason}
                      onChange={(e) => setSpecialDeductionForm({ ...specialDeductionForm, reason: e.target.value })}
                      placeholder={specialDeductionForm.isOfflineSettlement
                        ? '默认备注：该收益已由用户与上级间线下完成现金收付'
                        : '请详细说明扣减原因，用户会在确认页面看到此信息'}
                      rows={3}
                    />
                    <span className={styles.pendingActions__formHint}>
                      此信息将显示给用户，请确保描述清晰准确
                    </span>
                  </div>
                </div>
              )}

              <div className={styles.pendingActions__formGroup}>
                <label>过期时间 (可选，所有操作共用)</label>
                <input
                  type="datetime-local"
                  value={formData.expiresAt}
                  onChange={(e) => setFormData({ ...formData, expiresAt: e.target.value })}
                />
                <span className={styles.pendingActions__formHint}>留空表示永不过期</span>
              </div>
            </div>
          )}
        </Modal>

        {/* 批量创建弹窗 */}
        <Modal
          visible={showBatchModal}
          title="批量创建操作"
          onClose={() => setShowBatchModal(false)}
          footer={
            <div className={styles.pendingActions__modalFooter}>
              <Button variant="outline" onClick={() => setShowBatchModal(false)}>
                取消
              </Button>
              <Button
                variant="primary"
                onClick={handleBatchSubmit}
                loading={batchCreateMutation.isPending}
              >
                批量创建
              </Button>
            </div>
          }
          width={600}
        >
          <div className={styles.pendingActions__form}>
            <div className={styles.pendingActions__formGroup}>
              <label>用户ID列表 *</label>
              <textarea
                value={batchFormData.userIds}
                onChange={(e) => setBatchFormData({ ...batchFormData, userIds: e.target.value })}
                placeholder="请输入用户ID，每行一个或用逗号分隔"
                rows={6}
                className={styles.pendingActions__userIdsInput}
              />
              <span className={styles.pendingActions__formHint}>
                当前 {batchFormData.userIds.split(/[\n,，]/).filter((s) => s.trim()).length} 个用户
              </span>
            </div>

            <div className={styles.pendingActions__formGroup}>
              <label>操作类型</label>
              <select
                value={batchFormData.actionCode}
                onChange={(e) => setBatchFormData({ ...batchFormData, actionCode: e.target.value })}
              >
                {ACTION_CODE_OPTIONS.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>

            {/* 特殊扣减提示 */}
            {batchFormData.actionCode === ACTION_CODES.SPECIAL_DEDUCTION && (
              <div className={styles.pendingActions__modeHint}>
                <div className={styles.pendingActions__modeHintIcon}>&#9432;</div>
                <div className={styles.pendingActions__modeHintText}>
                  <strong>特殊扣减参数说明</strong>
                  <p>金额为空或0：全额线下结算模式，自动扣减用户所有已结算收益</p>
                  <p>金额大于0：普通扣减模式，扣减指定金额（需填写原因）</p>
                </div>
              </div>
            )}

            <div className={styles.pendingActions__formGroup}>
              <label>
                操作参数 (JSON格式{batchFormData.actionCode === ACTION_CODES.SPECIAL_DEDUCTION ? '' : '，可选'})
              </label>
              <textarea
                value={batchFormData.actionParams}
                onChange={(e) => setBatchFormData({ ...batchFormData, actionParams: e.target.value })}
                placeholder={batchFormData.actionCode === ACTION_CODES.SPECIAL_DEDUCTION
                  ? '{"amount": 0, "reason": "可选备注"}\n金额为0或留空=全额线下结算'
                  : '{"key": "value"}'}
                rows={3}
              />
            </div>

            <div className={styles.pendingActions__formRow}>
              <div className={styles.pendingActions__formGroup}>
                <label>优先级</label>
                <input
                  type="number"
                  value={batchFormData.priority}
                  onChange={(e) => setBatchFormData({ ...batchFormData, priority: parseInt(e.target.value) || 0 })}
                  min={0}
                />
              </div>

              <div className={styles.pendingActions__formGroup}>
                <label>过期时间</label>
                <input
                  type="datetime-local"
                  value={batchFormData.expiresAt}
                  onChange={(e) => setBatchFormData({ ...batchFormData, expiresAt: e.target.value })}
                />
              </div>
            </div>
          </div>
        </Modal>

        {/* 查看详情弹窗 */}
        <Modal
          visible={!!viewingAction}
          title="操作详情"
          onClose={() => setViewingAction(null)}
          footer={
            <div className={styles.pendingActions__modalFooter}>
              <Button variant="outline" onClick={() => setViewingAction(null)}>
                关闭
              </Button>
            </div>
          }
          width={600}
        >
          {viewingAction && (
            <div className={styles.pendingActions__detail}>
              <div className={styles.pendingActions__detailRow}>
                <span className={styles.pendingActions__detailLabel}>ID:</span>
                <span>{viewingAction.id}</span>
              </div>
              <div className={styles.pendingActions__detailRow}>
                <span className={styles.pendingActions__detailLabel}>用户:</span>
                <span>
                  {viewingAction.accountSequence && `${viewingAction.accountSequence} / `}
                  ID: {viewingAction.userId}
                </span>
              </div>
              <div className={styles.pendingActions__detailRow}>
                <span className={styles.pendingActions__detailLabel}>操作类型:</span>
                <span>{getActionCodeLabel(viewingAction.actionCode)} ({viewingAction.actionCode})</span>
              </div>
              <div className={styles.pendingActions__detailRow}>
                <span className={styles.pendingActions__detailLabel}>状态:</span>
                <span
                  className={styles.pendingActions__statusTag}
                  style={{ backgroundColor: getStatusInfo(viewingAction.status).color, color: 'white' }}
                >
                  {getStatusInfo(viewingAction.status).label}
                </span>
              </div>
              <div className={styles.pendingActions__detailRow}>
                <span className={styles.pendingActions__detailLabel}>优先级:</span>
                <span>{viewingAction.priority}</span>
              </div>
              <div className={styles.pendingActions__detailRow}>
                <span className={styles.pendingActions__detailLabel}>创建时间:</span>
                <span>{formatDateTime(viewingAction.createdAt)}</span>
              </div>
              {viewingAction.completedAt && (
                <div className={styles.pendingActions__detailRow}>
                  <span className={styles.pendingActions__detailLabel}>完成时间:</span>
                  <span>{formatDateTime(viewingAction.completedAt)}</span>
                </div>
              )}
              {viewingAction.expiresAt && (
                <div className={styles.pendingActions__detailRow}>
                  <span className={styles.pendingActions__detailLabel}>过期时间:</span>
                  <span>{formatDateTime(viewingAction.expiresAt)}</span>
                </div>
              )}
              {viewingAction.createdBy && (
                <div className={styles.pendingActions__detailRow}>
                  <span className={styles.pendingActions__detailLabel}>创建人:</span>
                  <span>{viewingAction.createdBy}</span>
                </div>
              )}
              {viewingAction.actionParams && (
                <div className={styles.pendingActions__detailRow}>
                  <span className={styles.pendingActions__detailLabel}>操作参数:</span>
                  <pre className={styles.pendingActions__json}>
                    {JSON.stringify(viewingAction.actionParams, null, 2)}
                  </pre>
                </div>
              )}
            </div>
          )}
        </Modal>

        {/* 删除确认弹窗 */}
        <Modal
          visible={!!deleteConfirm}
          title="确认删除"
          onClose={() => setDeleteConfirm(null)}
          footer={
            <div className={styles.pendingActions__modalFooter}>
              <Button variant="outline" onClick={() => setDeleteConfirm(null)}>
                取消
              </Button>
              <Button
                variant="danger"
                onClick={() => deleteConfirm && handleDelete(deleteConfirm)}
                loading={deleteMutation.isPending}
              >
                确认删除
              </Button>
            </div>
          }
          width={400}
        >
          <p>确定要删除这条操作记录吗？此操作无法撤销。</p>
        </Modal>
      </div>
    </PageContainer>
  );
}
