WXL (wul)
2026-11-09 b4fe2c16274a91fee4fb26d91374f95fbe2dbcec
src/views/Satisfaction/sfstatistics/components/FollowupStatistics.vue
@@ -136,15 +136,19 @@
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :row-key="getRowKey"
        show-summary
        :summary-method="getSummaries"
      >
        <!-- 病区列 -->
        <el-table-column
          v-if="queryParams.statisticaltype == 1"
          label="出院病区"
          align="center"
          sortable
          key="leavehospitaldistrictname"
          prop="leavehospitaldistrictname"
          :show-overflow-tooltip="true"
          :sort-method="sortChineseNumber"
          min-width="120"
        />
@@ -191,14 +195,20 @@
          min-width="100"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.followUpRate !== null && scope.row.followUpRate !== undefined">
              {{ formatPercent(scope.row.followUpRate) }}
            <span
              v-if="
                scope.row.followUpRate !== null &&
                scope.row.followUpRate !== undefined
              "
            >
              {{ scope.row.followUpRate }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="orgname == '景宁畲族自治县人民医院'"
          label="及时率"
          align="center"
          key="rate"
@@ -241,24 +251,20 @@
          min-width="100"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.joyTotal !== null && scope.row.joyTotal !== undefined">
            <span
              v-if="
                scope.row.joyTotal !== null && scope.row.joyTotal !== undefined
              "
            >
              {{ formatPercent(scope.row.joyTotal) }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          width="120"
        >
        <el-table-column label="操作" align="center" fixed="right" width="120">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="getinfo(scope.row)"
            >
            <el-button type="text" @click="getinfo(scope.row)">
              <i class="el-icon-s-order" style="margin-right: 4px"></i>
              查看详情
            </el-button>
@@ -303,16 +309,23 @@
      :close-on-click-modal="false"
    >
      <template #title>
        <div style="display: flex; align-items: center;">
          <i class="el-icon-s-data" style="margin-right: 8px; color: #409EFF;"></i>
        <div style="display: flex; align-items: center">
          <i
            class="el-icon-s-data"
            style="margin-right: 8px; color: #409eff"
          ></i>
          <span>{{ topicvalue.name }}</span>
          <span style="margin-left: 10px; color: #666; font-size: 14px;">满意度指标详情</span>
          <span style="margin-left: 10px; color: #666; font-size: 14px"
            >满意度指标详情</span
          >
        </div>
      </template>
      <topic-dialog
        v-if="topicVisible"
        :row-data="currentRow"
        :topicList="topiclist"
        :query-params="queryParams"
        :topType="2"
        @close="topicVisible = false"
      />
    </el-dialog>
@@ -320,35 +333,39 @@
</template>
<script>
import { getSfStatisticsJoy, getSfStatisticsJoyInfo, selectTimelyRate } from "@/api/system/user";
import {
  getSfStatisticsJoy,
  getSfStatisticsJoyInfo,
  selectTimelyRate,
} from "@/api/system/user";
import ExcelJS from "exceljs";
import { saveAs } from "file-saver";
import SeedetailsDialog from './components/SeedetailsDialog.vue';
import TopicDialog from './components/TopicDialog.vue';
import SeedetailsDialog from "./components/SeedetailsDialog.vue";
import TopicDialog from "./components/TopicDialog.vue";
export default {
  name: 'FollowupStatistics',
  name: "FollowupStatistics",
  components: {
    SeedetailsDialog,
    TopicDialog
    TopicDialog,
  },
  data() {
    return {
      // 查询参数
      queryParams: {
        statisticaltype: 1,
        leavehospitaldistrictcodes: [],
        leavehospitaldistrictcodes: ["all"],
        deptcodes: [],
        serviceType: [2],
        dateRange: [],
        pageNum: 1,
        pageSize: 20
        pageSize: 20,
      },
      // 统计类型列表
      Statisticallist: [
        { label: "病区统计", value: 1 },
        { label: "科室统计", value: 2 }
        { label: "科室统计", value: 2 },
      ],
      // 病区列表
@@ -358,7 +375,25 @@
      flatArraydept: [],
      // 服务类型选项
      options: [],
      options: [
        {
          value: 6,
          label: "住院满意度",
          raw: {
            cssClass: "",
            listClass: "",
          },
        },
        {
          value: 14,
          label: "门诊满意度",
          raw: {
            cssClass: "",
            listClass: "",
          },
        },
      ],
      // 表格数据
      userList: [],
@@ -368,6 +403,7 @@
      // 加载状态
      loading: false,
      orgname: "",
      // 选中的行
      ids: [],
@@ -384,48 +420,50 @@
      // 满意度详情数据
      topiclist: [],
      topicvalue: {
        name: ''
        name: "",
      },
      // 日期选择器选项
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: '最近一个月',
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: '最近三个月',
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }
              picker.$emit("pick", [start, end]);
            },
          },
        ],
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      }
        },
      },
    };
  },
  created() {
    this.orgname = localStorage.getItem("orgname");
    this.initData();
  },
