official-site-agent-display-config-mock.ts 20 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
import { getAgentTagSource } from './agent-tag-mock';
import { getOfficialSiteJobTabSource, getOfficialSiteJobTabRecord } from './official-site-job-tab-mock';
import { getChannelCodeSource, getPositionDerivedInfo } from './channel-code-mock';

export type AgentDisplayStatus = 'enable' | 'disable';
export type AgentInternalStatus = 'enable' | 'disable';

export interface AgentDisplayConfigMockItem extends Record<string, unknown> {
  agent_id: number;
  agent_name: string;
  agent_status: AgentInternalStatus;
  icon_url: string;
  media_url: string;
  media_type: 'image' | 'video' | 'gif';
  media_size: number;
  speech_title: string;
  speech_content: string;
  display_status: AgentDisplayStatus;
  sort_order: number;
  created_at: string;
  updated_at: string;
  /** 已上架 Agent 可编辑,已停用 Agent 不可编辑 */
  can_edit: boolean;
}

export interface AgentDisplayConfigMockFixture {
  items: AgentDisplayConfigMockItem[];
  loadError?: boolean;
  saveError?: boolean;
  uploadError?: boolean;
  formatError?: boolean;
  sizeError?: boolean;
  validationError?: boolean;
}

export interface AgentDisplayConfigListResult {
  items: AgentDisplayConfigMockItem[];
  tab_context: {
    tab_id: number;
    position_name: string;
    qrcode_name: string;
    channel_code: string;
    employee_name: string;
    employee_role_text: string;
  };
  total: number;
}

export interface SaveAgentDisplayConfigPayload {
  agent_id: number;
  icon_url?: string;
  media_url?: string;
  media_type?: 'image' | 'video' | 'gif';
  media_size?: number;
  speech_title?: string;
  speech_content: string;
  display_status: AgentDisplayStatus;
  sort_order: number;
}

export interface SaveAgentDisplayConfigResult {
  agent_id: number;
  icon_url: string;
  media_url: string;
  media_type: 'image' | 'video' | 'gif';
  media_size: number;
  speech_title: string;
  speech_content: string;
  display_status: AgentDisplayStatus;
  sort_order: number;
  created_at: string;
  updated_at: string;
  can_edit: boolean;
  blocked?: boolean;
  message?: string;
  validation_errors?: Record<string, string>;
}

export interface UploadResult {
  url: string;
  type: 'image' | 'video' | 'gif';
  size: number;
  blocked?: boolean;
  message?: string;
}

const now = () => new Date().toISOString().replace('T', ' ').slice(0, 19);

const baseAgentDisplayConfigs: Record<number, AgentDisplayConfigMockItem[]> = {
  // tab_id: 1 - 店销顾问岗位
  1: [
    {
      agent_id: 101,
      agent_name: '复盘Agent',
      agent_status: 'enable',
      icon_url: 'https://cdn.example.com/icons/review-agent.png',
      media_url: 'https://cdn.example.com/media/review-agent.mp4',
      media_type: 'video',
      media_size: 15 * 1024 * 1024, // 15MB
      speech_title: '复盘Agent',
      speech_content: '帮助店销顾问完成每日复盘,分析业绩数据和客户反馈',
      display_status: 'enable',
      sort_order: 10,
      created_at: '2026-05-10 09:00:00',
      updated_at: '2026-05-15 10:30:00',
      can_edit: true,
    },
    {
      agent_id: 103,
      agent_name: '销售助手Agent',
      agent_status: 'enable',
      icon_url: 'https://cdn.example.com/icons/sales-assist.png',
      media_url: 'https://cdn.example.com/media/sales-assist.gif',
      media_type: 'gif',
      media_size: 2 * 1024 * 1024, // 2MB
      speech_title: '销售助手Agent',
      speech_content: '智能推荐话术和产品搭配,提升销售转化率',
      display_status: 'disable',
      sort_order: 20,
      created_at: '2026-05-11 10:00:00',
      updated_at: '2026-05-16 11:00:00',
      can_edit: true,
    },
    {
      agent_id: 102,
      agent_name: '质检Agent',
      agent_status: 'disable',
      icon_url: 'https://cdn.example.com/icons/quality-check.png',
      media_url: '',
      media_type: 'image',
      media_size: 0,
      speech_title: '质检Agent',
      speech_content: '对话质检,检测合规性和服务质量',
      display_status: 'disable',
      sort_order: 30,
      created_at: '2026-05-12 12:00:00',
      updated_at: '2026-05-17 09:00:00',
      can_edit: false, // 已停用,不可编辑
    },
  ],
  // tab_id: 2 - 售后客服岗位
  2: [
    {
      agent_id: 105,
      agent_name: '客诉安抚Agent',
      agent_status: 'enable',
      icon_url: '',
      media_url: '',
      media_type: 'image',
      media_size: 0,
      speech_title: '客诉安抚Agent',
      speech_content: '', // 未配置,speech_content 为空
      display_status: 'disable', // 未配置,默认已下架
      sort_order: 10,
      created_at: '2026-05-13 14:00:00',
      updated_at: '2026-05-18 16:00:00',
      can_edit: true,
    },
  ],
  // tab_id: 3 - 私域增长岗位
  3: [
    {
      agent_id: 104,
      agent_name: '线索跟进Agent',
      agent_status: 'enable',
      icon_url: 'https://cdn.example.com/icons/lead-follow.png',
      media_url: 'https://cdn.example.com/media/lead-follow.jpg',
      media_type: 'image',
      media_size: 500 * 1024, // 500KB
      speech_title: '线索跟进Agent',
      speech_content: '自动跟进线索,提醒销售及时处理',
      display_status: 'enable',
      sort_order: 0,
      created_at: '2026-05-14 15:00:00',
      updated_at: '2026-05-19 17:00:00',
      can_edit: true,
    },
  ],
};

