CreateBotQrcode.tsx 11.8 KB
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  listBotsQrcode,
  uploadMedia,
  saveEmployeeQrcode,
} from '../api/agent';
import type { BotQrcodeItem, SaveQrcodeResult } from '../api/agent';

const AVATAR_COLORS = ['#00D4AA', '#4A8CFF', '#FFA502', '#FF4757', '#2ED573', '#A855F7', '#EC4899', '#06B6D4'];

function botAvatarColor(botId: string): string {
  let hash = 0;
  for (let i = 0; i < botId.length; i++) {
    hash = botId.charCodeAt(i) + ((hash << 5) - hash);
  }
  return AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length];
}

function botInitials(name: string): string {
  const cleaned = name.replace(/[^a-zA-Z0-9\u4e00-\u9fff]/g, '');
  if (!cleaned) return '●';
  const isChinese = /[\u4e00-\u9fff]/.test(cleaned);
  if (isChinese) return cleaned.slice(-1);
  return cleaned.slice(0, 2).toUpperCase();
}

export function CreateBotQrcode() {
  const navigate = useNavigate();
  const fileRef = useRef<HTMLInputElement>(null);
  const [bots, setBots] = useState<BotQrcodeItem[]>([]);
  const [botsLoading, setBotsLoading] = useState(true);
  const [botsError, setBotsError] = useState<string | null>(null);

  const [selectedBotId, setSelectedBotId] = useState('');
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [uploading, setUploading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<SaveQrcodeResult | null>(null);

  const fetchBots = useCallback(() => {
    setBotsLoading(true);
    setBotsError(null);
    listBotsQrcode()
      .then(setBots)
      .catch(() => setBotsError('机器人列表加载失败'))
      .finally(() => setBotsLoading(false));
  }, []);

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

  function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith('image/')) {
      setError('请选择图片文件');
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      setError('图片不能超过 5MB');
      return;
    }

    setSelectedFile(file);
    setPreviewUrl(URL.createObjectURL(file));
    setError(null);
    setResult(null);
  }

  function selectBot(bot: BotQrcodeItem) {
    setSelectedBotId(bot.bot_id);
    setResult(null);
    setError(null);
    if (bot.has_qrcode && bot.qrcode_url) {
      setPreviewUrl(bot.qrcode_url);
    } else {
      setPreviewUrl(null);
    }
    setSelectedFile(null);
    if (fileRef.current) fileRef.current.value = '';
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setResult(null);

    if (!selectedBotId) {
      setError('请选择一个机器人');
      return;
    }
    if (!selectedFile) {
      setError('请上传二维码图片');
      return;
    }

    setUploading(true);
    try {
      const uploadResult = await uploadMedia(selectedFile);
      setSaving(true);

      try {
        const saveResult = await saveEmployeeQrcode(selectedBotId, uploadResult.cdn_url);
        setResult(saveResult);
        setSelectedFile(null);
        setPreviewUrl(null);
        if (fileRef.current) fileRef.current.value = '';
        fetchBots();
      } catch {
        setError('保存二维码失败');
      } finally {
        setSaving(false);
      }
    } catch {
      setError('上传图片失败');
    } finally {
      setUploading(false);
    }
  }

  const selectedBot = bots.find((b) => b.bot_id === selectedBotId);
  const isExisting = selectedBot?.has_qrcode ?? false;

  if (botsLoading) {
    return (
      <div className="page">
        <div className="page-heading">
          <h1>机器人二维码</h1>
          <p className="page-desc">绑定或更新机器人的二维码</p>
        </div>
        <div className="loading-block">
          <div className="loading-spinner" />
          <span>正在加载机器人列表...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="page">
      <div className="page-heading">
        <h1>机器人二维码</h1>
        <p className="page-desc">选择机器人并上传二维码图片,系统将自动上传 OSS 并完成绑定</p>
      </div>

      {error && (
        <div className="alert alert-error">
          <span className="alert-icon">!</span>
          <span>{error}</span>
        </div>
      )}

      {result && (
        <div className="alert alert-success">
          <span className="alert-icon">✓</span>
          <span>
            机器人 <code className="tag">{result.employee_id}</code> 二维码{isExisting ? '更新' : '绑定'}成功
          </span>
        </div>
      )}

      <form onSubmit={handleSubmit}>
        <div className="bq-layout">
          {/* ============ Left: Bot Cards ============ */}
          <div className="bq-panel bq-panel-bots">
            <div className="bq-panel-header bq-panel-header-stacked">
              <div className="bq-panel-heading">
                <span className="bq-panel-title">选择机器人</span>
                <span className="bq-panel-subtitle">选择一个机器人进行二维码绑定或更新</span>
              </div>
              <span className="bq-panel-count">
                {bots.filter((b) => b.has_qrcode).length}/{bots.length} 已绑定
              </span>
            </div>

            {botsError ? (
              <div className="inline-error" style={{ margin: '16px' }}>
                <span>{botsError}</span>
                <button className="btn btn-ghost btn-sm" onClick={fetchBots}>重试</button>
              </div>
            ) : bots.length === 0 ? (
              <div className="bq-empty">
                <div className="bq-empty-icon">!</div>
                <div className="bq-empty-title">暂无数据</div>
                <div className="bq-empty-desc">未找到机器人</div>
              </div>
            ) : (
              <div className="bq-card-list">
                {bots.map((bot) => {
                  const selected = selectedBotId === bot.bot_id;
                  const color = botAvatarColor(bot.bot_id);
                  return (
                    <label
                      key={bot.bot_id}
                      className={`bq-card${selected ? ' selected' : ''}${bot.has_qrcode ? ' has-qrcode' : ''}`}
                      style={{ '--accent-color': color } as React.CSSProperties}
                    >
                      <input
                        type="radio"
                        name="bot_id"
                        value={bot.bot_id}
                        checked={selected}
                        onChange={() => selectBot(bot)}
                      />
                      <div className="bq-card-accent" />
                      <div
                        className="bq-card-avatar"
                        style={{ background: color + '18', color }}
                      >
                        {botInitials(bot.bot_name || bot.bot_id)}
                      </div>
                      <div className="bq-card-body">
                        <div className="bq-card-name-row">
                          <div className="bq-card-name">{bot.bot_name || bot.bot_id}</div>
                          <div className={`bq-card-status${bot.has_qrcode ? ' bound' : ' unbound'}`}>
                            <span className="bq-card-status-dot" />
                            <span className="bq-card-status-label">{bot.has_qrcode ? '已绑定' : '未绑定'}</span>
                          </div>
                        </div>
                        <div className="bq-card-id">{bot.bot_id}</div>
                      </div>
                      {selected && <div className="bq-card-check">✓</div>}
                    </label>
                  );
                })}
              </div>
            )}
          </div>

          {/* ============ Right: Upload Area ============ */}
          <div className="bq-panel bq-panel-upload">
            <div className="bq-panel-header">
              <span className="bq-panel-title">
                {selectedBot
                  ? isExisting ? '更新二维码' : '新增二维码'
                  : '二维码图片'}
              </span>
              {selectedBot && (
                <span className="bq-panel-bot-tag" style={{ color: botAvatarColor(selectedBot.bot_id) }}>
                  {selectedBot.bot_name || selectedBot.bot_id}
                </span>
              )}
            </div>

            <div className="bq-upload-area" onClick={() => fileRef.current?.click()}>
              {previewUrl ? (
                <div className="bq-preview-wrap">
                  <img src={previewUrl} alt="二维码预览" className="bq-preview-img" />
                  {isExisting && !selectedFile && (
                    <div className="bq-preview-overlay">当前已绑定的二维码,点击上传新图片替换</div>
                  )}
                </div>
              ) : (
                <div className="bq-upload-placeholder">
                  <div className="bq-upload-icon">
                    <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                      <polyline points="17 8 12 3 7 8" />
                      <line x1="12" y1="3" x2="12" y2="15" />
                    </svg>
                  </div>
                  <div className="bq-upload-text">点击上传二维码图片</div>
                  <div className="bq-upload-hint">JPG / PNG,最大 5MB</div>
                </div>
              )}
              <input
                ref={fileRef}
                type="file"
                accept="image/*"
                className="upload-input"
                onChange={handleFileSelect}
              />
            </div>

            {previewUrl && (
              <div className="bq-upload-actions">
                <button
                  type="button"
                  className="btn btn-ghost btn-sm"
                  onClick={() => {
                    setSelectedFile(null);
                    if (isExisting && selectedBot?.qrcode_url) {
                      setPreviewUrl(selectedBot.qrcode_url);
                    } else {
                      setPreviewUrl(null);
                    }
                    if (fileRef.current) fileRef.current.value = '';
                  }}
                >
                  {isExisting && !selectedFile ? '取消' : '重新选择'}
                </button>
              </div>
            )}

            {selectedBot && selectedFile && (
              <div className="bq-summary">
                <div className="bq-summary-label">绑定对象</div>
                <div className="bq-summary-value">
                  <span
                    className="bq-summary-dot"
                    style={{ background: botAvatarColor(selectedBot.bot_id) }}
                  />
                  {selectedBot.bot_name || selectedBot.bot_id}
                  <span className="bq-summary-id">{selectedBot.bot_id}</span>
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="form-footer" style={{ marginTop: '24px' }}>
          <button
            type="submit"
            className="btn btn-primary"
            disabled={uploading || saving || !selectedBotId || !selectedFile}
          >
            {uploading ? '上传图片中...' : saving ? '保存中...' : isExisting ? '更新二维码' : '创建绑定'}
          </button>
          <button type="button" className="btn btn-ghost" onClick={() => navigate('/')}>
            取消
          </button>
        </div>
      </form>
    </div>
  );
}