<style lang="scss">
.content {
  // height: 80vh;
}
// 新
.item {
  font-size: 14px;
  margin-bottom: 20px;
  .item-title {
    margin-bottom: 10px;
    color: #606266;
    .title-num {
      display: inline-block;
      // width:50px;
      font-weight: bold;
    }
    .title-header {
      // font-weight: 600;
    }
    .title-type {
      margin-left: 10px;
    }
    .title-download {
      color: #409eff;
      cursor: pointer;
    }
  }
  .item-content {
    // margin-left:60px;
    display: flex;
    .el-table {
      flex: 1.5;
    }

    div {
      flex: 1;
    }
  }
}
</style>
<template>
  <section>
    <p><span>信息管理></span>问卷统计</p>
    <div class="content">
      <div class="download-all" style="display: inline-block; float: right">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="downloadAll"
          >导出excel</el-button
        >
      </div>
      <div class="item" v-for="(item, index) in results" :key="index">
        <div class="item-title">
          <span class="title-num">第{{ index + 1 }}题：</span>
          <span class="title-header">{{ item.label }}</span>
          <span class="title-type">{{ item.type | getType }}</span>
          <span class="title-download" @click="downloadItem(item)"
            >导出Excel</span
          >
        </div>
        <!-- <div
          class="item-content"
          v-if="item.type == 'input' || item.type == 'textarea'"
        >
          【答案】：<span v-for="(item1, index) in item.result" :key="index"
            >{{ item1 }}{{ index == item.result.length - 1 ? "" : "、" }}</span
          >
        </div> -->
        <div
          class="item-content"
          v-if="item.type == 'input' || item.type == 'textarea'"
        >
          【答案】：<el-button type="primary" size="mini" @click="showItemResult(item)">查看详情</el-button>
        </div>
        <div
          class="item-content"
          v-if="item.type == 'radio' || item.type == 'checkbox'"
        >
          <el-table :data="item.items" border>
            <el-table-column prop="label" label="选项"> </el-table-column>
            <el-table-column prop="times" label="次数"> </el-table-column>
            <el-table-column prop="sale" label="比例">
              <template slot-scope="scope">
                <el-progress :percentage="scope.row.sale"></el-progress>
              </template>
            </el-table-column>
          </el-table>
          <div
            :id="`chartPie${index}`"
            style="width: 500px; height: 250px"
          ></div>
          <div
            :id="`chartBar${index}`"
            style="width: 500px; height: 250px"
          ></div>
        </div>
      </div>
    </div>
     <!-- 查看答题详情 -->
    <el-dialog
        :title="dialogTitle"
        :close-on-click-modal="false"
        :visible.sync="dialogVisible"
      >
        <div class="content">
            <div class="filter">
              <el-form
                size="small"
                label-width="70px"
                :inline="true"
                label-position="left"
              >
                <el-form-item label="">
                  <el-input
                    clearable
                    placeholder="请输入标题"
                    v-model="form.name"
                    @clear="search"
                    @keyup.enter.native="search"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="search">搜索</el-button>
                </el-form-item>
                <el-form-item style="float: right">
                  <el-button
                    type="primary"
                    icon="el-icon-download"
                    size="mini"
                    @click="downloadItem(cur_item)"
                    >导出excel</el-button
                  >
                </el-form-item>
              </el-form>
            </div>
            <el-table
              class="table"
              :data="analyseDataList"
              height="50vh"
              border
              v-loading="loading"
              default-expand-all
              row-key="id"
              style="width: 100%"
            >
            <el-table-column
        label="序号"
        type="index"
        width="50"
        align="center">
</el-table-column>
              <el-table-column v-for="(item, key) in this.headers" :key="key" :prop="item" :label="item"> </el-table-column>
            </el-table>
            <Page
              ref="pageButton"
              :current="form.page"
              :page_size="form.page_size"
              :total="total"
              @pageChange="gopage"
            />
        </div>
    </el-dialog>
  </section>
