<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:400px;"></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: [],
        obj:{
    "code": "200",
    "data": {
        "genderStatistics": [
            {
                "gender": "男",
                "genderNumber": 11
            }
        ],
        "maleNumber": 11,
        "femaleNumber": 0,
        "unknownGenderNumber": 0,
        "countNumber": 11,
        "sumResTime": 191.86,
        "todayNumber": 11,
        "averageDuration": 17,
        "groupKeys": "[GroupKey(questionNumber=1, answer=1, countAnswer=2, percentage=18.00), GroupKey(questionNumber=1, answer=2, countAnswer=4, percentage=36.00), GroupKey(questionNumber=1, answer=3, countAnswer=3, percentage=27.00), GroupKey(questionNumber=1, answer=4, countAnswer=2, percentage=18.00)]",
        "cereQuestionnaireTable": {
            "id": "141",
            "title": "1231",
            "startDate": "2024-11-22",
            "endDate": "2024-11-30",
            "publishPort": "H5端",
            "questionnaireType": "社会调查问卷",
            "estimatedTime": "12",
            "remarks": "123",
            "filler": "公众",
            "fillingConditions": "可重复填写",
            "coverImage": "https://jy.scjysm.asia:18086/mefile/file/2024/11/f883786057004b1596d569b212471a27_ac6e8eb7cc9e9be4f7f2e7351ddf872.jpg",
            "rewardForParticipation": "不设置奖励",
            "rewardContent": "",
            "questionId": "361",
            "responseStatus": "5",
            "reviewStatus": "3",
            "queryStatus": "",
            "reviewComments": "通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过和嘎尔uiorg和农村 通过",
            "opinionDelisting": "到期下架",
            "createTime": "2024-11-22 16:24",
            "createUser": "213",
            "updateTime": "2024-11-22 16:32",
            "cereQuestionManagements": [
                {
                    "id": "361",
                    "questionType": "单选",
                    "questionBank": "公共端题库",
                    "isRequired": "必填",
                    "questionDescription": "",
                    "optionSettings": "{\"1\":\"123\"}",
                    "tikuTitle": "asdasdas",
                    "createDate": "2024-11-22 16:23",
                    "createUser": "",
                    "questionCode": "",
                    "score": "{\"1\":1}",
                    "pageSize": 0,
                    "pageNumber": 0
                }
            ],
            "countNumber": 0,
            "question": "{\"1\":{\"choose\":\"\",\"type\":\"单选\",\"title\":\"asdasdas\",\"required\":\"必填\",\"options\":[{\"score\":\"1\",\"answer\":\"123\",\"disabled\":false}]}}",
            "needName": "",
            "needPhone": "",
            "needGender": "",
            "needOpinion": "",
            "pageSize": 0,
            "pageNumber": 0
        }
    },
    "errorData": {},
    "message": "成功",
    "name": "",
    "describe": "",
    "json": ""
}
      }
    },
    watch: {
      // 监听 tableData 的变化
      tableData: {
        handler(newVal, oldVal) {
          let obj = {
            timu: '',

          }


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



      this.loadQuestionByIndex(this.index)
      this.tubiao()
      console.log(JSON.parse(this.obj))
      // 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); // 解析问卷中的问题数据


        // 遍历 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)


            }


        // 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]

        optionlist.push(info2);

      }

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

    },
    // 初始化选项统计，确保每个选项都有统计数据
    initOptionStats(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: ['30%', '60%'],
          center: ['50%', '40%'], // 调整饼图位置
          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();
      }
    }
    this.dataList  =  []
        this.tiList  =  []
      this.selectedQuestion  =  []
  }
  };
</script>

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