<script setup>
import { computed, reactive, ref } from "vue";
import {
  AppstoreOutlined,
  BarChartOutlined,
  BellFilled,
  CheckCircleFilled,
  ClockCircleOutlined,
  CloseOutlined,
  CloudUploadOutlined,
  DatabaseOutlined,
  DownOutlined,
  FileDoneOutlined,
  FileSearchOutlined,
  FormOutlined,
  ImportOutlined,
  LeftOutlined,
  LogoutOutlined,
  MenuFoldOutlined,
  NotificationFilled,
  PlayCircleFilled,
  ReloadOutlined,
  RightOutlined,
  SafetyCertificateFilled,
  SearchOutlined,
  SettingFilled,
  SlidersOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons-vue";
import { dictionary, importBatches, roles, serviceRecords, taskSummary, workOrders } from "./mock/data.js";
import FilterPanel from "./components/FilterPanel.vue";
import InvestigationFields from "./components/InvestigationFields.vue";
import OrderContext from "./components/OrderContext.vue";
import OrderTable from "./components/OrderTable.vue";

const loggedIn = ref(false);
const currentApp = ref("");
const loginLoading = ref(false);
const currentRoleId = ref("supervisor");
const currentPage = ref("tasks");
const selectedOrder = ref(workOrders[0]);
const activeTaskType = ref("");
const showRoleMenu = ref(false);
const showNotice = ref(false);
const showAssignment = ref(false);
const showReview = ref(false);
const toast = ref("");
const importPreview = ref(false);
const importFileName = ref("");
const transcriptExpanded = ref(true);
const appSearch = ref("");

const microApps = [
  { id: "work-orders", name: "12398 工单系统", description: "受理与处理客户工单，跟踪进度，提升服务效率", status: "可用", icon: FormOutlined, available: true },
  { id: "risk-events", name: "风险事件管理", description: "风险事件上报、评估、处置与跟踪，降低风险影响", status: "即将接入", icon: SafetyCertificateFilled, available: false },
  { id: "compliance", name: "合规检查", description: "检查计划与执行、问题整改与跟踪，强化合规管理", status: "即将接入", icon: CheckCircleFilled, available: false },
];

const loginForm = reactive({ username: "", password: "", code: "" });
const filters = reactive({ no: "", stage: "", source: "", calledAt: "", transferredAt: "", customer: "", phone: "", address: "", region: "", province: "", eventType: "", transferCategory: "", problemCategory: "" });
const dispatchForm = reactive({
  responsibilityType: "主责",
  preliminaryDepartments: ["运营部"],
  firstContactDepartment: "客服一部",
  supervisor: "监督员A（张某）",
  escalationDepartments: [],
});
const assignmentForm = reactive({ member: "", department: "客服一部" });
const assignmentMode = ref("first-contact");
const investigationForm = reactive({
  firstContactAt: "2026-08-12 14:32",
  firstContactNo: "2026-08-06-001",
  firstContactContent: "已联系客户核实电压波动情况，并告知后续调查安排。",
  preliminaryContent: "经初查，台区监测记录存在短时电压波动，已安排现场核验。",
  importedContent: "客户反映近期电压不稳，设备频繁重启，要求尽快处理。",
  externalExposureRisk: "否",
  internalAppealIssued: "否",
  customerAppealSummary: "客户要求核查电压不稳原因并尽快恢复稳定供电。",
  escalationReason: "客户多次反映后问题仍偶发，期望提高处理时效。",
  investigationProcess: "调取95598历史记录、台区电压监测数据，并组织属地单位开展现场检查。",
  localResponsibility: "是",
  handlingSituation: "已完成线路及设备检查，针对波动时段持续开展监测。",
  accountable: "否",
  hasHandlingBasis: "是",
  handlingMethod: "调整台区运行参数，增加重点时段监测频次，并向客户说明处理情况。",
  handlingResult: "当前电压监测数据已恢复正常，后续继续跟踪。",
  respondentName: "监督员A（张某）",
  repliedAt: "2026-08-10 10:44",
  replyPhone: "131****7777",
  replySituation: "",
  callbackResult: "同意",
});
const callbackUploads = reactive({ replyLetter: false, deliveryProof: false });
const reportForm = reactive({ title: "关于客户反映电压不稳问题的调查报告", summary: "", rootCause: "", measures: "", conclusion: "" });
const deliverableFiles = ref(["12398工单调查报告.pdf", "客户答复书.pdf"]);
const reviewForm = reactive({ result: "", reason: "", callbackDepartment: "" });
const sla = reactive({ total: 188, dispatch: 60, firstContact: 60, preliminary: 120, investigation: 180, review: 60, callback: 120, report: 240 });

const currentRole = computed(() => roles.find((role) => role.id === currentRoleId.value) || roles[0]);
const visibleMicroApps = computed(() => {
  const keyword = appSearch.value.trim();
  return keyword ? microApps.filter((app) => app.name.includes(keyword) || app.description.includes(keyword)) : microApps;
});
const navItems = computed(() => {
  if (currentRoleId.value === "supervisor") {
    return [
      { id: "import", label: "工单导入", icon: ImportOutlined },
      { id: "query", label: "工单查询", icon: DatabaseOutlined },
      { id: "tasks", label: "工单处理", icon: FormOutlined },
      { id: "rules", label: "规则配置", icon: SlidersOutlined, children: [{ id: "smart-rules", label: "智能派工规则配置" }, { id: "rules", label: "流程时限管理" }] },
      { id: "analytics", label: "统计分析", icon: BarChartOutlined },
    ];
  }
  return [
    { id: "query", label: "工单查询", icon: DatabaseOutlined },
    { id: "tasks", label: "待办工单", icon: FormOutlined },
  ];
});
const pageTitle = computed(() => ({
  import: "12398 工单导入",
  "import-preview": "12398 工单导入",
  "import-history": "12398 工单导入",
  query: "工单查询",
  tasks: currentRoleId.value === "supervisor" ? "工单处理" : "待办工单",
  dispatch: "派单处理",
  detail: "工单详情",
  investigation: "工单处理",
  callback: "工单处理",
  report: "工单处理",
  deliverable: "工单处理",
  "review-detail": "工单处理",
  "callback-assignment": "回访分配",
  "smart-rules": "智能派工规则配置",
  rules: "流程时限管理",
  analytics: "统计分析",
}[currentPage.value] || "工单处理"));
const investigationSubmitReady = computed(() => {
  if (currentRoleId.value !== "officer") return true;
  const preliminaryReady = selectedOrder.value.preliminaryCompletedCount >= selectedOrder.value.preliminaryRequired;
  if (selectedOrder.value.responsibilityType === "协查") return preliminaryReady;
  return selectedOrder.value.firstContactCompleted && preliminaryReady;
});
const preliminaryProgressText = computed(() => `${selectedOrder.value.preliminaryCompletedCount || 0}/${selectedOrder.value.preliminaryRequired || 1}`);
const taskPages = ["dispatch", "detail", "investigation", "callback", "report", "deliverable", "review-detail", "callback-assignment"];
const summaryIcon = (label) => label.includes("待") ? ClockCircleOutlined : label.includes("完成") ? CheckCircleFilled : label.includes("报告") || label.includes("成果") ? FileDoneOutlined : AppstoreOutlined;

const filteredOrders = computed(() => workOrders.filter((order) => {
  return (!filters.no || order.no.includes(filters.no))
    && (!filters.stage || order.stage === filters.stage)
    && (!filters.source || order.source === filters.source)
    && (!filters.calledAt || order.calledAt === filters.calledAt)
    && (!filters.transferredAt || order.transferredAt === filters.transferredAt)
    && (!filters.customer || order.customerName.includes(filters.customer))
    && (!filters.phone || order.phone.includes(filters.phone))
    && (!filters.address || order.address.includes(filters.address))
    && (!filters.region || order.region.includes(filters.region))
    && (!filters.province || order.province === filters.province)
    && (!filters.eventType || order.eventType === filters.eventType)
    && (!filters.transferCategory || order.transferCategory === filters.transferCategory)
    && (!filters.problemCategory || order.problemCategory === filters.problemCategory);
}));

const taskOrders = computed(() => {
  const source = filteredOrders.value;
  if (!activeTaskType.value && currentRoleId.value === "business-director") return source.filter((order) => order.stage === "待业务部主任审核");
  if (!activeTaskType.value || activeTaskType.value === "任务总数") return source;
  if (activeTaskType.value === "待审核") {
    const stage = currentRoleId.value === "business-director" ? "待业务部主任审核" : "待审核";
    return source.filter((order) => order.stage === stage);
  }
  const stageMap = {
    "待分配派工": ["待分配派工"], "已分派完成": ["事件调查", "首联与多部门并行初查", "多部门并行事件初查"],
    "调查结果填报": ["事件调查", "调查结果填报", "首联与多部门并行初查", "多部门并行事件初查"], "调查报告编写": ["调查报告编写"], "回访结果填报": ["回访结果填报"], "成果物输出": ["成果物输出"], "已完成": ["已办结"],
    "首联分派": ["首联分派", "首联与多部门并行初查"], "待调查": ["事件调查", "多部门并行事件初查", "首联与多部门并行初查"], "回访分派": ["回访分派"], "待首联": ["首联分派", "首联与多部门并行初查"],
  };
  const stages = stageMap[activeTaskType.value];
  return stages ? source.filter((order) => stages.includes(order.stage)) : source;
});

function login() {
  loginLoading.value = true;
  window.setTimeout(() => {
    loginLoading.value = false;
    loggedIn.value = true;
    currentApp.value = "";
    notify("登录成功，欢迎进入风险防控处置系统");
  }, 450);
}

function enterApp(app) {
  if (!app.available) {
    notify(`${app.name}即将接入`);
    return;
  }
  currentApp.value = app.id;
  currentPage.value = "tasks";
  activeTaskType.value = "";
  notify(`已进入${app.name}`);
}

function returnToWorkbench() {
  currentApp.value = "";
  showRoleMenu.value = false;
  showNotice.value = false;
}

function logout() {
  currentApp.value = "";
  loggedIn.value = false;
  showRoleMenu.value = false;
  showNotice.value = false;
}

function notify(message) {
  toast.value = message;
  window.setTimeout(() => { if (toast.value === message) toast.value = ""; }, 2400);
}

function changeRole(roleId) {
  currentRoleId.value = roleId;
  currentPage.value = "tasks";
  activeTaskType.value = "";
  showRoleMenu.value = false;
  notify(`已切换为${currentRole.value.name}视角`);
}

function go(page) {
  currentPage.value = page;
  activeTaskType.value = "";
}

function resetFilters() {
  Object.assign(filters, { no: "", stage: "", source: "", calledAt: "", transferredAt: "", customer: "", phone: "", address: "", region: "", province: "", eventType: "", transferCategory: "", problemCategory: "" });
  activeTaskType.value = "";
}

function openOrder(order, action = "detail") {
  selectedOrder.value = order;
  if (action === "dispatch") currentPage.value = "dispatch";
  else if (action === "callback-assignment") currentPage.value = "callback-assignment";
  else if (action === "assign") {
    assignmentMode.value = activeTaskType.value.includes("回访") || order.stage.includes("回访") ? "callback" : "first-contact";
    showAssignment.value = true;
  }
  else if (action === "review") {
    reviewForm.result = "";
    reviewForm.reason = "";
    reviewForm.callbackDepartment = "";
    showReview.value = true;
  }
  else if (action === "handle" && currentRoleId.value === "officer" && activeTaskType.value.includes("回访")) currentPage.value = "callback";
  else if (action === "handle" && currentRoleId.value === "officer" && activeTaskType.value.includes("报告")) currentPage.value = "report";
  else if (action === "handle" && currentRoleId.value === "officer" && activeTaskType.value.includes("成果")) currentPage.value = "deliverable";
  else if (action === "handle") currentPage.value = "investigation";
  else currentPage.value = "detail";
}

function primaryAction(order) {
  if (activeTaskType.value === "已完成") return "detail";
  if (currentRoleId.value === "supervisor") return order.stage === "待审核" ? "review" : order.stage === "待回访分配" ? "callback-assignment" : "dispatch";
  if (currentRoleId.value === "customer-manager") return activeTaskType.value === "待调查" || order.stage.includes("调查") || order.stage.includes("初查") ? "handle" : "assign";
  if (currentRoleId.value === "business-director") return "review";
  return "handle";
}

function primaryActionLabel(order) {
  if (activeTaskType.value === "已完成") return "查看";
  if (currentRoleId.value === "supervisor") return order.stage === "待审核" ? "审核" : order.stage === "待回访分配" ? "回访分配" : "派工";
  if (currentRoleId.value === "customer-manager") return activeTaskType.value === "待调查" || order.stage.includes("调查") || order.stage.includes("初查") ? "处理" : activeTaskType.value.includes("回访") || order.stage.includes("回访") ? "回访分派" : "首联分派";
  if (currentRoleId.value === "business-director") return "审核";
  return "处理";
}

function confirmDispatch() {
  if (!dispatchForm.preliminaryDepartments.length || !dispatchForm.supervisor) {
    notify("请选择初查部门和服务监督员");
    return;
  }
  if (dispatchForm.responsibilityType === "主责" && !dispatchForm.firstContactDepartment) {
    notify("主责工单必须选择首联部门");
    return;
  }
  selectedOrder.value.responsibilityType = dispatchForm.responsibilityType;
  selectedOrder.value.firstContactCompleted = false;
  selectedOrder.value.preliminaryCompleted = false;
  selectedOrder.value.preliminaryRequired = dispatchForm.preliminaryDepartments.length;
  selectedOrder.value.preliminaryCompletedCount = 0;
  selectedOrder.value.preliminarySubmittedBy = [];
  selectedOrder.value.stage = dispatchForm.responsibilityType === "协查" ? "多部门并行事件初查" : "首联与多部门并行初查";
  notify(`${dispatchForm.responsibilityType}工单派发成功，监督员已可先行填报调查草稿`);
  currentPage.value = "tasks";
}

function saveDraft() {
  notify("草稿已保存；前置任务完成后可提交全面调查");
}

function submitForm() {
  if (!investigationSubmitReady.value) {
    notify(selectedOrder.value.responsibilityType === "协查" ? "全部初查尚未完成，当前只能保存调查草稿" : "首联或初查尚未全部完成，当前只能保存调查草稿");
    return;
  }
  if (currentRoleId.value === "team-leader") selectedOrder.value.firstContactCompleted = true;
  if (["operation", "duty-manager", "customer-manager"].includes(currentRoleId.value)) {
    const submitted = selectedOrder.value.preliminarySubmittedBy || (selectedOrder.value.preliminarySubmittedBy = []);
    if (!submitted.includes(currentRoleId.value)) {
      submitted.push(currentRoleId.value);
      selectedOrder.value.preliminaryCompletedCount = Math.min(selectedOrder.value.preliminaryRequired, (selectedOrder.value.preliminaryCompletedCount || 0) + 1);
    }
    selectedOrder.value.preliminaryCompleted = selectedOrder.value.preliminaryCompletedCount >= selectedOrder.value.preliminaryRequired;
  }
  if (currentRoleId.value === "officer") selectedOrder.value.stage = "待审核";
  const submitMessage = currentRoleId.value === "team-leader" ? "首联信息已提交" : currentRoleId.value === "officer" ? "调查结果已提交服务监督主管审核" : `初查内容已提交，当前进度 ${preliminaryProgressText.value}`;
  notify(submitMessage);
  currentPage.value = "tasks";
}

function confirmReview() {
  if (!reviewForm.result) {
    notify("请选择审核结果");
    return;
  }
  if (reviewForm.result === "不同意" && !reviewForm.reason.trim()) {
    notify("审核不同意时必须填写驳回理由");
    return;
  }
  const isAssist = selectedOrder.value.responsibilityType === "协查";
  if (reviewForm.result === "同意" && !isAssist && !reviewForm.callbackDepartment) {
    notify("主责工单审核通过时请选择回访部门");
    return;
  }
  showReview.value = false;
  if (currentRoleId.value === "supervisor") {
    selectedOrder.value.stage = reviewForm.result === "同意" ? "待业务部主任审核" : "调查结果填报";
    notify(reviewForm.result === "同意" ? "服务监督主管审核通过，进入业务部主任审核" : "已驳回至调查结果填报");
    currentPage.value = "tasks";
    activeTaskType.value = "待审核";
    return;
  }
  const branch = isAssist ? "直接进入 11 调查报告编写" : "进入回访分配";
  if (reviewForm.result === "同意") selectedOrder.value.stage = isAssist ? "调查报告编写" : "待回访分配";
  else selectedOrder.value.stage = "调查结果填报";
  notify(reviewForm.result === "同意" ? `审核通过，${branch}` : "已驳回至调查结果填报");
  currentPage.value = "tasks";
  activeTaskType.value = "待审核";
}

function openFullReview() {
  showReview.value = false;
  currentPage.value = "review-detail";
}

function previewImport(event) {
  const file = event.target.files?.[0];
  if (!file) return;
  importFileName.value = file.name;
  importPreview.value = true;
  currentPage.value = "import-preview";
  notify("文件解析完成，请核对预览数据");
}

function submitCallback() {
  if (investigationForm.callbackResult !== "同意" && (!callbackUploads.replyLetter || !callbackUploads.deliveryProof)) {
    notify("请完整上传答复书和送达凭证");
    return;
  }
  selectedOrder.value.stage = "调查报告编写";
  notify("回访结果已提交，进入调查报告编写");
  currentPage.value = "tasks";
}

function generateReport() {
  reportForm.summary = investigationForm.customerAppealSummary;
  reportForm.rootCause = "经核查，客户所在台区在负荷波动时段出现短时电压偏差。";
  reportForm.measures = investigationForm.handlingMethod;
  reportForm.conclusion = investigationForm.handlingResult;
  notify("已生成报告草稿，可继续编辑");
}

function submitReport() {
  selectedOrder.value.stage = "成果物输出";
  notify("调查报告已生成并下载，进入成果物输出");
  currentPage.value = "tasks";
}

function finishOrder() {
  selectedOrder.value.stage = "已办结";
  selectedOrder.value.status = "已结束";
  notify("成果物已提交，工单已办结");
  currentPage.value = "tasks";
}

function addMockDeliverable() {
  const next = `补充成果物-${deliverableFiles.value.length + 1}.pdf`;
  deliverableFiles.value.push(next);
  notify(`${next} 上传成功`);
}
</script>

<template>
  <div v-if="!loggedIn" class="login-screen">
    <section class="login-panel">
      <div class="login-heading">
        <div class="login-kicker">智慧客服引领 <span>未来客服革命</span></div>
        <p>提升效率，推动智能客服持续发展</p>
      </div>
      <form class="login-card" @submit.prevent="login">
        <h1>欢迎登录 风险防控处置系统</h1>
        <label class="login-field"><input v-model="loginForm.username" placeholder="请输入您的账号" /></label>
        <label class="login-field"><input v-model="loginForm.password" type="password" placeholder="请输入您的密码" /></label>
        <div class="captcha-row">
          <label class="login-field"><input v-model="loginForm.code" placeholder="请输入验证码" /></label>
          <button class="captcha" type="button">TB5K</button>
        </div>
        <button class="login-button" :disabled="loginLoading">{{ loginLoading ? "正在登录…" : "登录" }}</button>
      </form>
    </section>
  </div>

  <div v-else-if="!currentApp" class="portal-shell">
    <header class="portal-header">
      <div class="portal-brand"><SafetyCertificateFilled /><strong>风险防控处置系统</strong></div>
      <div class="portal-header-spacer"></div>
      <div class="clock"><span>2026年08月08日</span><strong>09:48:16</strong></div>
      <div class="divider"></div>
      <div class="role-switcher">
        <button class="role-button" @click="showRoleMenu = !showRoleMenu"><span>您好，</span><strong>{{ currentRole.name }}</strong><DownOutlined /></button>
        <div v-if="showRoleMenu" class="role-menu portal-role-menu">
          <button v-for="role in roles" :key="role.id" :class="{ active: role.id === currentRoleId }" @click="changeRole(role.id)">{{ role.name }}</button>
          <button class="logout" @click="logout"><LogoutOutlined />退出登录</button>
        </div>
      </div>
      <button class="icon-button"><UserOutlined /></button>
      <button class="icon-button notice-button" @click="showNotice = !showNotice"><BellFilled /><i></i></button>
      <button class="icon-button"><SettingFilled /></button>
      <div v-if="showNotice" class="notice-popover portal-notice"><strong>待办提醒</strong><p>您有 47 条工单待处理</p><p>进入 12398 工单系统查看详情</p></div>
    </header>

    <main class="portal-content">
      <section class="portal-intro">
        <div><h1>上午好，{{ currentRole.name }}</h1><p>选择一个应用开始今天的工作</p></div>
        <label class="portal-search"><SearchOutlined /><input v-model="appSearch" placeholder="搜索应用名称" /></label>
      </section>

      <section class="portal-section">
        <h2>最近使用</h2>
        <button class="recent-app" @click="enterApp(microApps[0])">
          <span class="portal-app-icon"><FormOutlined /></span>
          <span class="recent-copy"><strong>12398 工单系统</strong><em>受理与处理客户工单，跟踪进度，提升服务效率</em></span>
          <span class="recent-todo"><em>今日待办</em><strong>47</strong></span>
          <span class="portal-enter outline">进入应用</span><RightOutlined class="recent-arrow" />
        </button>
      </section>

      <section class="portal-section all-apps-section">
        <h2>全部应用</h2>
        <div v-if="visibleMicroApps.length" class="micro-app-grid">
          <button v-for="app in visibleMicroApps" :key="app.id" class="micro-app-card" :class="{ disabled: !app.available }" @click="enterApp(app)">
            <span class="portal-app-icon"><component :is="app.icon" /></span>
            <span class="micro-app-copy"><span><strong>{{ app.name }}</strong><i :class="{ available: app.available }">{{ app.status }}</i></span><em>{{ app.description }}</em></span>
            <span class="micro-app-action">{{ app.available ? '进入应用' : '即将接入' }} <RightOutlined v-if="app.available" /></span>
          </button>
        </div>
        <div v-else class="portal-empty">没有找到匹配的应用</div>
      </section>
    </main>

    <footer class="portal-footer"><SafetyCertificateFilled /><span>统一身份认证与权限管理保障应用访问安全合规</span><i></i><button>了解更多 <RightOutlined /></button></footer>
    <transition name="toast"><div v-if="toast" class="toast"><CheckCircleFilled />{{ toast }}</div></transition>
  </div>

  <div v-else class="app-shell">
    <aside class="sidebar">
      <button class="brand app-home-return" title="返回应用工作台" @click="returnToWorkbench"><SafetyCertificateFilled /><strong>风险防控处置系统</strong></button>
      <nav class="main-nav">
        <div v-for="item in navItems" :key="item.id" class="nav-block">
          <button class="nav-item" :class="{ active: currentPage === item.id || (item.id === 'tasks' && taskPages.includes(currentPage)) || (item.id === 'import' && currentPage.startsWith('import-')) || (item.id === 'rules' && currentPage === 'smart-rules') }" @click="go(item.id)">
            <component :is="item.icon" />
            <span>{{ item.label }}</span>
            <DownOutlined v-if="item.children" class="nav-arrow expanded" />
            <RightOutlined v-else class="nav-arrow" />
          </button>
          <div v-if="item.children" class="sub-nav">
            <button :class="{ active: currentPage === child.id }" v-for="child in item.children" :key="child.id" @click="go(child.id)">{{ child.label }}</button>
          </div>
        </div>
      </nav>
      <div class="sidebar-foot">Mock 原型 · V0.1</div>
    </aside>

    <section class="app-main">
      <header class="topbar">
        <button class="icon-button ghost"><MenuFoldOutlined /></button>
        <div class="topbar-spacer"></div>
        <div class="clock"><span>2026年08月08日</span><strong>09:48:16</strong></div>
        <div class="divider"></div>
        <div class="role-switcher">
          <button class="role-button" @click="showRoleMenu = !showRoleMenu">
            <span>您好，</span><strong>{{ currentRole.name }}</strong><DownOutlined />
          </button>
          <div v-if="showRoleMenu" class="role-menu">
            <button v-for="role in roles" :key="role.id" :class="{ active: role.id === currentRoleId }" @click="changeRole(role.id)">{{ role.name }}</button>
            <button class="logout" @click="logout"><LogoutOutlined />退出登录</button>
          </div>
        </div>
        <button class="icon-button"><UserOutlined /></button>
        <button class="icon-button notice-button" @click="showNotice = !showNotice"><BellFilled /><i></i></button>
        <button class="icon-button"><SettingFilled /></button>
        <div v-if="showNotice" class="notice-popover">
          <strong>待办提醒</strong>
          <p>有 22 条工单等待分配派工</p>
          <p>有 11 条工单等待回访分配</p>
        </div>
      </header>

      <main class="workspace">
        <section class="page-card">
          <div class="page-heading">
            <h1>{{ pageTitle }}</h1>
            <button v-if="taskPages.includes(currentPage)" class="outline-button" @click="go('tasks')"><LeftOutlined />返回列表</button>
          </div>

          <template v-if="currentPage === 'import'">
            <section class="import-box import-main">
              <div class="section-title">12398 工单导入</div>
              <div class="form-row"><label>导入方式</label><select class="field"><option>Excel / CSV文件导入</option></select></div>
              <div class="form-row"><label>导入批次</label><input class="field" value="20260806-B01" /></div>
              <div class="file-drop"><CloudUploadOutlined /><div><strong>{{ importFileName || '将文件拖拽到此处，或点击选择文件' }}</strong><span>支持 Excel、CSV，单个文件不超过20MB</span></div><input type="file" accept=".xlsx,.xls,.csv" @change="previewImport" /></div>
              <div class="button-row"><button class="outline-button" @click="go('import-history')">导入明细</button><button class="primary-button" @click="go('import-preview')">导入预览</button></div>
            </section>
          </template>

          <template v-else-if="currentPage === 'import-preview'">
            <section class="preview-panel"><div class="section-title"><span>导入预览</span><button class="text-button" @click="go('import')"><CloseOutlined />返回导入</button></div><OrderTable :orders="workOrders.slice(0,8)" :readonly="true" @open="openOrder" /><div class="button-row"><button class="outline-button" @click="go('import')">取消</button><button class="primary-button" @click="notify('确认导入成功，共生成 18 条工单'); go('import-history')">确认导入</button></div></section>
          </template>

          <template v-else-if="currentPage === 'import-history'">
            <section class="preview-panel"><div class="section-title"><span>导入明细</span><button class="text-button" @click="go('import')"><LeftOutlined />返回导入</button></div><table class="data-table compact"><thead><tr><th>序号</th><th>导入时间</th><th>导入批次</th><th>导入条数</th><th>导入人员</th></tr></thead><tbody><tr v-for="batch in importBatches" :key="batch.id"><td>{{ batch.id }}</td><td>{{ batch.importedAt }}</td><td>{{ batch.batchNo }}</td><td>{{ batch.count }}</td><td>{{ batch.importedBy }}</td></tr></tbody></table></section>
          </template>

          <template v-else-if="currentPage === 'query'">
            <FilterPanel v-model="filters" @reset="resetFilters" />
            <div class="section-title">工单详情 <span class="result-count">共 {{ filteredOrders.length }} 条</span></div>
            <OrderTable :orders="filteredOrders" :readonly="true" @open="openOrder" />
          </template>

          <template v-else-if="currentPage === 'tasks'">
            <div class="summary-grid">
              <button v-for="item in taskSummary[currentRoleId]" :key="item[0]" :class="{ active: activeTaskType === item[0] }" @click="activeTaskType = activeTaskType === item[0] ? '' : item[0]">
                <span class="summary-icon"><component :is="summaryIcon(item[0])" /></span><span class="summary-copy"><span>{{ item[0] }}</span><strong>{{ item[1] }}</strong><em>条</em></span>
              </button>
            </div>
            <FilterPanel v-model="filters" simple @reset="resetFilters" />
            <OrderTable :orders="taskOrders.slice(0,8)" :action-label="primaryActionLabel" @open="openOrder" @action="(order) => openOrder(order, primaryAction(order))" />
          </template>

          <template v-else-if="taskPages.includes(currentPage)">
            <OrderContext :order="selectedOrder" :records="serviceRecords" v-model:expanded="transcriptExpanded" />

            <section v-if="currentPage === 'dispatch'" class="detail-section form-section">
              <div class="section-title">派单选择信息</div>
              <div class="wide-form">
                <div class="form-row"><label>责任类型</label><div class="radio-group"><label><input v-model="dispatchForm.responsibilityType" type="radio" value="主责" />主责</label><label><input v-model="dispatchForm.responsibilityType" type="radio" value="协查" />协查</label></div></div>
                <div class="form-row"><label>派工主体</label><div class="static-value">服务监督主管</div></div>
                <div class="flow-tip"><NotificationFilled /><span v-if="dispatchForm.responsibilityType === '协查'">协查派工后直接进入 <strong>04 多部门并行事件初查</strong>；服务监督员可先行填报调查草稿，全部初查完成后方可提交。</span><span v-else>主责派工后同步进入首联和 <strong>04 多部门并行事件初查</strong>；服务监督员可先行填报调查草稿，首联及全部初查完成后方可提交。</span></div>
                <div class="form-row"><label>初查部门</label><div class="checkbox-select"><label v-for="dept in dictionary.departments" :key="dept"><input v-model="dispatchForm.preliminaryDepartments" type="checkbox" :value="dept" />{{ dept }}</label></div></div>
                <div v-if="dispatchForm.responsibilityType === '主责'" class="form-row"><label>首联部门</label><select v-model="dispatchForm.firstContactDepartment" class="field"><option v-for="dept in dictionary.firstContactDepartments" :key="dept">{{ dept }}</option></select></div>
                <div class="form-row"><label>服务监督员</label><select v-model="dispatchForm.supervisor" class="field"><option v-for="person in dictionary.supervisors" :key="person">{{ person }}</option></select></div>
                <div class="form-row"><label>提级督办</label><div class="checkbox-select"><label v-for="dept in dictionary.departments" :key="dept"><input v-model="dispatchForm.escalationDepartments" type="checkbox" :value="dept" />{{ dept }}</label></div></div>
              </div>
              <div class="button-row"><button class="outline-button" @click="go('tasks')">取消</button><button class="primary-button" @click="confirmDispatch">确认派发</button></div>
            </section>

            <section v-else-if="currentPage === 'investigation'" class="detail-section form-section">
              <div v-if="currentRoleId === 'team-leader'" class="wide-form">
                <div class="section-title">首联信息</div>
                <div class="form-row"><label>首联时间</label><input v-model="investigationForm.firstContactAt" class="field" type="datetime-local" /></div>
                <div class="form-row"><label>首联工单号</label><input v-model="investigationForm.firstContactNo" class="field" placeholder="请输入首联工单号" /></div>
                <div class="form-row"><label>首联内容</label><textarea v-model="investigationForm.firstContactContent" class="field" placeholder="请填写首联内容"></textarea></div>
              </div>
              <div v-else-if="['operation','duty-manager','customer-manager'].includes(currentRoleId)" class="wide-form">
                <div class="section-title">处置信息填写</div>
                <div class="form-row"><label>初查内容</label><textarea v-model="investigationForm.preliminaryContent" class="field large" placeholder="请输入初查内容"></textarea></div>
              </div>
              <InvestigationFields v-else :form="investigationForm" show-tip show-imported-content :progress-text="preliminaryProgressText" :show-first-contact="selectedOrder.responsibilityType === '主责'" />
              <div class="button-row"><button v-if="currentRoleId === 'officer'" class="outline-button" @click="saveDraft">保存草稿</button><button class="primary-button" :disabled="!investigationSubmitReady" @click="submitForm">{{ investigationSubmitReady ? '确认提交' : '等待前置任务完成' }}</button></div>
            </section>

            <section v-else-if="currentPage === 'callback'" class="detail-section form-section">
              <InvestigationFields :form="investigationForm" readonly :show-first-contact="selectedOrder.responsibilityType === '主责'" />
              <div class="wide-form">
                <div class="section-title">回访结果</div>
                <div class="form-row"><label>回复人</label><input v-model="investigationForm.respondentName" class="field" /></div>
                <div class="form-row"><label>回复时间</label><input v-model="investigationForm.repliedAt" class="field" /></div>
                <div class="form-row"><label>回复电话号码</label><input v-model="investigationForm.replyPhone" class="field" /></div>
                <div class="form-row"><label>回复情况</label><textarea v-model="investigationForm.replySituation" class="field" placeholder="请填写回复情况"></textarea></div>
                <div class="form-row"><label>回访结果</label><select v-model="investigationForm.callbackResult" class="field"><option>同意</option><option>不同意或客户主动要求</option></select></div>
                <div v-if="investigationForm.callbackResult !== '同意'" class="inline-callback-files">
                  <div class="upload-file-row"><strong>上传答复书</strong><button class="upload-square" :class="{ uploaded: callbackUploads.replyLetter }" @click="callbackUploads.replyLetter = true"><CloudUploadOutlined /></button><button class="upload-file-name" @click="callbackUploads.replyLetter = true">{{ callbackUploads.replyLetter ? '客户答复书.pdf' : '点击选择答复书' }}</button></div>
                  <div class="upload-file-row"><strong>上传送达凭证</strong><button class="upload-square" :class="{ uploaded: callbackUploads.deliveryProof }" @click="callbackUploads.deliveryProof = true"><CloudUploadOutlined /></button><button class="upload-file-name" @click="callbackUploads.deliveryProof = true">{{ callbackUploads.deliveryProof ? '送达凭证.jpg' : '点击选择送达凭证' }}</button></div>
                </div>
              </div>
              <div class="button-row"><button class="outline-button" @click="go('tasks')">取消</button><button class="primary-button" @click="submitCallback">确认审核</button></div>
            </section>

            <section v-else-if="currentPage === 'report'" class="detail-section form-section">
              <InvestigationFields :form="investigationForm" readonly :show-first-contact="selectedOrder.responsibilityType === '主责'" />
              <div class="wide-form">
                <div class="form-row"><label>回复人</label><input v-model="investigationForm.respondentName" class="field" readonly /></div>
                <div class="form-row"><label>回复时间</label><input v-model="investigationForm.repliedAt" class="field" readonly /></div>
                <div class="form-row"><label>回复电话号码</label><input v-model="investigationForm.replyPhone" class="field" readonly /></div>
                <div class="form-row"><label>回复情况</label><textarea v-model="investigationForm.replySituation" class="field" readonly placeholder="请填写回复情况"></textarea></div>
                <div class="form-row"><label>回访结果</label><select v-model="investigationForm.callbackResult" class="field"><option>同意</option><option>不同意或客户主动要求</option></select></div>
                <div v-if="investigationForm.callbackResult !== '同意'" class="inline-callback-files">
                  <div class="upload-file-row"><strong>上传答复书</strong><button class="upload-square uploaded"><CloudUploadOutlined /></button><button class="upload-file-name">客户答复书.pdf</button></div>
                  <div class="upload-file-row"><strong>上传送达凭证</strong><button class="upload-square uploaded"><CloudUploadOutlined /></button><button class="upload-file-name">送达凭证.jpg</button></div>
                </div>
              </div>
              <div class="button-row"><button class="outline-button" @click="go('tasks')">取消</button><button class="primary-button" @click="submitReport">确认下载</button></div>
            </section>

            <section v-else-if="currentPage === 'deliverable'" class="detail-section form-section">
              <InvestigationFields :form="investigationForm" readonly :show-first-contact="selectedOrder.responsibilityType === '主责'" />
              <div class="wide-form">
                <div class="section-title">成果物清单</div>
                <div class="deliverable-list"><article v-for="(file,index) in deliverableFiles" :key="file"><FileDoneOutlined /><div><strong>{{ file }}</strong><span>2026-08-11 16:2{{ index }} · 监督员A（张某）</span></div><button class="text-button" @click="deliverableFiles.splice(index,1)">移除</button></article><button class="add-deliverable" @click="addMockDeliverable"><CloudUploadOutlined /><span>上传成果物</span></button></div>
                <div class="tip"><CheckCircleFilled />报告及必备成果物齐全，确认提交后工单进入办结校验。</div>
              </div>
              <div class="button-row"><button class="outline-button" @click="go('tasks')">取消</button><button class="primary-button" @click="finishOrder">确认提交并办结</button></div>
            </section>

            <section v-else-if="currentPage === 'review-detail'" class="detail-section form-section">
              <InvestigationFields :form="investigationForm" readonly :show-first-contact="selectedOrder.responsibilityType === '主责'" />
              <div class="wide-form review-actions"><div class="section-title">审核意见</div><div class="form-row"><label>审核结果</label><div class="radio-group"><label><input v-model="reviewForm.result" type="radio" value="同意" />同意</label><label><input v-model="reviewForm.result" type="radio" value="不同意" />不同意</label></div></div><div class="form-row"><label>审核意见</label><textarea v-model="reviewForm.reason" class="field" placeholder="请输入审核意见"></textarea></div><div class="branch-tip"><NotificationFilled /><span v-if="currentRoleId === 'supervisor'">服务监督主管审核通过后进入业务部主任审核。</span><span v-else>业务部主任审核通过后：主责进入回访，协查直接进入调查报告编写。</span></div></div>
              <div class="button-row"><button class="outline-button" @click="go('tasks')">取消</button><button class="primary-button" @click="confirmReview">确认审核</button></div>
            </section>

            <section v-else-if="currentPage === 'callback-assignment'" class="detail-section form-section">
              <div class="wide-form"><div class="section-title">回访分配</div><div class="form-row"><label>回访部门</label><select v-model="assignmentForm.department" class="field"><option v-for="dept in dictionary.firstContactDepartments" :key="dept">{{ dept }}</option></select></div></div><div class="button-row"><button class="outline-button" @click="go('tasks')">取消</button><button class="primary-button" @click="selectedOrder.stage = '回访分派'; notify('回访部门分配成功'); go('tasks')">确认派发</button></div>
            </section>
          </template>

          <template v-else-if="currentPage === 'rules'">
            <div class="rules-layout single"><section class="sla-card"><div class="section-title">环节时限配置</div><div class="total-limit"><span>整体时限</span><input v-model="sla.total" type="number" /><em>分钟</em></div><div class="sla-grid"><label>办理派工<input v-model="sla.dispatch" type="number" /><span>分钟</span></label><label>首联<input v-model="sla.firstContact" type="number" /><span>分钟</span></label><label>事件调查<input v-model="sla.preliminary" type="number" /><span>分钟</span></label><label>调查结果<input v-model="sla.investigation" type="number" /><span>分钟</span></label><label>调查审核<input v-model="sla.review" type="number" /><span>分钟</span></label><label>回访<input v-model="sla.callback" type="number" /><span>分钟</span></label><label>调查报告<input v-model="sla.report" type="number" /><span>分钟</span></label></div><div class="button-row"><button class="outline-button">取消</button><button class="primary-button" @click="notify('流程时限配置已保存')">保存时限</button></div></section></div>
          </template>

          <template v-else-if="currentPage === 'smart-rules' || currentPage === 'analytics'"><div class="prototype-blank"></div></template>
        </section>
      </main>
    </section>

    <div v-if="showAssignment" class="modal-mask" @click.self="showAssignment = false"><section class="modal assignment-modal"><button class="modal-close" @click="showAssignment = false"><CloseOutlined /></button><h2>{{ assignmentMode === 'callback' ? '回访分派' : '首联分派' }}</h2><div class="modal-inner-panel"><div class="section-title">分派选择信息</div><div class="form-row"><label>班组</label><select v-model="assignmentForm.member" class="field"><option value="" disabled>请选择班组/人员</option><option v-for="person in dictionary.teamMembers" :key="person">{{ person }}</option></select></div></div><div class="button-row"><button class="outline-button" @click="showAssignment = false">取消</button><button class="primary-button" @click="showAssignment = false; selectedOrder.stage = assignmentMode === 'callback' ? '回访结果填报' : '首联分派'; notify('分派成功')">确认分派</button></div></section></div>

    <div v-if="showReview" class="modal-mask" @click.self="showReview = false"><section class="modal review-modal-v2"><button class="modal-close" @click="showReview = false"><CloseOutlined /></button><h2>审核工单信息</h2><div class="modal-inner-panel"><div class="section-title">审核结果</div><div class="form-row"><label>审核结果</label><select v-model="reviewForm.result" class="field"><option value="" disabled>请选择审核结果（同意/不同意）</option><option>同意</option><option>不同意</option></select></div><div class="section-title">驳回理由</div><textarea v-model="reviewForm.reason" class="field review-reason" placeholder="请输入驳回理由"></textarea><template v-if="selectedOrder.responsibilityType === '主责'"><div class="section-title">回访分派</div><div class="form-row"><label>回访分派</label><select v-model="reviewForm.callbackDepartment" class="field"><option value="" disabled>选择部门（单选）</option><option v-for="dept in dictionary.firstContactDepartments" :key="dept">{{ dept }}</option></select></div></template><div v-if="currentRoleId === 'business-director' && selectedOrder.responsibilityType === '协查'" class="branch-tip"><NotificationFilled />协查工单审核通过后直接进入 11 调查报告编写。</div></div><div class="button-row"><button class="outline-button" @click="showReview = false">取消</button><button class="primary-button" @click="confirmReview">确认审核</button></div></section></div>

    <transition name="toast"><div v-if="toast" class="toast"><CheckCircleFilled />{{ toast }}</div></transition>
  </div>
</template>
