index.vue 10.3 KB
<template>
  <div style="margin-bottom:20px;border: 1px solid #dddfe5;padding:20px;">
    <div style="font-size:16px;margin-bottom:20px;">({{tixingtype}}){{ title }}</div>
    <div style="display: flex;">
      <div style="width: 45%;display: flex;justify-content: space-evenly;">
        <div ref="chart" style="width:500px; height: 300px;"></div>
      </div>
      <div style="width: 55%;">
        <el-table :data="tiList"
          :header-cell-style="{fontSize: '14px',color:'#0009',fontWeight: 'normal',backgroundColor:'#F2F3F5'}">
          <el-table-column label="选项" min-width="50%" prop="title">
            <template slot-scope="scope">
              {{scope.row.title}}
            </template>
          </el-table-column>
          <el-table-column label="选择次数" min-width="20%">
            <template slot-scope="scope">
              <span v-if="scope.row.numci!=0"> {{scope.row.numci.countAnswer }}</span>
              <span v-else>0</span>
            </template>
          </el-table-column>
          <el-table-column prop="percentage" label="百分比" min-width="20%">
            <template slot-scope="scope">
              <span v-if="scope.row.numci !=0"> {{scope.row.numci.percentage}}%</span>
              <span v-else> 0%</span>
              <!-- {{scope.row.numci.percentage==''?0:scope.row.numci.percentage}}% -->
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
  import * as echarts from 'echarts';
  import {
    Table,
    TableColumn
  } from 'element-ui';

  export default {
    name: 'DynamicChartTable',
    components: {
      'el-table': Table,
      'el-table-column': TableColumn
    },
    props: {
      title: {
        type: String,
        required: true
      },
      tixingtype:{
        type: String,
        required: true
      },
      tableData: {
        type: Object,
        required: true
      },
      index: {
        type: String,
        required: true
      },
    },
    data() {
      return {
        dataList: [],
        tiList: [],
        selectedQuestion: []
      }
    },
    watch: {
      // 监听 tableData 的变化
      tableData: {
        handler(newVal, oldVal) {
          let obj = {
            timu: '',

          }


          // this.initChart();
        },
        deep: true // 开启深度监听,以便监听对象内部属性的变化
      }
    },
    mounted() {



      this.loadQuestionByIndex(this.index)
      this.tubiao()
      // this.processData()
    },
    onload() {

    },
    methods: {
      init(data){
        this.tableData = data;
        console.log('initdata',data);
        this.loadQuestionByIndex(this.index)
        this.tubiao()
      },
      loadQuestionByIndex(index) {

        var tiIndex = Number(index);
        const {
          groupKeys,
          cereQuestionnaireTable
        } = this.tableData;

        var list = []; // 用于存储结果

        var table = JSON.parse(cereQuestionnaireTable.question); // 解析问卷中的问题数据

        console.log(JSON.parse(cereQuestionnaireTable.question)); // 打印问题的原始数据
        // 遍历 groupKeys 中的每个条目
        // for (let i = 0; i < groupKeys.length; i++) {
        //     for (var key in table) {
        //         if (groupKeys[i].questionNumber == key) {  // 匹配 questionNumber
        //             console.log(table[key]);  // 打印当前匹配的问题

        //             // 确保该问题有选项,并且 options 数组不为空
        //             if (table[key].options && table[key].options.length != 0) {
        //                 // 遍历每个选项
        //                 for (let j = 0; j < table[key].options.length; j++) {
        //                     // 如果当前选项索引和 groupKeys[i].answer 匹配
        //                     if (j + 1 == groupKeys[i].answer) {
        //                         var info1 = {};  // 创建一个新的 info1 对象,避免引用问题
        //                         info1.title = table[key].options[j].answer;  // 选项的答案
        //                         info1.numci = groupKeys[i].countAnswer;  // 统计该选项的回答次数
        //                         info1.baifenbi = groupKeys[i].percentage;  // 该选项的百分比
        //                         list.push(info1);  // 将 info1 添加到 list 数组
        //                     }
        //                 }
        //             }
        //         }
        //     }
        // }

        var list = [{}];
            for (let key in table) {

              var itemdata = {};
              var timu =  table[parseInt(key)];
               var option = {};
               // if(timu.type =='文本') continue;
               for (let o in timu.options)
               {
                 option[parseInt( o )+ 1] = timu.options[o].answer;
               }
               // option.push({
               //   index: parseInt( o )+ 1,
               //   answer: timu.options[o].answer
               // });
               // itemdata[key] = {tikuTitle:timu.title,optionSettings: JSON.stringify(option)};
               list.push({tikuTitle:timu.title,optionSettings: JSON.stringify(option)})
               // list.push(itemdata)


            }
            console.log('list',list)

        // var querytabel = Object.keys(table).map((key, index) => {
        //     const item = table[key];

        //     const optionSettings = item.options.map((acc, index) => {
        //       index = acc.answer;
        //       return acc;
        //     }, {});
        //     const score = item.options.reduce((acc, option) => {
        //       acc[option.score] = option.score;
        //       return acc;
        //     }, {});




        //   return {
        //     id: (index + 1).toString(),
        //     questionType: item.type,
        //     questionBank: index === 0 ? "用户端题库" : "公共端题库",
        //     isRequired: item.required,
        //     questionDescription: "",
        //     optionSettings: JSON.stringify(optionSettings),
        //     tikuTitle: item.title,
        //     createDate: new Date().toISOString().slice(0, 19).replace("T", " "),
        //     createUser: "",
        //     questionCode: "",
        //     score: JSON.stringify(score),
        //     pageSize: 0,
        //     pageNumber: 0
        //   };
        // });

      // const filteredQueryTable = Object.values(querytabel);
      // 假设 this.index 是从1开始的序号
      const arrayIndex = Number(this.index); // 将序号转换为数组索引

      const question = list[arrayIndex]; // 索引是从1开始的

      const optionStats = this.initOptionStats(question.optionSettings);

      // 统计选项选择次数
      groupKeys.forEach((group) => {

        if (group.questionNumber == tiIndex) {
          const optionId = group.answer;
          const countAnswer = group.countAnswer;

          // 如果选项存在,将选择次数累加,并计算百分比
          if (optionStats[optionId]) {
            optionStats[optionId].countAnswer += countAnswer;
          } else {
            optionStats[optionId] = {
              countAnswer,
              percentage: group.percentage
            };
          }
        }

      });

      // 设置为当前选择的问题
      this.selectedQuestion = {
        ...question,
        optionStats
      }

      const optionlist = []
      // this.selectedQuestion.optionStats
      for (var key in this.selectedQuestion.optionStats) {

        const info2 = {
          tihao: 0,
          title: '',
          numci: 0,
          baifenbi: 0
        }
        const optionSettings = {
          ...JSON.parse(this.selectedQuestion.optionSettings)
        }
        info2.tihao = key
        info2.title = optionSettings[key]
        info2.numci = this.selectedQuestion.optionStats[key]
        console.log(this.selectedQuestion.optionStats[key], info2)
        optionlist.push(info2);

      }

      this.tiList = [];
      this.tiList = optionlist

    },
    // 初始化选项统计,确保每个选项都有统计数据
    initOptionStats(optionSettings) {
      console.log('1111111111111111111', optionSettings)
      const options = JSON.parse(optionSettings); // 解析 JSON 字符串

      const optionStats = {};
      for (const key in options) {
        optionStats[key] = 0; // 初始值为0
      }

      return optionStats;

    },

    // 根据选项ID获取选项描述
    getOptionDescription(optionId) {
      const optionSettings = JSON.parse(this.selectedQuestion.optionSettings);
      return optionSettings[optionId] || "无描述"; // 如果没有描述,返回"无描述"
    },

    tubiao() {
      const res = this.tiList.map(function(item) {
        return {
          name: item.title,
          value: item.numci.countAnswer || 0 /////
        }
      })
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          //  bottom: '30',
          // left: 'center',
          x: 'right', // 可设定图例在左、右、居中
          y: 'bottom', // 可设定图例在上、下、居中
          left: 'center'
        },
        series: [{
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center',

          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          color: ['#3f9b6a', 'rgb(61,182,211)', 'rgb(126, 211, 146)', 'rgb(200, 40, 211)', 'rgb(171, 184, 211)',
            'rgb(211, 169, 150)', 'rgb(185, 211, 16)'
          ],
          data: res,
        }]
      }
      const chartDom = this.$refs.chart;
      const myChart = echarts.init(chartDom);
      option && myChart.setOption(option);
    }
  },
  beforeDestroy() {
    if (this.$refs.chart) {
      const myChart = echarts.getInstanceByDom(this.$refs.chart);
      if (myChart) {
        window.removeEventListener('resize', myChart.resize);
        myChart.dispose();
      }
    }
  }
  };
</script>

<style scoped>
  /* 添加一些基本样式 */
</style>