AccountsPanel.tsx

13.7 KB v1.0
// 邮箱账号管理
import { useEffect, useState } from 'react';
import { api, ApiError, type TestConnectionResult } from '../../api';
import { useI18n } from '../../i18n';
import { Icon } from '../../components/Icon';
import { Modal } from '../../components/Modal';
import { Card, ColorSwatches, EmptyState, Field, InlineError, Spinner, Toggle } from '../../components/ui';
import { PanelHeader, type PanelProps } from './common';
import { accentOf } from '../../theme';
import type { Account, AccountInput } from '../../types';
import { formatFullDate } from '../../utils';

const PRESETS: Record<
  string,
  { imapHost: string; imapPort: number; imapSecure: boolean; smtpHost: string; smtpPort: number; smtpSecure: boolean }
> = {
  qq: { imapHost: 'imap.qq.com', imapPort: 993, imapSecure: true, smtpHost: 'smtp.qq.com', smtpPort: 465, smtpSecure: true },
  '163': { imapHost: 'imap.163.com', imapPort: 993, imapSecure: true, smtpHost: 'smtp.163.com', smtpPort: 465, smtpSecure: true },
  '126': { imapHost: 'imap.126.com', imapPort: 993, imapSecure: true, smtpHost: 'smtp.126.com', smtpPort: 465, smtpSecure: true },
  gmail: {
    imapHost: 'imap.gmail.com',
    imapPort: 993,
    imapSecure: true,
    smtpHost: 'smtp.gmail.com',
    smtpPort: 465,
    smtpSecure: true,
  },
  outlook: {
    imapHost: 'outlook.office365.com',
    imapPort: 993,
    imapSecure: true,
    smtpHost: 'smtp.office365.com',
    smtpPort: 587,
    smtpSecure: false,
  },
};

const EMPTY_FORM: AccountInput = {
  name: '',
  email: '',
  imapHost: '',
  imapPort: 993,
  imapSecure: true,
  smtpHost: '',
  smtpPort: 465,
  smtpSecure: true,
  username: '',
  password: '',
  color: 'blue',
};

