<template>
  <div >
    <el-dialog :title="tmpVote.title" @open="voteResultOpen"  :visible.sync="isShow" append-to-body class="vote-item-dialog">
    <!-- 调查结果 -->
      <!-- <div class="prop">调查主题：{{tmpVote.title}}</div> -->
      <el-collapse v-model="activeNames" v-if="isShow">
        <el-collapse-item v-for="(votesubject,index) in tmpVote.voteSubject" :key="votesubject.voteID+votesubject.ID" :name="votesubject.ID">
          <template slot="title">
            <!-- 显示对应的调查项类型 -->
            <span class="item-title">
              {{ index+1 }} . {{votesubject.subject}}&nbsp;[{{votesubject.typeName}}]
            </span>
          </template>
          <div class="vote-content">
            <el-col :span="12">
              <el-table :data="votesubject.voteItem" width="100%" >
                <el-table-column type="index" label="序号" align="center"></el-table-column>
                <el-table-column label="选项" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <!-- 如果选项是图片 -->
                    <template v-if="votesubject.type === 'I'">
                      <img :src="scope.row.imagePath" style="float:left;padding:5px 10px;max-width:120px;" />
                      <div style="float:rigth;">
                        描述：<span>{{scope.row.imageInfo}}</span> <br/>
                        转向链接：<span>{{scope.row.linkURL}}</span>
                      </div>
                    </template>
                    <template v-else>{{scope.row.item}}</template>
                  </template>
                </el-table-column>
                <el-table-column prop="score" width="100" label="票数" align="center"></el-table-column>
                <el-table-column prop="percent" width="100" label="比例" align="center"></el-table-column>
              </el-table>
            </el-col>
            <el-col :span="12">
              <template v-if="!notShowSubjectType.includes(votesubject.type)">
                <div style="text-align:center;padding-bottom:20px;">
                  <span class="selected-type" @click.stop="changeChart('bar',votesubject.ID)" :id="'btn-pie-'+votesubject.ID" style="cursor: pointer;">
                    <i class="fa fa-pie-chart"></i> 饼状图
                  </span>
                  <span style="padding:0 20px"></span>
                  <span @click.stop="changeChart('pie',votesubject.ID)" :id="'btn-bar-'+votesubject.ID" style="cursor: pointer;">
                    <i class="fa fa-bar-chart"></i> 柱状图
                  </span>
                </div>
                <div :id="'voteChart_'+votesubject.ID" style="width:100%; height:300px;margin:auto;"></div>
                <div :id="'voteChart_bar_'+votesubject.ID" style="width:100%; height:300px;margin:auto;"></div>
              </template>
            </el-col>
          </div>
        </el-collapse-item>
      </el-collapse>
      <div slot="footer">
        <el-button type="primary" @click="isShow = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import util from '@src/common/util.js'