@@ -433,7 +471,7 @@
    // 初始化数据
    async initData() {
      await this.getDeptTree();
      await this.getList();
      // await this.getList();
    },
    // 获取科室树
@@ -442,20 +480,24 @@
      this.options = this.$store.getters.tasktypes || [];
      // 获取科室列表
      this.flatArraydept = (this.$store.getters.belongDepts || []).map((dept) => {
        return {
          label: dept.deptName,
          value: dept.deptCode
        };
      });
      this.flatArraydept = (this.$store.getters.belongDepts || []).map(
        (dept) => {
          return {
            label: dept.deptName,
            value: dept.deptCode,
          };
        }
      );
      // 获取病区列表
      this.flatArrayhospit = (this.$store.getters.belongWards || []).map((ward) => {
        return {
          label: ward.districtName,
          value: ward.districtCode
        };
      });
      this.flatArrayhospit = (this.$store.getters.belongWards || []).map(
        (ward) => {
          return {
            label: ward.districtName,
            value: ward.districtCode,
          };
        }
      );
      // 添加全部选项
      this.flatArraydept.push({ label: "全部", value: "all" });
@@ -469,11 +511,14 @@
        // 处理查询参数
        const params = {
          configKey: "joyCount",
          ...this.queryParams
          ...this.queryParams,
        };
        // 处理日期范围
        if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
        if (
          this.queryParams.dateRange &&
          this.queryParams.dateRange.length === 2
        ) {
          params.startTime = this.queryParams.dateRange[0];
          params.endTime = this.queryParams.dateRange[1];
        }