function AccountModal({
  account,
  onClose,
  onSaved,
  showToast,
}: {
  account: Account | null;
  onClose: () => void;
  onSaved: () => void;
  showToast: (message: string, type?: 'info' | 'error') => void;
}) {
  const { t, lang } = useI18n();
  const [form, setForm] = useState<AccountInput>(() =>
    account
      ? {
          id: account.id,
          name: account.name,
          email: account.email,
          imapHost: account.imapHost,
          imapPort: account.imapPort,
          imapSecure: account.imapSecure,
          smtpHost: account.smtpHost,
          smtpPort: account.smtpPort,
          smtpSecure: account.smtpSecure,
          username: account.username,
          password: '',
          color: account.color,
        }
      : { ...EMPTY_FORM }
  );
  const [preset, setPreset] = useState('custom');
  const [testing, setTesting] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [testResult, setTestResult] = useState<TestConnectionResult | null>(null);

  const set = (patch: Partial<AccountInput>) => setForm((prev) => ({ ...prev, ...patch }));

  const applyPreset = (key: string) => {
    setPreset(key);
    if (PRESETS[key]) set(PRESETS[key]);
  };

  const test = async () => {
    setError('');
    setTestResult(null);
    setTesting(true);
    try {
      const result = await api.accounts.test(form);
      setTestResult(result);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : t('networkError'));
    } finally {
      setTesting(false);
    }
  };

  const save = async () => {
    setError('');
    if (!form.name.trim() || !form.email.trim() || !form.imapHost.trim() || !form.smtpHost.trim() || !form.username.trim()) {
      setError(t('fillRequired'));
      return;
    }
    if (!account && !form.password) {
      setError(t('fillRequired'));
      return;
    }
    setSaving(true);
    try {
      if (account) {
        await api.accounts.update(account.id, form);
      } else {
        await api.accounts.create(form);
      }
      showToast(t('accountSaved'));
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : t('networkError'));
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      title={account ? t('editAccount') : t('addAccount')}
      onClose={onClose}
      wide
      footer={
        <>
          <button type="button" className="btn" onClick={() => void test()} disabled={testing || saving}>
            {testing ? <Spinner size={14} /> : <Icon name="server" size={15} />}
            {testing ? t('testing') : t('testConnection')}
          </button>
          <div className="spacer" />
          <button type="button" className="btn" onClick={onClose} disabled={saving}>
            {t('cancel')}
          </button>
          <button type="button" className="btn btn-primary" onClick={() => void save()} disabled={saving}>
            {saving ? <Spinner size={14} /> : null}
            {t('save')}
          </button>
        </>
      }
    >
      <div className="grid-2">
        <Field label={t('accountName')} hint={t('accountNameHint')}>
          <input className="input" value={form.name} onChange={(event) => set({ name: event.target.value })} />
        </Field>
        <Field label={t('presetServers')}>
          <select className="input" value={preset} onChange={(event) => applyPreset(event.target.value)}>
            <option value="custom">{t('presetCustom')}</option>
            <option value="qq">QQ Mail</option>
            <option value="163">163 Mail</option>
            <option value="126">126 Mail</option>
            <option value="gmail">Gmail</option>
            <option value="outlook">Outlook / Microsoft 365</option>
          </select>
        </Field>
      </div>

      <div className="grid-2">
        <Field label={t('emailAddress')}>
          <input
            className="input"
            type="email"
            value={form.email}
            onChange={(event) => set({ email: event.target.value })}
          />
        </Field>
        <Field label={t('mailboxUser')}>
          <input className="input" value={form.username} onChange={(event) => set({ username: event.target.value })} />
        </Field>
      </div>

      <Field label={t('mailboxPassword')} hint={account ? t('passwordKeep') : undefined}>
        <input
          className="input"
          type="password"
          autoComplete="new-password"
          value={form.password}
          onChange={(event) => set({ password: event.target.value })}
        />
      </Field>

      <div className="server-group">
        <div className="server-group-title">{t('imapServer')}</div>
        <div className="server-row">
          <input
            className="input"
            placeholder={t('host')}
            value={form.imapHost}
            onChange={(event) => set({ imapHost: event.target.value })}
          />
          <input
            className="input port-input"
            type="number"
            value={form.imapPort}
            onChange={(event) => set({ imapPort: Number(event.target.value) })}
          />
          <label className="inline-toggle">
            <Toggle checked={form.imapSecure} onChange={(value) => set({ imapSecure: value })} />
            <span>{t('secure')}</span>
          </label>
        </div>
      </div>

      <div className="server-group">
        <div className="server-group-title">{t('smtpServer')}</div>
        <div className="server-row">
          <input
            className="input"
            placeholder={t('host')}
            value={form.smtpHost}
            onChange={(event) => set({ smtpHost: event.target.value })}
          />
          <input
            className="input port-input"
            type="number"
            value={form.smtpPort}
            onChange={(event) => set({ smtpPort: Number(event.target.value) })}
          />
          <label className="inline-toggle">
            <Toggle checked={form.smtpSecure} onChange={(value) => set({ smtpSecure: value })} />
            <span>{t('secure')}</span>
          </label>
        </div>
      </div>

      <Field label={t('colorTag')}>
        <ColorSwatches value={form.color} onChange={(value) => set({ color: value })} />
      </Field>

      {testResult && (
        <div className="test-result">
          <div className={testResult.imap.ok ? 'test-ok' : 'test-fail'}>
            <Icon name={testResult.imap.ok ? 'check' : 'alert'} size={14} />
            IMAP · {testResult.imap.ok ? t('imapOk') : testResult.imap.error}
          </div>
          {form.smtpHost && (
            <div className={testResult.smtp.ok ? 'test-ok' : 'test-fail'}>
              <Icon name={testResult.smtp.ok ? 'check' : 'alert'} size={14} />
              SMTP · {testResult.smtp.ok ? t('smtpOk') : testResult.smtp.error}
            </div>
          )}
        </div>
      )}

      <InlineError message={error} />
      {account?.lastSyncAt && (
        <div className="field-hint">
          {t('lastSync', { time: formatFullDate(account.lastSyncAt, lang) })}
        </div>
      )}
    </Modal>
  );
}