export default {
  data() {
    return {
      activeNames: [], // 折叠控制参数
      notShowSubjectType: ['W'] // 不展示echarts图片的投票类型
    }
  },
  computed: {
    isShow: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    }
  },

  methods: {
    getSubjectTypeName(type){
      if (!type){
        return ''
      }
      let o = this.voteSubjectType.find(i => i.key === type)
      return o ? o.value : ''
    },
    changeChart(type, subID) {
      let barBtn = document.querySelector('#btn-bar-' + subID)
      let pieBtn = document.querySelector('#btn-pie-' + subID)
      let barChart = document.querySelector('#voteChart_' + subID)
      let pieChart = document.querySelector('#voteChart_bar_' + subID)

      barBtn && barBtn.setAttribute('class', type === 'bar' ? '' : 'selected-type')
      pieBtn && pieBtn.setAttribute('class', type === 'bar' ? 'selected-type' : '')
      barChart && barChart.setAttribute('class', type === 'bar' ? 'show' : 'hide')
      pieChart && pieChart.setAttribute('class', type === 'bar' ? 'hide' : 'show')

      type === 'pie' && this.setPieChartOptions()
      type === 'bar' && this.setBarChartOptions()
    },
    async voteResultOpen() {
      this.tmpVote.voteSubject.forEach(row => {
        this.activeNames.push(row.ID)
      })

      try {
        await util.loadJS('lib/echarts.common.min.js')
      } catch (e) {
        console.error('echarts.common.min.js is missing', e.toString())
        return
      }

      this.tmpVote.voteSubject.forEach(sub => {
        this.$set(sub, 'typeName', this.getSubjectTypeName(sub.type))
        if (sub.voteItem && sub.voteItem.length){
          let totalScoreArr = sub.voteItem.map(item => item.score)
          // let totalScore = eval(totalScoreArr.join('+')) // eslint报错
          let totalScore = new Function('return ' + totalScoreArr.join('+'))()
          sub.voteItem.forEach(item => {
            let percent = !totalScore ? Math.round(100 / sub.voteItem.length) : Math.round(item.score / totalScore * 100)
            this.$set(item, 'percent', percent + '%')
          })
        }
      })

      this.setPieChartOptions()
      this.setBarChartOptions()
    },

    setPieChartOptions() {
      this.tmpVote.voteSubject.forEach(row => {
        if (!this.notShowSubjectType.includes(row.type)) {
          let voteChartID = 'voteChart_' + row.ID
          let voteChartDIV = document.getElementById(voteChartID)
          let voteChart = window.echarts.init(voteChartDIV)
          // 指定图表的配置项和数据
          let voteItems = row.voteItem
          let i = 0
          let voteDataArray = voteItems.map(o => {
            i++
            return {value: o.score, name: row.type === 'I' ? i : o.item}
          })
          let voteOption = {
            tooltip: {
              trigger: 'item',
              formatter: '{b},投票结果:{c}'
            },
            series: [
              {
                name: '投票结果',
                type: 'pie',
                center: ['50%', '50%'],
                data: voteDataArray.sort(function(a, b) {
                  return a.value - b.value
                }),
                animationType: 'scale',
                animationEasing: 'elasticOut',
                animationDelay: function(idx) {
                  return Math.random() * 200
                }
              }
            ]
          }
          voteChart.setOption(voteOption)
        }
      })
    },
    setBarChartOptions() {
      this.tmpVote.voteSubject.forEach(row => {
        if (!this.notShowSubjectType.includes(row.type)) {
          let voteChartID = 'voteChart_bar_' + row.ID
          let voteChartDIV = document.getElementById(voteChartID)
          let voteChart = window.echarts.init(voteChartDIV)
          // 指定图表的配置项和数据

          let category = []
          let datas = []
          let i = 0
          for (let item of row.voteItem) {
            i++
            if (item.score) {
              category.push(row.type === 'I' ? i : item.item)
              datas.push(item.score)
            }
          }

          let voteOption = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            xAxis: {
              name: '选项',
              type: 'category',
              data: category,
              axisTick: {
                alignWithLabel: true
              }
            },
            yAxis: {
              name: '票数',
              type: 'value'
            },
            series: [
              {
                name: '投票结果',
                barWidth: '60%',
                center: ['50%', '50%'],
                data: datas,
                type: 'bar'
              }
            ]
          }
          voteChart.setOption(voteOption)
          voteChartDIV && voteChartDIV.setAttribute('class', 'hide')
        }
      })
    }
  },
  props: {
    show: {
      type: Boolean,
      required: true
    },
    tmpVote: {
      type: Object,
      required: true
    },
    voteSubjectType: {
      required: true
    }
  }
}
</script>
<style>
.selected-type {
  color: #28b06e;
  font-weight: bold;
}
.vote-item-dialog .el-dialog {
  width: 1200px;
}
@media (max-width: 480px) {
  .vote-item-dialog .el-dialog {
    width: 96%;
  }
}
</style>
<style scoped>
.prop{
  font-size:24px;
  font-weight:bold;
  padding: 20px 10px;
}
</style>
