WXL (wul)
昨天 a2c10da81668de1f5b7d38f5962d46d795e3cc7e
src/views/Satisfaction/sfstatistics/components/SatisfactionStatistics.vue
@@ -11,19 +11,16 @@
          label-width="100px"
          class="query-form"
        >
          <el-form-item label="患者来源" prop="patientSource">
          <el-form-item label="统计类型" prop="patientSource">
            <el-select
              v-model="queryParams.patientSource"
              placeholder="请选择患者来源"
              v-model="queryParams.type"
              placeholder="请选择统计类型"
              clearable
              style="width: 200px"
              style="width: 100%"
            >
              <el-option
                v-for="source in patientSourceList"
                :key="source.value"
                :label="source.label"
                :value="source.value"
              />
              <el-option label="问卷类型" :value="2" />
              <el-option label="语音类型" :value="1" />
              <el-option label="全部" :value="null" />
            </el-select>
          </el-form-item>
@@ -34,6 +31,7 @@
              clearable
              filterable
              style="width: 200px"
              @change="handleDeptChange"
            >
              <el-option
                v-for="dept in deptList"
@@ -51,6 +49,7 @@
              clearable
              filterable
              style="width: 200px"
              @change="handleWardChange"
            >
              <el-option
                v-for="ward in wardList"
@@ -190,7 +189,7 @@
                  min-width="300"
                >
                  <template slot-scope="{ row }">
                    <span>{{ row.scriptContent }}?</span>
                    <span>{{ row.scriptContent }}</span>
                    <el-tag
                      :type="row.scriptType === 1 ? 'primary' : 'success'"
                      size="mini"
@@ -254,7 +253,7 @@
                  width="100"
                >
                  <template slot-scope="{ row }">
                    {{ row.totalCount - row.answerCount }}
                    {{ row.noAnswerPerson }}
                  </template>
                </el-table-column>
@@ -265,7 +264,7 @@
                  width="100"
                >
                  <template slot-scope="{ row }">
                    {{ formatPercent(row.answerCount / row.totalCount) }}
                    {{ formatPercent(row.answerRate) }}
                  </template>
                </el-table-column>
              </el-table>
@@ -273,10 +272,6 @@
              <!-- 综合得分行 -->
              <div class="summary-row">
                <div class="summary-content">
                  <div class="summary-item">
                    <span class="label">综合得分:</span>
                    <span class="value">{{ totalScore.toFixed(1) }}</span>
                  </div>
                  <div class="summary-item">
                    <span class="label">总答题人数:</span>
                    <span class="value">{{ totalAnswerCount }}</span>