export function AccountsPanel({ showToast }: PanelProps) {
  const { t, lang } = useI18n();
  const [accounts, setAccounts] = useState<Account[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<Account | null>(null);
  const [creating, setCreating] = useState(false);
  const [busyId, setBusyId] = useState<number | null>(null);

  const load = async () => {
    setLoading(true);
    try {
      setAccounts(await api.accounts.list());
    } catch (err) {
      showToast(err instanceof ApiError ? err.message : t('networkError'), 'error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const remove = async (account: Account) => {
    if (!window.confirm(t('deleteAccountConfirm', { name: account.name }))) return;
    try {
      await api.accounts.remove(account.id);
      showToast(t('accountDeleted'));
      void load();
    } catch (err) {
      showToast(err instanceof ApiError ? err.message : t('networkError'), 'error');
    }
  };

  const sync = async (account: Account) => {
    setBusyId(account.id);
    try {
      const result = await api.accounts.sync(account.id);
      showToast(t('accountSyncDone', { n: result.count }));
      void load();
    } catch (err) {
      showToast(err instanceof ApiError ? err.message : t('networkError'), 'error');
    } finally {
      setBusyId(null);
    }
  };

  return (
    <>
      <PanelHeader title={t('accountsTitle')} desc={t('accountsDesc')} />

      <Card
        actions={
          <button type="button" className="btn btn-primary btn-small" onClick={() => setCreating(true)}>
            <Icon name="plus" size={15} />
            {t('addAccount')}
          </button>
        }
      >
        {loading ? (
          <div className="panel-loading">
            <Spinner size={18} />
          </div>
        ) : accounts.length === 0 ? (
          <EmptyState
            icon={<Icon name="server" size={26} />}
            title={t('noAccounts')}
            desc={t('accountsDesc')}
          >
            <button type="button" className="btn btn-primary" onClick={() => setCreating(true)}>
              {t('addAccount')}
            </button>
          </EmptyState>
        ) : (
          <div className="account-cards">
            {accounts.map((account) => (
              <div className="account-card" key={account.id}>
                <div className="account-card-main">
                  <span className="account-avatar" style={{ background: accentOf(account.color).soft, color: accentOf(account.color).strong }}>
                    {account.name.slice(0, 1).toUpperCase()}
                  </span>
                  <div className="account-card-info">
                    <div className="account-card-title">
                      {account.name}
                      <span className="account-card-email">{account.email}</span>
                    </div>
                    <div className="account-card-meta">
                      IMAP {account.imapHost}:{account.imapPort} · SMTP {account.smtpHost}:{account.smtpPort}
                    </div>
                    <div className="account-card-meta">
                      {account.lastSyncAt
                        ? t('lastSync', { time: formatFullDate(account.lastSyncAt, lang) })
                        : t('neverSynced')}
                    </div>
                    {account.syncError && <div className="inline-error">{account.syncError}</div>}
                  </div>
                </div>
                <div className="account-card-actions">
                  <button
                    type="button"
                    className="btn btn-small"
                    onClick={() => void sync(account)}
                    disabled={busyId === account.id}
                  >
                    {busyId === account.id ? <Spinner size={13} /> : <Icon name="refresh" size={14} />}
                    {t('syncNow')}
                  </button>
                  <button type="button" className="btn btn-small" onClick={() => setEditing(account)}>
                    <Icon name="compose" size={14} />
                    {t('edit')}
                  </button>
                  <button
                    type="button"
                    className="btn btn-small danger-text"
                    onClick={() => void remove(account)}
                  >
                    <Icon name="trash" size={14} />
                    {t('delete')}
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>

      {editing && (
        <AccountModal
          account={editing}
          onClose={() => setEditing(null)}
          onSaved={() => void load()}
          showToast={showToast}
        />
      )}
      {creating && (
        <AccountModal
          account={null}
          onClose={() => setCreating(false)}
          onSaved={() => void load()}
          showToast={showToast}
        />
      )}
    </>
  );
}