const savedConfigsKey = 'agent-admin-saved-agent-display-configs';

function canUseStorage() {
  return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
}

function readSavedConfigs(): Record<number, AgentDisplayConfigMockItem[]> {
  if (!canUseStorage()) return {};
  try {
    const raw = window.localStorage.getItem(savedConfigsKey);
    return raw ? JSON.parse(raw) : {};
  } catch {
    return {};
  }
}

function writeSavedConfigs(configs: Record<number, AgentDisplayConfigMockItem[]>) {
  if (!canUseStorage()) return;
  window.localStorage.setItem(savedConfigsKey, JSON.stringify(configs));
}

export function resetAgentDisplayConfigMockState() {
  if (!canUseStorage()) return;
  window.localStorage.removeItem(savedConfigsKey);
}

export const agentDisplayConfigMockFixtures: Record<string, AgentDisplayConfigMockFixture> = {
  normal: { items: baseAgentDisplayConfigs[1] },
  empty: { items: [] },
  allDisabled: {
    items: [
      {
        agent_id: 106,
        agent_name: '未配置Agent',
        agent_status: 'enable',
        icon_url: '',
        media_url: '',
        media_type: 'image',
        media_size: 0,
        speech_title: '未配置Agent',
        speech_content: '',
        display_status: 'disable',
        sort_order: 0,
        created_at: '2026-05-20 10:00:00',
        updated_at: '2026-05-20 10:00:00',
        can_edit: true,
      },
    ],
  },
  allEnabled: {
    items: [
      {
        agent_id: 107,
        agent_name: '展示中Agent',
        agent_status: 'enable',
        icon_url: 'https://cdn.example.com/icons/test.png',
        media_url: 'https://cdn.example.com/media/test.jpg',
        media_type: 'image',
        media_size: 800 * 1024,
        speech_title: '展示中Agent',
        speech_content: '测试Agent概述',
        display_status: 'enable',
        sort_order: 0,
        created_at: '2026-05-20 10:00:00',
        updated_at: '2026-05-20 10:00:00',
        can_edit: true,
      },
    ],
  },
  loadError: { items: [], loadError: true },
  saveError: { items: baseAgentDisplayConfigs[1], saveError: true },
  uploadError: { items: baseAgentDisplayConfigs[1], uploadError: true },
  formatError: { items: baseAgentDisplayConfigs[1], formatError: true },
  sizeError: { items: baseAgentDisplayConfigs[1], sizeError: true },
  validationError: { items: baseAgentDisplayConfigs[1], validationError: true },
};

/**
 * 从岗位关联渠道活码中提取可配置 Agent 列表
 * 排除管家 Agent(agent_id = 1)
 */