@@ -483,31 +528,215 @@
          // 病区统计
          if (params.leavehospitaldistrictcodes.includes("all")) {
            // 如果选择了"全部",则移除"all"值
            params.leavehospitaldistrictcodes = params.leavehospitaldistrictcodes.filter(item => item !== "all");
            params.leavehospitaldistrictcodes =
              params.leavehospitaldistrictcodes.filter(
                (item) => item !== "all"
              );
            // 如果需要传所有病区代码,可以从store中获取
            params.leavehospitaldistrictcodes = (this.$store.getters.belongWards || []).map(ward => ward.districtCode);
            params.leavehospitaldistrictcodes = (
              this.$store.getters.belongWards || []
            ).map((ward) => ward.districtCode);
          }
        } else if (params.statisticaltype == 2) {
          // 科室统计
          if (params.deptcodes.includes("all")) {
            // 如果选择了"全部",则移除"all"值
            params.deptcodes = params.deptcodes.filter(item => item !== "all");
            params.deptcodes = params.deptcodes.filter(
              (item) => item !== "all"
            );
            // 如果需要传所有科室代码,可以从store中获取
            params.deptcodes = (this.$store.getters.belongDepts || []).map(dept => dept.deptCode);
            params.deptcodes = (this.$store.getters.belongDepts || []).map(
              (dept) => dept.deptCode
            );
          }
        }
        const response = await getSfStatisticsJoy(params);
        this.userList = response.data || [];
        this.userList = this.customSort(response.data) || [];
        this.total = response.total || 0;
      } catch (error) {
        console.error('获取统计列表失败:', error);
        this.$message.error('获取数据失败');
        console.error("获取统计列表失败:", error);
        this.$message.error("获取数据失败");
      } finally {
        this.loading = false;
      }
    },
    sortChineseNumber(aRow, bRow) {
      const a = aRow.leavehospitaldistrictname;
      const b = bRow.leavehospitaldistrictname;
      // 中文数字到阿拉伯数字的映射(扩展到45)
      const chineseNumMap = {
        一: 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,
      };
      // 提取中文数字
      const getNumberFromText = (text) => {
        if (!text || typeof text !== "string") return -1;
        // 匹配中文数字,支持一到四十五
        const match = text.match(/^([一二三四五六七八九十]+)/);
        if (match && match[1]) {
          const chineseNum = match[1];
          return chineseNumMap[chineseNum] !== undefined
            ? chineseNumMap[chineseNum]
            : -1;
        }
        // 如果没有匹配到中文数字,尝试匹配阿拉伯数字
        const arabicMatch = text.match(/^(\d+)/);
        if (arabicMatch && arabicMatch[1]) {
          const num = parseInt(arabicMatch[1], 10);
          return num >= 1 && num <= 45 ? num : -1;
        }
        return -1;
      };
      const numA = getNumberFromText(a);
      const numB = getNumberFromText(b);
      // 处理无法解析的情况
      if (numA === -1 && numB === -1) {
        return (a || "").localeCompare(b || "");
      }
      if (numA === -1) return 1;
      if (numB === -1) return -1;
      return numA - numB;
    },
    customSort(data) {
      // 定义您期望的病区顺序(扩展到四十五)
      const order = [
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九",
        "十",
        "十一",
        "十二",
        "十三",
        "十四",
        "十五",
        "十六",
        "十七",
        "十八",
        "十九",
        "二十",
        "二十一",
        "二十二",
        "二十三",
        "二十四",
        "二十五",
        "二十六",
        "二十七",
        "二十八",
        "二十九",
        "三十",
        "三十一",
        "三十二",
        "三十三",
        "三十四",
        "三十五",
        "三十六",
        "三十七",
        "三十八",
        "三十九",
        "四十",
        "四十一",
        "四十二",
        "四十三",
        "四十四",
        "四十五",
      ];
      return data.sort((a, b) => {
        // 提取病区名称中的中文数字部分
        const getIndex = (name) => {
          if (!name || typeof name !== "string") return -1;
          // 匹配中文数字
          const chineseMatch = name.match(/^([一二三四五六七八九十]+)/);
          if (chineseMatch && chineseMatch[1]) {
            return order.indexOf(chineseMatch[1]);
          }
          // 匹配阿拉伯数字
          const arabicMatch = name.match(/^(\d+)/);
          if (arabicMatch && arabicMatch[1]) {
            const num = parseInt(arabicMatch[1], 10);
            if (num >= 1 && num <= 45) {
              return num - 1; // 因为数组索引从0开始
            }
          }
          return -1;
        };
        const indexA = getIndex(a.leavehospitaldistrictname);
        const indexB = getIndex(b.leavehospitaldistrictname);
        // 排序逻辑
        if (indexA === -1 && indexB === -1) {
          return (a.leavehospitaldistrictname || "").localeCompare(
            b.leavehospitaldistrictname || ""
          );
        }
        if (indexA === -1) return 1;
        if (indexB === -1) return -1;
        return indexA - indexB;
      });
    },
    // 处理统计类型变化
    handleStatisticalTypeChange(value) {
      if (value === 1) {
@@ -534,7 +763,7 @@
        serviceType: [2],
        dateRange: [],
        pageNum: 1,
        pageSize: 20
        pageSize: 20,
      };
      this.getList();
    },