@@ -403,32 +398,6 @@
                </el-table-column>
                <el-table-column
                  label="最高分"
                  prop="maxScore"
                  align="center"
                  width="120"
                >
                  <template slot-scope="{ row }">
                    <span class="score-text">{{
                      row.maxScore.toFixed(1)
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="最低分"
                  prop="minScore"
                  align="center"
                  width="120"
                >
                  <template slot-scope="{ row }">
                    <span class="score-text">{{
                      row.minScore.toFixed(1)
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="满意度等级"
                  prop="satisfactionLevel"
                  align="center"
@@ -539,6 +508,8 @@
<script>
import * as echarts from "echarts";
import { statistics, satisfactionGraph } from "@/api/system/user";
import store from "@/store";
export default {
  name: "SatisfactionStatistics",
@@ -546,6 +517,7 @@
    return {
      // 查询参数
      queryParams: {
        type: 2,
        patientSource: "",
        deptCode: "",
        wardCode: "",
@@ -597,9 +569,12 @@
      // 各类型统计明细数据
      typeDetailData: [],
      // 柱状图数据
      chartData: [],
      // 统计信息
      totalSendCount: 12560,
      totalReceiveCount: 10240,
      totalSendCount: 0,
      totalReceiveCount: 0,
      overallRecoveryRate: 0,
      // 类型统计汇总
@@ -650,7 +625,54 @@
        { id: 403, name: "门诊满意度", color: "#409EFF" },
        { id: 404, name: "常用满意度", color: "#FF9D4D" },
      ],
      // 新增:默认服务类型数组
      defaultServiceTypes: ["6", "14", "15", "16"],
      // 新增:基础模板问题ID集合
      scriptIds: [],
      // 新增:模板ID
      templateId: null,
    };
  },
  computed: {
    // 计算查询开始时间
    startTime() {
      if (this.queryParams.dateRange && this.queryParams.dateRange[0]) {
        return this.queryParams.dateRange[0];
      }
      // 默认最近7天
      const date = new Date();
      date.setDate(date.getDate() - 7);
      return this.formatDate(date);
    },
    // 计算查询结束时间
    endTime() {
      if (this.queryParams.dateRange && this.queryParams.dateRange[1]) {
        return this.queryParams.dateRange[1];
      }
      // 默认今天
      return this.formatDate(new Date());
    },
    // 计算科室编码数组
    deptCodes() {
      if (this.queryParams.deptCode) {
        return [this.queryParams.deptCode];
      }
      return this.deptList.map((dept) => dept.value);
    },
    // 计算病区编码数组
    hospitalDistrictCodes() {
      if (this.queryParams.wardCode) {
        return [this.queryParams.wardCode];
      }
      return this.wardList.map((ward) => ward.value);
    },
  },
  mounted() {
@@ -665,6 +687,14 @@
  },
  methods: {
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    // 初始化数据
    async initData() {
      await this.getDeptList();
@@ -676,34 +706,26 @@
    // 获取科室列表
    getDeptList() {
      return new Promise((resolve) => {
        setTimeout(() => {
          this.deptList = [
            { value: "dept001", label: "心血管内科" },
            { value: "dept002", label: "神经内科" },
            { value: "dept003", label: "普外科" },
            { value: "dept004", label: "骨科" },
            { value: "dept005", label: "妇产科" },
            { value: "dept006", label: "儿科" },
          ];
          resolve();
        }, 100);
        this.deptList = (this.$store.getters.belongDepts || []).map((dept) => {
          return {
            label: dept.deptName,
            value: dept.deptCode,
          };
        });
        resolve();
      });
    },
    // 获取病区列表
    getWardList() {
      return new Promise((resolve) => {
        setTimeout(() => {
          this.wardList = [
            { value: "ward001", label: "内科一病区" },
            { value: "ward002", label: "内科二病区" },
            { value: "ward003", label: "外科一病区" },
            { value: "ward004", label: "外科二病区" },
            { value: "ward005", label: "妇产科病区" },
            { value: "ward006", label: "儿科病区" },
          ];
          resolve();
        }, 100);
        this.wardList = (this.$store.getters.belongWards || []).map((ward) => {
          return {
            label: ward.districtName,
            value: ward.districtCode,
          };
        });
        resolve();
      });
    },
@@ -720,21 +742,104 @@
    async loadChartData() {
      this.loading = true;
      try {
        // 模拟API调用
        const chartData = await this.generateChartData();
        this.renderChart(chartData);
        const params = {
          type: this.queryParams.type,
          startTime: this.startTime,
          endTime: this.endTime,
          deptcodes: this.deptCodes,
          hospitaldistrictcodes: this.hospitalDistrictCodes,
          templateid: this.templateId,
        };
        // 计算总体回收率
        this.overallRecoveryRate = this.totalReceiveCount / this.totalSendCount;
        const response = await satisfactionGraph(params);
        if (response.code === 200) {
          this.processChartData(response);
        } else {
          this.$message.error(response.msg || "获取图表数据失败");
          // 使用mock数据
          await this.generateMockChartData();
        }
      } catch (error) {
        console.error("获取图表数据出错:", error);
        this.$message.error("获取图表数据失败");
        // 错误时使用mock数据
        await this.generateMockChartData();
      } finally {
        this.loading = false;
      }
    },
    // 处理图表数据
    processChartData(apiData) {
      if (!apiData || !apiData.rows || Object.keys(apiData.rows).length === 0) {
        this.chartData = [];
        this.totalSendCount = 0;
        this.totalReceiveCount = 0;
        this.overallRecoveryRate = 0;
        this.renderChart([]);
        return;
      }
      const chartData = [];
      let totalSend = 0;
      let totalReceive = 0;
      let index = 0;
      // 处理接口返回的满意度类型统计
      Object.entries(apiData.rows).forEach(([typeName, typeStat]) => {
        const sendCount = typeStat.subidAll || 0;
        const receiveCount = typeStat.fillCountAll || 0;
        const recoveryRate = typeStat.receiveRate || 0;
        chartData.push({
          name: typeName,
          value: recoveryRate * 100, // 转换为百分比
          sendCount: sendCount,
          receiveCount: receiveCount,
          averageScore: typeStat.averageScore || 0,
          itemStyle: { color: this.getChartColor(index) },
        });
        totalSend += sendCount;
        totalReceive += receiveCount;
        index++;
      });
      this.totalSendCount = totalSend;
      this.totalReceiveCount = totalReceive;
      this.overallRecoveryRate = totalSend > 0 ? totalReceive / totalSend : 0;
      this.chartData = chartData;
      this.renderChart(chartData);
    },
    // 加载题目明细数据
    async loadQuestionDetailData() {
      this.detailLoading = true;
      try {
        const params = {
          type: this.queryParams.type,
          startTime: this.startTime,
          endTime: this.endTime,
          scriptids: this.scriptIds,
          templateid: this.templateId,
        };
        const response = await statistics(params);
        if (response.code === 200) {
          this.processQuestionDetailData(response.rows);
        } else {
          this.$message.error(response.msg || "获取题目明细数据失败");
          const mockData = await this.generateMockQuestionDetail();
          this.questionDetailData = mockData.list;
          this.detailTotal = mockData.total;
          this.calculateSummary(mockData);
        }
      } catch (error) {
        console.error("获取题目明细数据出错:", error);
        this.$message.error("获取题目明细数据失败");
        const mockData = await this.generateMockQuestionDetail();
        this.questionDetailData = mockData.list;
        this.detailTotal = mockData.total;
@@ -744,18 +849,137 @@
      }
    },
    // 处理接口返回的题目明细数据
    processQuestionDetailData(apiData) {
      if (!apiData || !apiData.patSatisfactionDetailEntities) {
        this.questionDetailData = [];
        this.detailTotal = 0;
        this.totalAnswerCount = 0;
        this.totalAnswerRate = 0;
        return;
      }
      const detailData = apiData.patSatisfactionDetailEntities.map((item) => {
        const options = [];
        if (item.matchedtextStats) {
          Object.keys(item.matchedtextStats).forEach((key) => {
            const stat = item.matchedtextStats[key];
            options.push({
              optionText: key,
              chosenQuantity: stat.count || 0,
              chosenPercentage: (stat.ratio || 0) / 100,
            });
          });
        }
        return {
          scriptContent: item.scriptContent || "",
          scriptType: 1,
          answerPerson: item.answerPerson || 0,
          noAnswerPerson: item.noAnswerPerson || 0,
          answerCount: item.answerPerson || 0,
          averageScore: item.averageScore || 0,
          maxScore: item.maxScore || 0,
          minScore: item.minScore || 0,
          answerRate: item.answerRate || 0,
          totalCount: (item.answerPerson || 0) + (item.noAnswerPerson || 0),
          options: options,
        };
      });
      const startIndex =
        (this.detailQueryParams.pageNum - 1) * this.detailQueryParams.pageSize;
      const endIndex = startIndex + this.detailQueryParams.pageSize;
      const paginatedData = detailData.slice(startIndex, endIndex);
      this.questionDetailData = paginatedData;
      this.detailTotal = detailData.length;
      this.totalAnswerCount = apiData.totalPerson || 0;
      this.totalAnswerRate = apiData.totalAnswerRate || 0;
    },
    // 加载类型明细数据
    async loadTypeDetailData() {
      this.typeDetailLoading = true;
      try {
        const params = {
          type: this.queryParams.type,
          startTime: this.startTime,
          endTime: this.endTime,
          deptcodes: this.deptCodes,
          hospitaldistrictcodes: this.hospitalDistrictCodes,
          templateid: this.templateId,
        };
        const response = await satisfactionGraph(params);
        if (response.code === 200) {
          this.processTypeDetailData(response.data);
        } else {
          this.$message.error(response.msg || "获取类型明细数据失败");
          const mockData = await this.generateMockTypeDetail();
          this.typeDetailData = mockData;
          this.calculateTypeSummary(mockData);
        }
      } catch (error) {
        console.error("获取类型明细数据出错:", error);
        this.$message.error("获取类型明细数据失败");
        const mockData = await this.generateMockTypeDetail();
        this.typeDetailData = mockData;
        // 计算类型统计汇总
        this.calculateTypeSummary(mockData);
      } finally {
        this.typeDetailLoading = false;
      }
    },
    // 处理类型明细数据
    processTypeDetailData(apiData) {
      if (!apiData || !apiData.rows || Object.keys(apiData.rows).length === 0) {
        this.typeDetailData = [];
        this.calculateTypeSummary([]);
        return;
      }
      const typeDetail = [];
      Object.entries(apiData.rows).forEach(([typeName, typeStat], index) => {
        const sendCount = typeStat.subidAll || 0;
        const receiveCount = typeStat.fillCountAll || 0;
        const recoveryRate = typeStat.receiveRate || 0;
        const averageScore = typeStat.averageScore || 0;
        typeDetail.push({
          id: index + 1,
          typeName: typeName,
          isSpecial: false, // 根据实际情况判断
          sendCount: sendCount,
          receiveCount: receiveCount,
          recoveryRate: recoveryRate,
          averageScore: averageScore,
          maxScore: 5, // 默认值
          minScore: 0, // 默认值
          satisfactionLevel: this.getSatisfactionLevel(averageScore),
          trend: "stable", // 默认稳定
        });
      });
      this.typeDetailData = typeDetail;
      this.calculateTypeSummary(typeDetail);
    },
    // 根据平均分获取满意度等级
    getSatisfactionLevel(score) {
      if (score >= 4.5) return "优秀";
      if (score >= 4.0) return "良好";
      if (score >= 3.0) return "一般";
      if (score >= 2.0) return "较差";
      return "差";
    },
    // 获取趋势
    getTrend(trend) {
      if (trend > 0.1) return "up";
      if (trend < -0.1) return "down";
      return "stable";
    },
    // 计算综合得分
@@ -814,50 +1038,27 @@
      window.addEventListener("resize", this.handleChartResize);
    },
    // 生成图表数据
    generateChartData() {
      return new Promise((resolve) => {
        setTimeout(() => {
          const data = this.satisfactionTypes.map((type) => ({
            name: type.name,
            recoveryRate: Math.random() * 0.3 + 0.6, // 60%-90%的回收率
            sendCount: Math.floor(Math.random() * 3000) + 1500, // 1500-4500
            receiveCount: 0,
            color: type.color,
          }));
          // 计算回收数量
          data.forEach((item) => {
            item.receiveCount = Math.floor(item.sendCount * item.recoveryRate);
          });
          // 更新总量
          this.totalSendCount = data.reduce(
            (sum, item) => sum + item.sendCount,
            0
          );
          this.totalReceiveCount = data.reduce(
            (sum, item) => sum + item.receiveCount,
            0
          );
          resolve({
            data: data.map((item) => ({
              name: item.name,
              value: item.recoveryRate * 100, // 转换为百分比
              sendCount: item.sendCount,
              receiveCount: item.receiveCount,
              itemStyle: { color: item.color },
            })),
          });
        }, 300);
      });
    },
    // 渲染图表
    renderChart(chartData) {
      if (!this.barChart) return;
 if (!chartData || chartData.length === 0) {
    const emptyOption = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#999",
          fontSize: 16,
          fontWeight: "normal"
        }
      },
      xAxis: { show: false },
      yAxis: { show: false }
    };
    this.barChart.setOption(emptyOption);
    return;
  }
      const option = {
        title: {
          text: "",
@@ -900,7 +1101,7 @@
        },
        xAxis: {
          type: "category",
          data: chartData.data.map((item) => item.name),
          data: chartData.map((item) => item.name),
          axisLabel: {
            interval: 0,
            rotate: 0,
@@ -942,7 +1143,7 @@
            name: "填报比例",
            type: "bar",
            barWidth: 40,
            data: chartData.data,
            data: chartData,
            itemStyle: {
              color: (params) => {
                return params.data.itemStyle.color;
@@ -962,19 +1163,100 @@
      this.barChart.setOption(option);
    },
    // 生成Mock图表数据
    generateMockChartData() {
      return new Promise((resolve) => {
        setTimeout(() => {
          const data = this.satisfactionTypes.map((type, index) => ({
            name: type.name,
            recoveryRate: Math.random() * 0.3 + 0.6,
            sendCount: Math.floor(Math.random() * 3000) + 1500,
            receiveCount: 0,
            color: type.color,
          }));
          data.forEach((item) => {
            item.receiveCount = Math.floor(item.sendCount * item.recoveryRate);
          });
          this.totalSendCount = data.reduce(
            (sum, item) => sum + item.sendCount,
            0
          );
          this.totalReceiveCount = data.reduce(
            (sum, item) => sum + item.receiveCount,
            0
          );
          this.overallRecoveryRate =
            this.totalSendCount > 0
              ? this.totalReceiveCount / this.totalSendCount
              : 0;
          const chartData = data.map((item) => ({
            name: item.name,
            value: item.recoveryRate * 100,
            sendCount: item.sendCount,
            receiveCount: item.receiveCount,
            itemStyle: { color: item.color },
          }));
          this.chartData = chartData;
          this.renderChart(chartData);
          resolve();
        }, 300);
      });
    },
    // 生成Mock题目详情数据
    generateMockQuestionDetail() {
      return new Promise((resolve) => {
        setTimeout(() => {
          const questions = [
            {
              scriptContent: "您对医护人员的服务态度是否满意",
              scriptContent: "您对本次就医的整体满意程度?",
              scriptType: 1,
              totalCount: 156,
              answerPerson: 120,
              noAnswerPerson: 30,
              answerCount: 120,
              totalCount: 150,
              averageScore: 4.2,
              maxScore: 5.0,
              minScore: 1.0,
              answerRate: 0.8,
              options: [
                {
                  optionText: "非常满意",
                  chosenQuantity: 60,
                  chosenPercentage: 0.5,
                },
                {
                  optionText: "满意",
                  chosenQuantity: 36,
                  chosenPercentage: 0.3,
                },
                {
                  optionText: "一般",
                  chosenQuantity: 18,
                  chosenPercentage: 0.15,
                },
                {
                  optionText: "不满意",
                  chosenQuantity: 6,
                  chosenPercentage: 0.05,
                },
              ],
            },
            {
              scriptContent: "您对医护人员的服务态度是否满意?",
              scriptType: 1,
              answerPerson: 145,
              noAnswerPerson: 11,
              answerCount: 145,
              totalCount: 156,
              averageScore: 4.5,
              maxScore: 5,
              minScore: 3,
              answerRate: 0.93,
              options: [
                {
                  optionText: "非常满意",
@@ -1003,78 +1285,6 @@
                },
              ],
            },
            {
              scriptContent: "您对医生的诊疗水平和技术能力评价如何",
              scriptType: 1,
              totalCount: 156,
              answerCount: 142,
              averageScore: 4.7,
              maxScore: 5,
              minScore: 3,
              options: [
                {
                  optionText: "非常专业",
                  chosenQuantity: 95,
                  chosenPercentage: 0.67,
                },
                {
                  optionText: "比较专业",
                  chosenQuantity: 40,
                  chosenPercentage: 0.28,
                },
                {
                  optionText: "一般",
                  chosenQuantity: 5,
                  chosenPercentage: 0.04,
                },
                {
                  optionText: "不够专业",
                  chosenQuantity: 2,
                  chosenPercentage: 0.01,
                },
                {
                  optionText: "非常不专业",
                  chosenQuantity: 0,
                  chosenPercentage: 0,
                },
              ],
            },
            {
              scriptContent: "您对医院的环境和卫生状况是否满意",
              scriptType: 1,
              totalCount: 156,
              answerCount: 138,
              averageScore: 4.3,
              maxScore: 5,
              minScore: 2,
              options: [
                {
                  optionText: "非常满意",
                  chosenQuantity: 75,
                  chosenPercentage: 0.54,
                },
                {
                  optionText: "满意",
                  chosenQuantity: 50,
                  chosenPercentage: 0.36,
                },
                {
                  optionText: "一般",
                  chosenQuantity: 10,
                  chosenPercentage: 0.07,
                },
                {
                  optionText: "不满意",
                  chosenQuantity: 3,
                  chosenPercentage: 0.02,
                },
                {
                  optionText: "非常不满意",
                  chosenQuantity: 0,
                  chosenPercentage: 0,
                },
              ],
            },
          ];
          const startIndex =
@@ -1095,7 +1305,6 @@
    generateMockTypeDetail() {
      return new Promise((resolve) => {
        setTimeout(() => {
          // 在 generateMockTypeDetail 方法中替换为:
          const types = [
            {
              id: 401,
@@ -1156,6 +1365,19 @@
      });
    },
    // 获取图表颜色
    getChartColor(index) {
      const colors = [
        "#36B37E",
        "#4CAF50",
        "#409EFF",
        "#FF9D4D",
        "#9B8DFF",
        "#FF6B6B",
      ];
      return colors[index % colors.length];
    },
    // 处理图表响应式
    handleChartResize() {
      if (this.barChart) {
@@ -1167,6 +1389,12 @@
    handleSearch() {
      this.detailQueryParams.pageNum = 1;
      this.loadData();
      // 强制重新渲染图表
      setTimeout(() => {
        if (this.chartData.length === 0) {
          this.renderChart([]);
        }
      }, 100);
    },
    // 处理重置
@@ -1200,21 +1428,21 @@
    // 处理类型详情
    handleTypeDetail(row) {
      this.$message.info(`查看类型详情:${row.typeName}`);
      // 这里可以跳转到详情页面或打开详情对话框
    },
    // 处理导出数据
    handleExportData(row) {
      this.$message.success(`正在导出 ${row.typeName} 数据...`);
      // 这里可以实现导出逻辑
    },
    // 格式化百分比
    formatPercent(value) {
      if (value === null || value === undefined) return "-";
      const num = parseFloat(value);
      if (isNaN(num)) return "-";
      return `${(num * 100).toFixed(2)}%`;
   if (value === null || value === undefined) return "-";
  const num = parseFloat(value);
  if (isNaN(num)) return "-";
  // 如果值小于1,认为是小数比例,需要乘以100
  const percentValue = num < 1 ? num * 100 : num;
  return `${percentValue.toFixed(2)}%`;
    },
    // 获取回收率样式类
@@ -1235,6 +1463,16 @@
      };
      return levelMap[level] || "info";
    },
    // 处理科室选择变化
    handleDeptChange() {
      this.loadData();
    },
    // 处理病区选择变化
    handleWardChange() {
      this.loadData();
    },
  },
};
</script>