function getAgentsForTab(tabId: number): { agent_id: number; agent_name: string; agent_status: AgentInternalStatus; speech_title: string }[] {
  const tab = getOfficialSiteJobTabRecord(String(tabId), getOfficialSiteJobTabSource());
  if (!tab) return [];

  const positionCode = tab.position_code;
  const agentTags = getAgentTagSource();

  // 找到岗位对应岗位标签的 Agent
  // 简化逻辑:根据渠道活码关联岗位,返回该岗位下的 Agent
  const channelCodes = getChannelCodeSource();
  const channelCode = channelCodes.find((c) => c.code_id === tab.qrcode_id);

  if (!channelCode) return [];

  // Mock 简化:根据岗位返回对应的 Agent
  const agentMapping: Record<string, number[]> = {
    'store_sales': [101, 103, 102],
    'after_sales_service': [105],
    'crm_growth': [104],
  };

  const agentIds = agentMapping[positionCode] ?? [];
  const agentNames: Record<number, { name: string; status: AgentInternalStatus }> = {
    101: { name: '复盘Agent', status: 'enable' },
    102: { name: '质检Agent', status: 'disable' },
    103: { name: '销售助手Agent', status: 'enable' },
    104: { name: '线索跟进Agent', status: 'enable' },
    105: { name: '客诉安抚Agent', status: 'enable' },
  };

  // 排除管家 Agent (agent_id = 1)
  return agentIds
    .filter((id) => id !== 1)
    .map((id) => ({
      agent_id: id,
      agent_name: agentNames[id]?.name ?? `Agent-${id}`,
      agent_status: agentNames[id]?.status ?? 'enable',
      speech_title: agentNames[id]?.name ?? `Agent-${id}`,
    }));
}

export function getAgentDisplayConfigList(
  tabId: number,
  scenario: string = 'normal',
): AgentDisplayConfigListResult | undefined {
  const tab = getOfficialSiteJobTabRecord(String(tabId), getOfficialSiteJobTabSource());

  if (!tab) return undefined;

  // Load error scenario
  if (scenario === 'loadError') {
    return {
      items: [],
      tab_context: {
        tab_id: tab.tab_id,
        position_name: tab.position_name,
        qrcode_name: tab.qrcode_name,
        channel_code: tab.channel_code,
        employee_name: tab.employee_name,
        employee_role_text: tab.employee_role_text,
      },
      total: 0,
    };
  }

  // Empty scenario - no configurable agents
  if (scenario === 'empty') {
    return {
      items: [],
      tab_context: {
        tab_id: tab.tab_id,
        position_name: tab.position_name,
        qrcode_name: tab.qrcode_name,
        channel_code: tab.channel_code,
        employee_name: tab.employee_name,
        employee_role_text: tab.employee_role_text,
      },
      total: 0,
    };
  }

  const savedConfigs = readSavedConfigs();
  const baseConfigs = baseAgentDisplayConfigs[tabId] ?? [];
  const overriddenConfigs = savedConfigs[tabId] ?? [];

  // Merge saved configs with base configs
  const configMap = new Map<number, AgentDisplayConfigMockItem>();
  for (const config of baseConfigs) {
    configMap.set(config.agent_id, config);
  }
  for (const config of overriddenConfigs) {
    configMap.set(config.agent_id, config);
  }

  // Get agents from this tab's channel code
  const agentsForTab = getAgentsForTab(tabId);

  // Build final list: include all agents for this tab
  const items: AgentDisplayConfigMockItem[] = agentsForTab.map((agent) => {
    const existingConfig = configMap.get(agent.agent_id);
    if (existingConfig) {
      // Update can_edit based on agent_status
      return {
        ...existingConfig,
        agent_status: agent.agent_status,
        can_edit: agent.agent_status === 'enable',
      };
    }
    // New agent without config - default to disabled
    return {
      agent_id: agent.agent_id,
      agent_name: agent.agent_name,
      agent_status: agent.agent_status,
      icon_url: '',
      media_url: '',
      media_type: 'image',
      media_size: 0,
      speech_title: agent.speech_title,
      speech_content: '',
      display_status: 'disable',
      sort_order: 99,
      created_at: now(),
      updated_at: now(),
      can_edit: agent.agent_status === 'enable',
    };
  });

  return {
    items,
    tab_context: {
      tab_id: tab.tab_id,
      position_name: tab.position_name,
      qrcode_name: tab.qrcode_name,
      channel_code: tab.channel_code,
      employee_name: tab.employee_name,
      employee_role_text: tab.employee_role_text,
    },
    total: items.length,
  };
}