@@ -554,7 +783,7 @@
    // 处理行选择
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
@@ -568,10 +797,96 @@
    // 格式化百分比
    formatPercent(value) {
      if (value === null || value === undefined) return '-';
      if (value === null || value === undefined) return "-";
      const num = parseFloat(value);
      if (isNaN(num)) return '-';
      if (isNaN(num)) return "-";
      return `${(num * 100).toFixed(2)}%`;
    },
    // 表格合计行
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const prop = column.property;
        // 数值列求和
        if (
          [
            "dischargeCount",
            "nonFollowUp",
            "followUpNeeded",
            "joyAllCount",
            "joyCount",
          ].includes(prop)
        ) {
          sums[index] = data.reduce(
            (sum, item) => sum + (Number(item[prop]) || 0),
            0
          );
          return;
        }
        // 完成比率:满意度填报量 / 满意度题目总量
        if (prop === "joyTotal") {
          const totalJoyAllCount = data.reduce(
            (sum, item) => sum + (Number(item.joyAllCount) || 0),
            0
          );
          const totalJoyCount = data.reduce(
            (sum, item) => sum + (Number(item.joyCount) || 0),
            0
          );
          sums[index] =
            totalJoyAllCount > 0
              ? ((totalJoyCount / totalJoyAllCount) * 100).toFixed(2) + "%"
              : "0.00%";
          return;
        }
        // 百分比列(随访率/及时率):取平均值(0 值也参与平均)
        if (prop === "followUpRate" || prop === "rate") {
          const percentageValues = data
            .map((item) => {
              const value = item[prop];
              if (
                value === null ||
                value === undefined ||
                value === "" ||
                value === "-"
              ) {
                return null;
              }
              if (typeof value === "string" && value.includes("%")) {
                const num = parseFloat(value.replace("%", "")) / 100;
                return isNaN(num) ? null : num;
              }
              const num = parseFloat(value);
              return isNaN(num) ? null : num;
            })
            .filter((value) => value !== null);
          sums[index] =
            percentageValues.length > 0
              ? (
                  (percentageValues.reduce((sum, value) => sum + value, 0) /
                    percentageValues.length) *
                  100
                ).toFixed(2) + "%"
              : "0.00%";
          return;
        }
        sums[index] = "";
      });
      return sums;
    },
    // 查看未及时随访详情