</template>
<script>
import Page from "../../components/Page";
import echarts from "echarts";
export default {
  components: {
    Page,
  },
  data() {
    return {
      //   checked: [],
      form:{},
      total: 1,
      loading: false,
      results: [],
      dialogTitle:"",
      dialogVisible:false,
      analyseDataList:[],
      headers:[],
      cur_item:null
    };
  },
  filters: {
    getType(val) {
      if ((val == "input") | (val == "textarea")) {
        return "【填空题】";
      } else if (val == "radio") {
        return "【单选题】";
      } else if (val == "checkbox") {
        return "【多选题】";
      }
    },
  },

  methods: {
    gopage(size) {
      if (size) {
        this.form.page_size = size;
      }
      this.form.page = this.$refs.pageButton.page;
      this.showItemResult();
    },
    downloadAll() {
      let message_id = this.$route.query.id;
      let type = this.$route.query.type;
      this.$api
        .downloadAnalyseAll({ message_id: message_id, type: type })
        .then((res) => {
          var elink = document.createElement("a");
          let blob = new Blob([res.data], {
            type: "application/vnd.ms-excel,charset=UTF-8",
          });
          let objUrl = URL.createObjectURL(blob);
          let file_name = decodeURIComponent(
            res.headers["content-disposition"].split("=")[1]
          );
          console.log(file_name);
          elink.download = file_name;
          elink.style.display = "none";
          elink.href = objUrl;
          document.body.appendChild(elink);
          elink.click();
          document.body.removeChild(elink);
          this.download_loading = false;
        });
    },
    downloadItem(item) {
      let message_id = this.$route.query.id;
      let type = this.$route.query.type;
      this.$api
        .downloadAnalyseItem({
          message_id: message_id,
          type: type,
          item: item.label,
        })
        .then((res) => {
          var elink = document.createElement("a");
          let blob = new Blob([res.data], {
            type: "application/vnd.ms-excel,charset=UTF-8",
          });
          let objUrl = URL.createObjectURL(blob);
          let file_name = decodeURIComponent(
            res.headers["content-disposition"].split("=")[1]
          );
          console.log(file_name);
          elink.download = file_name;
          elink.style.display = "none";
          elink.href = objUrl;
          document.body.appendChild(elink);
          elink.click();
          document.body.removeChild(elink);
          this.download_loading = false;
        });
    },
    showItemResult(item) {
      this.dialogTitle = '"'+item.label+'"答案详情'
      let message_id = this.$route.query.id;
      let type = this.$route.query.type;
      var parm = this.form;
      parm.message_id = message_id
      parm.type = type
      parm.item = item.label
      this.$api.showAnalyseItem(parm).then((res)=>{
        let data = res.data.data
        this.headers = Object.keys(data[0])
        this.analyseDataList = data
      })
      this.dialogVisible = true;
      this.cur_item = item;
    },
    search() {
      let item = this.cur_item;
      let parm = this.form;
      let message_id = this.$route.query.id;
      let type = this.$route.query.type;
      parm.message_id = message_id
      parm.type = type
      parm.item = item.label
      this.$api.showAnalyseItem(parm).then((res)=>{
        let data = res.data.data
        this.headers = Object.keys(data[0])
        this.analyseDataList = data
      })
    },
    getData() {
      let message_id = this.$route.query.id;
      let type = this.$route.query.type;
      this.$api
        .getMessageSurveyQuestionAnalyse({ id: message_id, type: type })
        .then((res) => {
          this.results = res.data.data;
          this.results.forEach((item, index) => {
            this.$nextTick(function () {
              this.getEcharts(item, index);
            });
          });
        });
    },
    getEcharts(item, index) {
      var myChart = this.$echarts.init(
        document.getElementById(`chartBar${index}`)
      );
      var myChart1 = this.$echarts.init(
        document.getElementById(`chartPie${index}`)
      );
      let dataPie = [];
      let dataBarX = [];
      let dataBarY = [];
      let colors = [
        "#9379ff",
        "#62A2FF",
        "#FFD053",
        "#FF9F41",
        "#FF542C",
        "#FE8463",
        "#9BCA63",
        "#FAD860",
        "#F3A43B",
        "#60C0DD",
        "#D7504B",
        "#C6E579",
        "#F4E001",
        "#F0805A",
        "#26C0C0",
      ];
      let pieColors = []
      item.items.forEach((item, index) => {
        dataPie.push({
          name: item.label,
          value: item.times,
          color:colors[index],
          itemStyle : {
          normal : {
              label : {
                show : true,
                color:colors[index]
              },
              labelLine : {
                show : true,
                color:colors[index]
              }
            },
          },
        });
        dataBarX.push(item.label);
        dataBarY.push({
          sale: item.sale,
          value: item.times,
          itemStyle: { color: colors[index] },
        });
      });
      dataPie = dataPie.filter(function(x){if(x.value==0){return false}return true})
      dataPie.forEach((item,index)=>{
          pieColors.push(item.color)
        })
      let option = {
        title: {
          subtext: "填报次数",
        },
        color: ["#5066FF"],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        grid: {
          left: "2%",
          right: "4%",
          bottom: "3%",
          // top:'0px',
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: dataBarX,

            axisTick: {
              alignWithLabel: true,
            },
            axisLine: {
              lineStyle: {
                color: "#D4D8EE",
                width: 2,
                type: "dotted",
              },
            },
            axisLabel: {
              // formatter:function(val) {
              //     console.log(val,"")
              //     return '中国科' //对每个标签处理后的结果（通过js字符串方法处理）
              // },
              formatter: function (value, index) {
                // 10 6 这些你自定义就行
                  var v = value.substring(0, 6) + '...'
                  return value.length > 10 ? v : value
              },
              // x轴字体颜色
              textStyle: {
                color: "#999999",
                // lineHeight: 20,
                fontSize: 12,
              },
              align: "center",
              // padding:[10,0 ,0,-40],
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            boundaryGap: ["0%", "20%"],
            axisTick: {
              show: false,
            },
            minInterval: 1,
            axisLine: {
              show: false,
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: "#666666", //更改坐标轴文字颜色
                fontSize: 14, //更改坐标轴文字大小
              },
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
              },
            },
            // data:['0' , '100' , '200' , '300,400]
          },
        ],
        series: [
          {
            name: "次数",
            type: "bar",
            barWidth: "30px",
            data: dataBarY,
            itemStyle: {
              //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
              normal: {
                //柱形图圆角，初始化效果
                barBorderRadius: [10, 10, 10, 10],
                label: {
                  show: true,
                  position: "top",
                  formatter: function (v) {
                    return v.data.sale ? v.data.sale + "%" : "0%";
                  },
                },
              },
            },
          },
        ],
      };
      let option1 = {
        // backgroundColor: '#dddddd',
        // title: {
        //     text: 'Customized Pie',
        //     left: 'center',
        //     top: 20,
        //     textStyle: {
        //         color: '#ccc'
        //     }
        // },
        color: pieColors,
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },

        series: [
          {
            name: "访问来源",
            type: "pie",
            radius: "65%",
            // center: ['50%', '50%'],
            data: dataPie.sort(function (a, b) {
              return a.value - b.value;
            }),
            // roseType: 'radius',
            // label: {
            //   color: "rgba(102, 102, 102,1)",
            //   fontSize: 14,
            // },
            // labelLine: {
            //   // show:false,
            //   lineStyle: {
            //     color: "rgba(000, 000, 000, 0.1)",
            //   },
            //   smooth: 0.2,
            //   length: 20,
            //   length2: 8,
            // },
            // itemStyle: {
            //     // color: '#c23531',
            //     // shadowBlur: 200,
            //     // shadowColor: 'rgba(0, 0, 0, 0.5)'
            //     normal:{
            //       label:{
            //           show: function(val){
            //             console.log(val,222222222)
            //             return false
            //           },
            //         },
            //         labelLine: {
            //             show: true
            //         }
            //     }

            // },
             data: dataPie.sort(function (a, b) {
              return a.value - b.value;
            }),
            animationType: "scale",
            animationEasing: "elasticOut",
            animationDelay: function (idx) {
              return Math.random() * 200;
            },
          },
        ],
      };
      myChart.setOption(option);
      myChart1.setOption(option1);
    },
  },
  mounted() {
    this.results.forEach((item, index) => {
      this.$nextTick(function () {
        this.getEcharts(item, index);
      });
    });
  },
  created() {
    this.getData();
  },
};
</script>