export function getAgentDisplayConfigItem(tabId: number, agentId: number): AgentDisplayConfigMockItem | undefined {
  const result = getAgentDisplayConfigList(tabId);
  if (!result) return undefined;
  return result.items.find((item) => item.agent_id === agentId);
}

export function saveAgentDisplayConfig(
  tabId: number,
  payload: SaveAgentDisplayConfigPayload,
  scenario: string = 'normal',
): SaveAgentDisplayConfigResult {
  const result = getAgentDisplayConfigList(tabId);
  if (!result) {
    return {
      agent_id: payload.agent_id,
      icon_url: payload.icon_url ?? '',
      media_url: payload.media_url ?? '',
      media_type: payload.media_type ?? 'image',
      media_size: payload.media_size ?? 0,
      speech_title: payload.speech_title ?? '',
      speech_content: payload.speech_content,
      display_status: payload.display_status,
      sort_order: payload.sort_order,
      created_at: now(),
      updated_at: now(),
      can_edit: false,
      blocked: true,
      message: '岗位展示配置不存在',
    };
  }

  const agent = result.items.find((item) => item.agent_id === payload.agent_id);
  if (!agent) {
    return {
      agent_id: payload.agent_id,
      icon_url: payload.icon_url ?? '',
      media_url: payload.media_url ?? '',
      media_type: payload.media_type ?? 'image',
      media_size: payload.media_size ?? 0,
      speech_title: payload.speech_title ?? '',
      speech_content: payload.speech_content,
      display_status: payload.display_status,
      sort_order: payload.sort_order,
      created_at: now(),
      updated_at: now(),
      can_edit: false,
      blocked: true,
      message: 'Agent 不属于当前岗位',
    };
  }

  // Check if agent is disabled
  if (agent.agent_status === 'disable') {
    return {
      agent_id: payload.agent_id,
      icon_url: agent.icon_url,
      media_url: agent.media_url,
      media_type: agent.media_type,
      media_size: agent.media_size,
      speech_title: agent.speech_title,
      speech_content: agent.speech_content,
      display_status: agent.display_status,
      sort_order: agent.sort_order,
      created_at: agent.created_at,
      updated_at: agent.updated_at,
      can_edit: false,
      blocked: true,
      message: '该 Agent 已停用,无法编辑展示配置',
    };
  }

  // Validation errors
  const validationErrors: Record<string, string> = {};
  if (!payload.icon_url?.trim()) {
    validationErrors.icon_url = '图标必填';
  }
  if (!payload.speech_title?.trim()) {
    validationErrors.speech_title = 'Agent名称必填';
  }
  if (!payload.speech_content.trim()) {
    validationErrors.speech_content = 'Agent概述必填';
  } else if (payload.speech_content.length > 100) {
    validationErrors.speech_content = 'Agent概述不能超过100字';
  }
  if (!payload.media_url?.trim()) {
    validationErrors.media_url = '展示素材必填';
  }
  if (payload.sort_order < 0 || payload.sort_order > 99) {
    validationErrors.sort_order = '排序请输入0-99的整数';
  }

  if (Object.keys(validationErrors).length > 0) {
    return {
      agent_id: payload.agent_id,
      icon_url: payload.icon_url ?? '',
      media_url: payload.media_url ?? '',
      media_type: payload.media_type ?? 'image',
      media_size: payload.media_size ?? 0,
      speech_title: payload.speech_title ?? '',
      speech_content: payload.speech_content,
      display_status: payload.display_status,
      sort_order: payload.sort_order,
      created_at: now(),
      updated_at: now(),
      can_edit: true,
      blocked: true,
      message: '字段校验失败',
      validation_errors: validationErrors,
    };
  }

  // Save error scenario
  if (scenario === 'saveError') {
    return {
      agent_id: payload.agent_id,
      icon_url: payload.icon_url ?? '',
      media_url: payload.media_url ?? '',
      media_type: payload.media_type ?? 'image',
      media_size: payload.media_size ?? 0,
      speech_title: payload.speech_title ?? '',
      speech_content: payload.speech_content,
      display_status: payload.display_status,
      sort_order: payload.sort_order,
      created_at: now(),
      updated_at: now(),
      can_edit: true,
      blocked: true,
      message: '保存失败,请重试',
    };
  }

  // Normal save
  const savedConfigs = readSavedConfigs();
  const currentConfigs = savedConfigs[tabId] ?? baseAgentDisplayConfigs[tabId] ?? [];
  const existingIndex = currentConfigs.findIndex((c) => c.agent_id === payload.agent_id);

  const newConfig: AgentDisplayConfigMockItem = {
    agent_id: payload.agent_id,
    agent_name: agent.agent_name,
    agent_status: agent.agent_status,
    icon_url: payload.icon_url ?? agent.icon_url,
    media_url: payload.media_url ?? agent.media_url,
    media_type: payload.media_type ?? agent.media_type,
    media_size: payload.media_size ?? agent.media_size,
    speech_title: payload.speech_title ?? agent.speech_title,
    speech_content: payload.speech_content,
    display_status: payload.display_status,
    sort_order: payload.sort_order,
    created_at: existingIndex >= 0 ? currentConfigs[existingIndex].created_at : now(),
    updated_at: now(),
    can_edit: true,
  };

  if (existingIndex >= 0) {
    currentConfigs[existingIndex] = newConfig;
  } else {
    currentConfigs.push(newConfig);
  }

  savedConfigs[tabId] = currentConfigs;
  writeSavedConfigs(savedConfigs);

  return {
    agent_id: newConfig.agent_id,
    icon_url: newConfig.icon_url,
    media_url: newConfig.media_url,
    media_type: newConfig.media_type,
    media_size: newConfig.media_size,
    speech_title: newConfig.speech_title,
    speech_content: newConfig.speech_content,
    display_status: newConfig.display_status,
    sort_order: newConfig.sort_order,
    created_at: newConfig.created_at,
    updated_at: newConfig.updated_at,
    can_edit: newConfig.can_edit,
  };
}