@@ -583,17 +898,19 @@
    // 查看满意度详情
    async getinfo(row) {
      this.currentRow = row;
      this.topicVisible = true;
      try {
        // 处理查询参数
        const params = {
          configKey: "joyCount",
          ...this.queryParams
          ...this.queryParams,
        };
        // 处理日期范围
        if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
        if (
          this.queryParams.dateRange &&
          this.queryParams.dateRange.length === 2
        ) {
          params.startTime = this.queryParams.dateRange[0];
          params.endTime = this.queryParams.dateRange[1];
        }
@@ -608,16 +925,124 @@
        const response = await getSfStatisticsJoyInfo(params);
        this.topiclist = response.data || [];
        this.topicVisible = true;
      } catch (error) {
        console.error('获取满意度详情失败:', error);
        this.$message.error('获取详情失败');
        console.error("获取满意度详情失败:", error);
        this.$message.error("获取详情失败");
      }
    },
    // 获取指定病区/科室的题目详情
    async fetchTopicDetail(row) {
      const params = {
        configKey: "joyCount",
        ...this.queryParams,
      };
      // 导出需要该病区/科室的全部题目,覆盖主表分页参数
      params.pageNum = 1;
      params.pageSize = 1000;
      if (
        this.queryParams.dateRange &&
        this.queryParams.dateRange.length === 2
      ) {
        params.startTime = this.queryParams.dateRange[0];
        params.endTime = this.queryParams.dateRange[1];
      }
      if (this.queryParams.statisticaltype == 1) {
        params.leavehospitaldistrictcodes = [row.leavehospitaldistrictcode];
      } else {
        params.deptcodes = [row.deptcode];
      }
      const response = await getSfStatisticsJoyInfo(params);
      return response.data || {};
    },
    // 主表导出行数据
    getMainExportRow(item) {
      return [
        this.queryParams.statisticaltype == 1
          ? item.leavehospitaldistrictname
          : item.deptname,
        item.dischargeCount || 0,
        item.nonFollowUp || 0,
        item.followUpNeeded || 0,
        item.followUpRate || "0%",
        item.rate ? this.formatPercent(item.rate) : "0%",
        item.joyAllCount || 0,
        item.joyCount || 0,
        item.joyTotal ? this.formatPercent(item.joyTotal) : "0%",
      ];
    },
    // 计算文本显示宽度(中文按 2、英文/数字按 1)
    textWidth(str) {
      if (!str) return 0;
      let width = 0;
      for (const ch of String(str)) {
        width += ch.charCodeAt(0) > 255 ? 2 : 1;
      }
      return width;
    },
    // 丽水市中医院:拉取所有科室题目明细,扁平化为「题目选项」列结构
    async buildLishuiTopicColumns() {
      const topicMap = new Map();
      const rowQuantities = [];
      for (const item of this.userList) {
        const topiclist = await this.fetchTopicDetail(item);
        const qMap = new Map();
        if (topiclist && Object.keys(topiclist).length) {
          Object.keys(topiclist).forEach((key) => {
            const topic = topiclist[key];
            if (!topic || !topic.scriptContent) return;
            const tKey =
              topic.scriptid != null && topic.scriptid !== ""
                ? String(topic.scriptid)
                : topic.scriptContent;
            if (!topicMap.has(tKey)) {
              topicMap.set(tKey, {
                key: tKey,
                scriptContent: topic.scriptContent,
                options: [],
                optionSet: new Set(),
              });
            }
            const t = topicMap.get(tKey);
            const topicQ = new Map();
            (topic.details || []).forEach((detail) => {
              if (!detail || !detail.optionText) return;
              if (!t.optionSet.has(detail.optionText)) {
                t.optionSet.add(detail.optionText);
                t.options.push(detail.optionText);
              }
              topicQ.set(detail.optionText, Number(detail.chosenQuantity) || 0);
            });
            qMap.set(tKey, topicQ);
          });
        }
        rowQuantities.push(qMap);
      }
      const topics = Array.from(topicMap.values());
      // 没有选项的题目默认填充一个空选项列,避免表头/数据错位
      topics.forEach((t) => {
        if (!t.options.length) {
          t.options = [""];
        }
      });
      return { topics, rowQuantities };
    },
    // 导出数据
    async handleExport() {
      if (!this.userList.length) {
        this.$message.warning('没有数据可导出');
        this.$message.warning("没有数据可导出");
        return;
      }
@@ -627,20 +1052,54 @@
        // 构建日期范围字符串
        let dateRangeString = "";
        let sheetNameSuffix = "";
        const isLishuiHospital = this.orgname == "丽水市中医院";
        if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
          const startDateFormatted = this.queryParams.dateRange[0];
          const endDateFormatted = this.queryParams.dateRange[1];
          dateRangeString = `${startDateFormatted}至${endDateFormatted}`;
          sheetNameSuffix = `${startDateFormatted}至${endDateFormatted}`;
        if (
          this.queryParams.dateRange &&
          this.queryParams.dateRange.length === 2
        ) {
          const startDateStr = this.queryParams.dateRange[0];
          const endDateStr = this.queryParams.dateRange[1];
          if (isLishuiHospital) {
            // 丽水市中医院:只显示年月
            const formatMonthOnly = (dateTimeStr) => {
              const date = new Date(dateTimeStr);
              const year = date.getFullYear();
              const month = date.getMonth() + 1;
              return `${year}年${month}月`;
            };
            const startDateFormatted = formatMonthOnly(startDateStr);
            const endDateFormatted = formatMonthOnly(endDateStr);
            dateRangeString = `${startDateFormatted}至${endDateFormatted}`;
            sheetNameSuffix = `${startDateFormatted}至${endDateFormatted}`;
          } else {
            // 其他医院:显示年月日
            const formatDateForDisplay = (dateTimeStr) => {
              return dateTimeStr.split(" ")[0];
            };
            const startDateFormatted = formatDateForDisplay(startDateStr);
            const endDateFormatted = formatDateForDisplay(endDateStr);
            dateRangeString = `${startDateFormatted}至${endDateFormatted}`;
            sheetNameSuffix = `${startDateFormatted}至${endDateFormatted}`;
          }
        } else {
          const now = new Date();
          const currentMonth = now.getMonth() + 1;
          dateRangeString = `${currentMonth}月`;
          sheetNameSuffix = `${currentMonth}月`;
          const currentYear = now.getFullYear();
          if (isLishuiHospital) {
            // 丽水市中医院:显示年月
            dateRangeString = `${currentYear}年${currentMonth}月`;
            sheetNameSuffix = `${currentYear}年${currentMonth}月`;
          } else {
            // 其他医院:显示月份
            dateRangeString = `${currentMonth}月`;
            sheetNameSuffix = `${currentMonth}月`;
          }
        }
        const excelName = `随访统计表_${dateRangeString}.xlsx`;
        const excelName = `满意度随访统计表_${dateRangeString}.xlsx`;
        const worksheetName = `随访统计_${sheetNameSuffix}`;
        // 创建Excel工作簿
@@ -650,26 +1109,38 @@
        // 定义样式
        const titleStyle = {
          font: { name: "微软雅黑", size: 16, bold: true },
          fill: { type: "pattern", pattern: "solid", fgColor: { argb: "FFE6F3FF" } },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "FFE6F3FF" },
          },
          alignment: { vertical: "middle", horizontal: "center" },
          border: {
            top: { style: "thin", color: { argb: "FFD0D0D0" } },
            left: { style: "thin", color: { argb: "FFD0D0D0" } },
            bottom: { style: "thin", color: { argb: "FFD0D0D0" } },
            right: { style: "thin", color: { argb: "FFD0D0D0" } }
          }
            right: { style: "thin", color: { argb: "FFD0D0D0" } },
          },
        };
        const headerStyle = {
          font: { name: "微软雅黑", size: 11, bold: true },
          fill: { type: "pattern", pattern: "solid", fgColor: { argb: "FFF5F7FA" } },
          alignment: { vertical: "middle", horizontal: "center" },
          fill: {
            type: "pattern",
            pattern: "solid",
            fgColor: { argb: "FFF5F7FA" },
          },
          alignment: {
            vertical: "middle",
            horizontal: "center",
            wrapText: true,
          },
          border: {
            top: { style: "thin", color: { argb: "FFD0D0D0" } },
            left: { style: "thin", color: { argb: "FFD0D0D0" } },
            bottom: { style: "thin", color: { argb: "FFD0D0D0" } },
            right: { style: "thin", color: { argb: "FFD0D0D0" } }
          }
            right: { style: "thin", color: { argb: "FFD0D0D0" } },
          },
        };
        const cellStyle = {
@@ -679,19 +1150,21 @@
            top: { style: "thin", color: { argb: "FFD0D0D0" } },
            left: { style: "thin", color: { argb: "FFD0D0D0" } },
            bottom: { style: "thin", color: { argb: "FFD0D0D0" } },
            right: { style: "thin", color: { argb: "FFD0D0D0" } }
          }
            right: { style: "thin", color: { argb: "FFD0D0D0" } },
          },
        };
        // 添加总标题
        worksheet.mergeCells(1, 1, 1, 10);
        const titleCell = worksheet.getCell(1, 1);
        titleCell.value = `随访统计表(${sheetNameSuffix})`;
        titleCell.style = titleStyle;
        worksheet.getRow(1).height = 35;
        // 丽水市中医院:预先拉取题目明细,扁平化为「题目选项」列
        let lishuiTopics = [];
        let lishuiRowQuantities = [];
        if (isLishuiHospital) {
          const built = await this.buildLishuiTopicColumns();
          lishuiTopics = built.topics;
          lishuiRowQuantities = built.rowQuantities;
        }
        // 添加表头
        const headers = [
        // 主表列
        const mainHeaders = [
          this.queryParams.statisticaltype == 1 ? "出院病区" : "科室",
          "出院人次",
          "无需随访人次",
@@ -700,52 +1173,168 @@
          "及时率",
          "满意度题目总量",
          "满意度填报量",
          "完成比率"
          "完成比率",
        ];
        const mainColumnCount = mainHeaders.length;
        const headerRow = worksheet.addRow(headers);
        headerRow.eachCell((cell) => {
          cell.style = headerStyle;
        });
        headerRow.height = 25;
        // 总列数(丽水市中医院在末尾追加题目选项列)
        const topicColumnCount = lishuiTopics.reduce(
          (sum, t) => sum + (t.options.length || 1),
          0
        );
        const totalColumns = mainColumnCount + topicColumnCount;
        // 添加数据行
        this.userList.forEach((item) => {
          const dataRow = worksheet.addRow([
            this.queryParams.statisticaltype == 1 ? item.leavehospitaldistrictname : item.deptname,
            item.dischargeCount || 0,
            item.nonFollowUp || 0,
            item.followUpNeeded || 0,
            item.followUpRate || "0%",
            item.rate ? this.formatPercent(item.rate) : "0%",
            item.joyAllCount || 0,
            item.joyCount || 0,
            item.joyTotal ? this.formatPercent(item.joyTotal) : "0%"
          ]);
        // 添加总标题
        worksheet.mergeCells(1, 1, 1, totalColumns);
        const titleCell = worksheet.getCell(1, 1);
        titleCell.value = `满意度随访统计表(${sheetNameSuffix})`;
        titleCell.style = titleStyle;
        worksheet.getRow(1).height = 35;
          dataRow.eachCell((cell) => {
            cell.style = cellStyle;
        if (isLishuiHospital && lishuiTopics.length) {
          // 计算每个题目的选项列宽(选项文字自适应,题干过长时摊宽列、必要时换行)
          const topicColumns = lishuiTopics.map((topic) => {
            const n = topic.options.length || 1;
            const baseWidths = topic.options.map((opt) =>
              opt === "" ? 10 : Math.max(10, this.textWidth(opt) + 4)
            );
            const sumWidth = baseWidths.reduce((s, w) => s + w, 0);
            const topicWidth = this.textWidth(topic.scriptContent) + 4;
            const groupWidth = Math.max(sumWidth, topicWidth);
            const extra = (groupWidth - sumWidth) / n;
            const widths = baseWidths.map((w) => w + extra);
            const lines = Math.max(1, Math.ceil(topicWidth / groupWidth));
            return { widths, lines };
          });
          dataRow.height = 22;
        });
          const maxHeaderLines = topicColumns.reduce(
            (m, t) => Math.max(m, t.lines),
            1
          );
        // 设置列宽
        worksheet.columns = [
          { width: 20 },
          { width: 12 },
          { width: 12 },
          { width: 12 },
          { width: 12 },
          { width: 12 },
          { width: 15 },
          { width: 15 },
          { width: 12 }
        ];
          // 两行表头:第一行 = 主表列 + 题目名;第二行 = 选项名
          const headerRow1 = worksheet.addRow([]);
          const headerRow2 = worksheet.addRow([]);
          mainHeaders.forEach((h, i) => {
            const col = i + 1;
            headerRow1.getCell(col).value = h;
            headerRow1.getCell(col).style = headerStyle;
            headerRow2.getCell(col).style = headerStyle;
            worksheet.mergeCells(
              headerRow1.number,
              col,
              headerRow2.number,
              col
            );
          });
          let colIndex = mainColumnCount + 1;
          lishuiTopics.forEach((topic) => {
            const optCount = topic.options.length || 1;
            for (let k = 0; k < optCount; k++) {
              headerRow1.getCell(colIndex + k).style = headerStyle;
            }
            headerRow1.getCell(colIndex).value = topic.scriptContent;
            if (optCount > 1) {
              worksheet.mergeCells(
                headerRow1.number,
                colIndex,
                headerRow1.number,
                colIndex + optCount - 1
              );
            }
            topic.options.forEach((opt, k) => {
              headerRow2.getCell(colIndex + k).value = opt;
              headerRow2.getCell(colIndex + k).style = headerStyle;
            });
            colIndex += optCount;
          });
          // 表头高度:题干换行时按最长题目预留
          headerRow1.height = Math.max(30, 15 * maxHeaderLines + 8);
          headerRow2.height = 25;
          // 数据行
          this.userList.forEach((item, idx) => {
            const row = worksheet.addRow([]);
            const main = this.getMainExportRow(item);
            main.forEach((v, i) => {
              const cell = row.getCell(i + 1);
              cell.value = v;
              cell.style = cellStyle;
            });
            const qMap = lishuiRowQuantities[idx] || new Map();
            let cIndex = mainColumnCount + 1;
            for (const topic of lishuiTopics) {
              const topicQ = qMap.get(topic.key);
              topic.options.forEach((opt) => {
                const cell = row.getCell(cIndex);
                if (opt === "") {
                  // 空选项占位列不填数字
                  cell.value = "";
                } else {
                  const val = topicQ ? topicQ.get(opt) : undefined;
                  cell.value = val === undefined || val === null ? 0 : val;
                }
                cell.style = cellStyle;
                cIndex++;
              });
            }
            row.height = 22;
          });
          // 列宽:主表列 + 题目选项列
          const columns = [
            { width: 20 },
            { width: 12 },
            { width: 12 },
            { width: 12 },
            { width: 12 },
            { width: 12 },
            { width: 15 },
            { width: 15 },
            { width: 12 },
          ];
          lishuiTopics.forEach((topic, ti) => {
            topicColumns[ti].widths.forEach((w) => {
              columns.push({ width: w });
            });
          });
          worksheet.columns = columns;
        } else {
          // 其他医院:单行表头
          const headerRow = worksheet.addRow(mainHeaders);
          headerRow.eachCell((cell) => {
            cell.style = headerStyle;
          });
          headerRow.height = 25;
          this.userList.forEach((item) => {
            const dataRow = worksheet.addRow(this.getMainExportRow(item));
            dataRow.eachCell((cell) => {
              cell.style = cellStyle;
            });
            dataRow.height = 22;
          });
          worksheet.columns = [
            { width: 20 },
            { width: 12 },
            { width: 12 },
            { width: 12 },
            { width: 12 },
            { width: 12 },
            { width: 15 },
            { width: 15 },
            { width: 12 },
          ];
        }
        // 生成并下载文件
        const buffer = await workbook.xlsx.writeBuffer();
        const blob = new Blob([buffer], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        saveAs(blob, excelName);
@@ -756,8 +1345,8 @@
      } finally {
        this.loading = false;
      }
    }
  }
    },
  },
};
</script>