<template>
  <div v-loading="isloading">
    <div style="background: #fff; padding: 10px 0; height: 100%">
      <div class="sd_person_button">
        <span @click="setType(2)" :class="{ active: type == 2 }"
          >个人项目评价</span
        >
        <span @click="setType(1)" :class="{ active: type == 1 }"
          >课程目标设置</span
        >
        <!-- <span @click="setType(3)" :class="{ active: type == 3 }">其他项目</span> -->
      </div>
      <div style="display: flex; width: 100%; height: calc(100% - 50px)">
        <div
          id="person_canvas1"
          class="echart"
          v-show="type == 1"
          style="
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
          "
        >
          <span v-if="!eJson">暂无数据</span>
        </div>
        <div
          id="person_canvas2"
          class="echart"
          v-show="type == 2"
          style="
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
          "
        >
          <!-- <div class="box2" v-show="work.length ? true : false">
            <div v-for="(item,index) in work" :key="index" class="target_box">
              <div class="target_task">
                <span>第{{item.stage+1}}阶段</span>
                <span>任务{{item.task+1}}</span>
              </div>
              <div class="target_content_box">
                <div v-for="(target,k) in item.work" :key="index+'-'+k"
                  :style="{width:(target.count / item.count * 100)+'%',backgroundColor:color[k]}">

                  <el-tooltip :content="target.name+' '+target.count">
                    <span class="targetA">{{target.count}}</span>
                  </el-tooltip>
                </div>

              </div>

            </div>
          </div>
          <span v-show="!work.length ? true : false">暂无数据</span> -->
          <span v-show="!randarJson.length ? true : false">暂无数据</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ["userid", "courseid"],
  data() {
    return {
      randarJson: [],
      isloading: false,
      chartObj2: null,
      chartObj3: null,
      color: [],
      workW: [],
      work: [],
      eJson: "",
      type: 2,
      option2: {
        //color:colors,
        tooltip: {
          trigger: "item",
        },
        legend: {
          left: "50",
          top: "center",
        },
        series: {
          type: "sunburst",
          data: [],
          radius: [20, "80%"],
          itemStyle: {
            borderRadius: 7,
            borderWidth: 2,
          },
          label: {
            show: true,
            fontSize: 10,
          },
        },
      },
      option3: {
        // title: {
        //   text: "项目活跃度:不同任务的学习时间占比",
        //   textStyle: {
        //     fontSize: 13,
        //   },
        // },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // Use axis to trigger tooltip
            type: "shadow", // 'shadow' as default; can also be 'line' or 'shadow'
          },
        },
        grid: {
          left: "15%",
          right: "15%",
          bottom: "15%",
          top: "15%",
        },
        xAxis: {
          type: "value",
        },
        yAxis: {
          type: "category",
          data: ["阶段1", "阶段2", "阶段3", "阶段4", "阶段5"],
        },
        legend: {
          show: false,
        },
        series: [
          {
            name: "任务1",
            type: "bar",
            stack: "total",
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [0, 0, 0, 0, 0],
          },
          {
            name: "任务2",
            type: "bar",
            stack: "total",
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [0, 0, 0, 0, 0],
          },
          {
            name: "任务3",
            type: "bar",
            stack: "total",
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [0, 0, 0, 0, 0],
          },
          {
            name: "任务4",
            type: "bar",
            stack: "total",
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [0, 0, 0, 0, 0],
          },
          {
            name: "任务5",
            type: "bar",
            stack: "total",
            label: {
              show: true,
            },
            emphasis: {
              focus: "series",
            },
            data: [0, 0, 0, 0, 0],
          },
        ],
      },
      radarOption: {
        splitNumber: 5,
        tooltip: {
          triggerOn: "mousemove",
          //雷达图的tooltip不会超出div，也可以设置position属性，position定位的tooltip 不会随着鼠标移动而位置变化，不友好
          confine: true,
          enterable: true, //鼠标是否可以移动到tooltip区域内
          backgroundColor: "rgba(255,255,255,0.7)",
          textStyle: {
            // 文字样式
            align: "left",
          },
          left: "right",
          top: "bottom",
        },
        radar: {
          radius: ["0%", "70%"],
          shape: "circle",
          center: ["50%", "50%"],
          axisName: {
            textStyle: {
              // 文字样式
              color: "#58a5e6",
            },
            formatter: function (value, indicator) {
              // value = value.replace(/\S{2}/g, function (match) {
              //   return match + "\n";
              // });
              return value;
            },
          },
          indicator: [
            // 雷达图的指示器，用来指定雷达图中的多个变量（维度）
          ],
        },
        // 雷达图背景的颜色，在这儿随便设置了一个颜色，完全不透明度为0，就实现了透明背景
        splitArea: {
          show: true,
          areaStyle: {
            color: "rgba(255,0,0,0)", // 图表背景的颜色
          },
        },
        splitLine: {
          show: true,
          lineStyle: {
            width: 1,
            color: "rgba(131,141,158,.1)", // 设置网格的颜色
          },
        },
        series: [
          {
            name: "目标得分占比", // tooltip中的标题
            type: "radar", // 表示是雷达图
            symbol: "circle", // 拐点的样式，还可以取值'rect','angle'等
            symbolSize: 8, // 拐点的大小
            areaStyle: {
              normal: {
                width: 1,
                opacity: 0.2,
              },
            },
            data: [
              {
                // 设置各个指标原始值
                value: [],
                // 设置区域边框和区域的颜色
                itemStyle: {
                  normal: {
                    color: "#58a5e6",
                    lineStyle: {
                      color: "#58a5e6",
                    },
                  },
                },
              },
            ],
          },
        ],
      },
    };
  },
  methods: {
    setChart() {
      // 雷达图显示的标签
      let newPromise = new Promise((resolve) => {
        resolve();
      });
      //然后异步执行echarts的初始化函数
      newPromise.then(() => {
        if (this.type == 1 && this.eJson) {
          const chartObj2 = this.$echarts.init(
            //劳动课程
            this.$el.querySelector("#person_canvas1")
          );
          // this.option2.series.data = [
          //   {
          //     name: "信息意识",
          //     value: 15,
          //     children: [
          //       {
          //         name: "信息应用意识",
          //         value: this.randomNum(1, 5),
          //       },
          //       {
          //         name: "信息安全意识",
          //         value: this.randomNum(1, 5),
          //       },
          //       {
          //         name: "信息感知意识",
          //         value: this.randomNum(1, 5),
          //       },
          //     ],
          //   },
          //   {
          //     name: "信息社会责任",
          //     value: 15,
          //     children: [
          //       {
          //         name: "信息伦理道德",
          //         value: this.randomNum(1, 5),
          //       },
          //       {
          //         name: "信息法律法规",
          //         value: this.randomNum(1, 10),
          //       },
          //     ],
          //   },
          //   {
          //     name: "信息知识与技能",
          //     value: 15,
          //     children: [
          //       {
          //         name: "信息应用技能",
          //         value: 5,
          //       },
          //       {
          //         name: "信息科学知识",
          //         value: 10,
          //       },
          //     ],
          //   },
          //   {
          //     name: "信息思维与行为",
          //     value: 15,
          //     children: [
          //       {
          //         name: "信息思维",
          //         value: this.randomNum(1, 10),
          //       },
          //       {
          //         name: "信息行为",
          //         value: this.randomNum(1, 5),
          //       },
          //     ],
          //   },
          // ];
          var res = this.eJson;
          var _array = [];
          let i = 0;
          for (var item in res) {
            let num = Object.keys(res);
            let count = 10 / num.length;
            let _item = res[item];
            _array.push({ name: _item.name, value: count, children: [] });
            let j = 0;
            for (var item2 in _item.child) {
              let num2 = Object.keys(_item.child);
              let count2 = count / num2.length;
              let _item2 = _item.child[item2];
              _array[i].children.push({
                name: _item2.name,
                value: count2,
                children: [],
              });
              for (var item3 in _item2.child) {
                let num3 = Object.keys(_item2.child);
                let count3 = count2 / num3.length;
                let _item3 = _item2.child[item3];
                _array[i].children[j].children.push({
                  name: _item3.name,
                  value: count3,
                });
              }
              j++;
            }
            i++;
          }
          this.option2.series.data = _array;
          // 初始化雷达图
          this.chartObj2 = chartObj2;
          this.chartObj2.setOption(this.option2);
        } else if (this.type == 2) {
          // const chartObj3 = this.$echarts.init(
          //   //劳动课程
          //   this.$el.querySelector("#person_canvas2")
          // );
          // let _array21 = [];
          // let _array22 = [];
          // let _array23 = [];
          // let _array24 = [];
          // let _array25 = [];
          // for (var i = 0; i < 5; i++) {
          //   //   this.option.series[0].data[i].value = this.randomNum(30, 80);
          //   _array21.push(this.randomNum(2, 20));
          //   _array22.push(this.randomNum(2, 20));
          //   _array23.push(this.randomNum(2, 20));
          //   _array24.push(this.randomNum(2, 20));
          //   _array25.push(this.randomNum(2, 20));
          // }
          // this.option3.series[0].data = _array21;
          // this.option3.series[1].data = _array22;
          // this.option3.series[2].data = _array23;
          // this.option3.series[3].data = _array24;
          // this.option3.series[4].data = _array25;
          if (this.randarJson.length) {
            const chartObj3 = this.$echarts.init(
              //劳动课程
              this.$el.querySelector("#person_canvas2")
            );
            var b = this.randarJson.reduce(function (acc, obj) {
              var found = acc.findIndex(function (element) {
                return element.target[0] === obj.target[0];
              });

              if (found !== -1) {
                acc[found].count += obj.count;
                acc[found].value += obj.value;
              } else {
                acc.push(obj);
              }

              return acc;
            }, []);

            b.forEach(function (element) {
              element.value /= element.count;
            });
            
            this.randarJson = b;

            let radarOption = JSON.parse(JSON.stringify(this.radarOption));
            for (var i = 0; i < this.randarJson.length; i++) {
              radarOption.radar.indicator.push({
                name: this.randarJson[i].target[0],
                max: 5,
              });
              radarOption.series[0].data[0].value.push(this.randarJson[i].value);
            }

            this.chartObj3 = chartObj3;
            this.chartObj3.setOption(radarOption);
          }

          // var _work = []
          // this.color = []
          // for (var i = 0; i < this.workW.length; i++) {
          //   _work[i] = { stage: this.workW[i].stage, task: this.workW[i].task, work: [], count: 0 }
          //   for (var j = 0; j < this.workW[i].work.length; j++) {
          //     for (var k = 0; k < this.workW[i].work[j].target.length; k++) {
          //       this.color.push(this.color16())
          //       _work[i].work.push(this.workW[i].work[j].target[k])
          //       _work[i].count += this.workW[i].work[j].target[k].count
          //     }
          //   }
          // }
          // this.work = _work;
          // console.log(_work);
          // this.$forceUpdate();
        }
      });
      let _this = this;
      window.addEventListener("resize", () => {
        // if (_this.chartObj2) {
        //   _this.chartObj2.resize();
        //   _this.chartObj3.resize();
        // }

        if (_this.chartObj2) {
          _this.chartObj2.resize();
        }
        if (_this.chartObj3) {
          _this.chartObj3.resize();
        }
      });
    },
    randomNum(minNum, maxNum) {
      switch (arguments.length) {
        case 1:
          return parseInt(Math.random() * minNum + 1, 10);
          break;
        case 2:
          return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
          break;
        default:
          return 0;
          break;
      }
    },
    getInfo() {
      this.isloading = true;
      let params = {
        uid: this.userid,
        cid: this.courseid,
      };
      if (!this.userid) {
        return;
      }
      this.ajax
        .get(this.$store.state.api + "getUserInfo", params)
        .then((res) => {
          this.isloading = false;
          let chapters = JSON.parse(res.data[2][0].chapters);
          var tool = 0;
          let workJson = [];
          let _pWork = res.data[3];
          let _allWork = res.data[4];
          let _allComment = res.data[5];
          var b = res.data[6].reduce((result, item) => {
            const key = item.stage + "-" + item.task;
            if (!result[key]) {
              result[key] = item;
            }
            return result;
          }, {});

          // 将结果转换为数组形式
          b = Object.values(b);
          let _isWorks = b;
          let workEvalist = res.data[7];
          var randarJson = [];
          var randarAarray = [];

          this.eJson = res.data[2][0].content
            ? JSON.parse(res.data[2][0].content)
            : "";

          for (var i = 0; i < chapters.length; i++) {
            workJson[i] = { tool: 0, ptool: 0, work: 0, ishuo: 0, isCan: 0 };
            for (
              var j = 0;
              j < chapters[i].chapterInfo[0].taskJson.length;
              j++
            ) {
              // 1、电子白板，3、思维导图，6协同文档，7思维网格 16、作业提交,40.项目-学生互评 41.项目-下拉选择题 42.项目-录音功能
              let _toolsAarry = [1, 3, 6, 7, 16, 15, 4, 40, 41, 42];
              for (
                var k = 0;
                k < chapters[i].chapterInfo[0].taskJson[j].toolChoose.length;
                k++
              ) {
                if (
                  _toolsAarry.indexOf(
                    chapters[i].chapterInfo[0].taskJson[j].toolChoose[k].tool[0]
                  ) != -1
                ) {
                  tool++;
                  workJson[i].tool++;
                }
              }
            }

            for (var k = 0; k < _pWork.length; k++) {
              if (_pWork[k].stage == i) {
                workJson[i].ptool++;
              }
            }
            for (var k = 0; k < _allComment.length; k++) {
              if (_allComment[k].stage == i) {
                workJson[i].ishuo++;
              }
            }
          }
          this.userinfo = res.data[0][0];
          this.ccount = tool;
          this.islearn = tool - parseInt(res.data[1][0].vcount);

          this.iscount = res.data[1][0].vcount;
          this.vcount = 0;

          for (var i = 0; i < workJson.length; i++) {
            if (workJson[i].ptool > workJson[i].tool) {
              workJson[i].work = 5;
            } else if (workJson[i].tool === 0) {
              workJson[i].work = 5;
            } else {
              workJson[i].work = Math.round(
                ((workJson[i].ptool / workJson[i].tool) * 100) / 20
              );
            }
            if (workJson[i].ptool) {
              workJson[i].isCan = 1;
            }
          }
          this.workJson = workJson;

          this.setChart();
          let _workW = [];
          for (var i = 0; i < _isWorks.length; i++) {
            for (var k = 0; k < workEvalist.length; k++) {
              if (
                chapters[_isWorks[i].stage].chapterInfo[0].taskJson[
                  _isWorks[i].task
                ].eList &&
                chapters[_isWorks[i].stage].chapterInfo[0].taskJson[
                  _isWorks[i].task
                ].eList.length
              ) {
                if (
                  _isWorks[i].stage == workEvalist[k].stage &&
                  _isWorks[i].task == workEvalist[k].task
                ) {
                  _workW.push({
                    stage: _isWorks[i].stage,
                    task: _isWorks[i].task,
                    rate: JSON.parse(workEvalist[k].rate),
                    elist:
                      chapters[_isWorks[i].stage].chapterInfo[0].taskJson[
                        _isWorks[i].task
                      ].eList,
                  });
                }
              }
            }
          }
          for (var i = 0; i < _workW.length; i++) {
            _workW[i].work = [];
            for (var j = 0; j < _workW[i].elist.length; j++) {
              if (_workW[i].elist[j].target) {
                if (randarAarray.indexOf(_workW[i].elist[j].target) == -1) {
                  randarAarray.push(_workW[i].elist[j].target);
                }
              }
              _workW[i].work.push({
                name: _workW[i].elist[j].value,
                target: _workW[i].elist[j].target,
              });
              _workW[i].work[_workW[i].work.length - 1][
                _workW[i].elist[j].value
              ] = _workW[i].rate[_workW[i].elist[j].value];
              _workW[i].work[_workW[i].work.length - 1].value =
                _workW[i].rate[_workW[i].elist[j].value];
            }
          }
          for (var k = 0; k < randarAarray.length; k++) {
            randarJson.push({ target: randarAarray[k], count: 0, value: 0 });
            for (var i = 0; i < _workW.length; i++) {
              for (var j = 0; j < _workW[i].work.length; j++) {
                if (_workW[i].work[j].target == randarAarray[k]) {
                  randarJson[k].count++;
                  randarJson[k].value += _workW[i].work[j].value;
                }
              }
            }
          }
          this.workW = _workW;
          this.randarJson = randarJson;
        })
        .catch((err) => {
          this.isloading = false;
          console.error(err);
        });
    },
    setType(type) {
      this.type = type;
      if (this.chartObj2) {
        this.chartObj2.dispose();
      }
      if (this.chartObj3) {
        this.chartObj3.dispose();
      }
      this.getInfo();
    },
    color16() {
      //十六进制颜色随机
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      var color = "#" + r.toString(16) + g.toString(16) + b.toString(16);
      return color;
    },
  },
  watch: {
    userid(newValue, oldValue) {
      this.getInfo();
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.getInfo();
    });
  },
};
</script>

<style scoped>
.sd_person_button {
  font-size: 16px;
  display: flex;
  margin-bottom: 10px;
}

.sd_person_button span {
  margin-left: 20px;
  padding: 0 0 6px;
  cursor: pointer;
}

.sd_person_button .active {
  border-bottom: 2px solid rgb(30, 146, 255);
  color: rgb(30, 146, 255);
}

.target_box {
  display: flex;
  align-items: center;
  width: 80%;
  margin: 0 auto;
}

.target_box + .target_box {
  margin-top: 10px;
}

.target_task {
  width: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: rgb(91, 91, 91);
}

.target_content_box {
  display: flex;
  align-items: center;
  width: calc(100% - 100px);
}

.target_content_box div {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.box2 {
  margin-top: 40px;
  height: 80%;
  width: 100%;
  overflow: auto;
}

.targetA {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>