export function uploadAgentMedia(
  file: { name: string; size: number; type: string },
  usage: 'icon' | 'media',
  scenario: string = 'normal',
): UploadResult {
  // Upload error scenario
  if (scenario === 'uploadError') {
    return {
      url: '',
      type: 'image',
      size: 0,
      blocked: true,
      message: '上传失败,请重试',
    };
  }

  // Format error scenario
  if (scenario === 'formatError') {
    return {
      url: '',
      type: 'image',
      size: 0,
      blocked: true,
      message: '文件格式不支持,请上传图片、视频或GIF',
    };
  }

  // Size error scenario (max 20MB for media)
  const maxSize = usage === 'icon' ? 5 * 1024 * 1024 : 20 * 1024 * 1024;
  if (file.size > maxSize) {
    return {
      url: '',
      type: 'image',
      size: 0,
      blocked: true,
      message: usage === 'icon' ? '图标大小不能超过5MB' : '素材大小不能超过20MB',
    };
  }

  // Validate file type
  const validImageTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'];
  const validVideoTypes = ['video/mp4'];
  const validTypes = usage === 'icon' ? validImageTypes : [...validImageTypes, ...validVideoTypes];

  if (!validTypes.includes(file.type)) {
    return {
      url: '',
      type: 'image',
      size: 0,
      blocked: true,
      message: '文件格式不支持',
    };
  }

  // Mock successful upload
  const mediaType: 'image' | 'video' | 'gif' =
    file.type === 'video/mp4' ? 'video' :
    file.type === 'image/gif' ? 'gif' : 'image';

  return {
    url: `https://cdn.example.com/uploads/${usage}-${Date.now()}-${file.name}`,
    type: mediaType,
    size: file.size,
  };
}

/**
 * 映射 agent_status 到页面文案
 */
export function mapAgentStatusToText(status: AgentInternalStatus): string {
  return status === 'enable' ? '已上架' : '已停用';
}

/**
 * 映射 display_status 到页面文案
 */
export function mapDisplayStatusToText(status: AgentDisplayStatus): string {
  return status === 'enable' ? '展示中' : '已下架';
}

/**
 * 获取列表展示状态文案(已停用 Agent 显示 `-`)
 */
export function getDisplayStatusTextForList(agentStatus: AgentInternalStatus, displayStatus: AgentDisplayStatus): string {
  if (agentStatus === 'disable') return '-';
  return mapDisplayStatusToText(displayStatus);
}