<template>
  <div class="report-detail">
    <div class="report-detail-body" v-if="showBody">
      <!-- info -->
      <div class="student-info report-part">
        <div class="student-info-name">
          <h3>{{ student.examStudentName }}</h3>
          <p>考试时间：{{ student.time | timestampFilter }}</p>
        </div>
        <div class="student-info-tags">
          <div class="tag-item">{{ student.studentCode }}</div>
          <div class="tag-item">{{ student.collegeName }}</div>
          <div class="tag-item">{{ student.className }}</div>
          <div class="tag-item">{{ student.examName }}</div>
        </div>
        <div class="student-info-level">
          <h4 class="course-name">{{ student.courseName }}</h4>
          <level-chart :infos="levelInfo" v-if="levelInfo"></level-chart>
        </div>
        <div class="student-info-intro report-part-intro">
          <h5 class="report-part-intro-title">
            <i class="icon icon-notice"></i>说明
          </h5>
          <p class="report-part-intro-content">
            你的位置显示你的成绩在学院内的相对位置，按照每{{
              levelAvgRate
            }}%划分为一个档位。
          </p>
        </div>
      </div>
      <!-- summary -->
      <div class="student-summary report-part">
        <h3 class="report-part-title">
          <i class="icon icon-compare"></i>个人与本院对比情况
        </h3>
        <div class="summary-top">
          <div class="summary-top-item">
            <div class="summary-top-body">
              <i class="icon icon-users"></i>
              <p>{{ synthesis.actualCount }}</p>
              <p>实考总人数</p>
            </div>
          </div>
          <div class="summary-top-item">
            <div class="summary-top-body">
              <i class="icon icon-creating"></i>
              <p>{{ synthesis.overRate }}%</p>
              <p>超过本院总体</p>
            </div>
          </div>
        </div>
        <div class="summary-progress">
          <div class="progress-item">
            <span>本院最低分</span>
            <span>{{ synthesis.collegeMinScore }}</span>
            <div class="progress-line">
              <div class="progress-line-body">
                <div
                  class="progress-line-progress"
                  :style="getSynthesisStyle(synthesis, 'collegeMinScore')"
                ></div>
              </div>
            </div>
          </div>
          <div class="progress-item" v-if="synthesis.clazzMinScore !== null">
            <span>课堂最低分</span>
            <span>{{ synthesis.clazzMinScore }}</span>
            <div class="progress-line">
              <div class="progress-line-body">
                <div
                  class="progress-line-progress"
                  :style="getSynthesisStyle(synthesis, 'clazzMinScore')"
                ></div>
              </div>
            </div>
          </div>
          <div class="progress-item">
            <span>本院平均分</span>
            <span>{{ synthesis.collegeAvgScore }}</span>
            <div class="progress-line">
              <div class="progress-line-body">
                <div
                  class="progress-line-progress"
                  :style="getSynthesisStyle(synthesis, 'collegeAvgScore')"
                ></div>
              </div>
            </div>
          </div>
          <div class="progress-item progress-user">
            <span>你的分数</span>
            <span>{{ synthesis.myScore }}</span>
            <div class="progress-line">
              <div class="progress-line-body">
                <div
                  class="progress-line-progress"
                  :style="getSynthesisStyle(synthesis, 'myScore')"
                ></div>
                <div
                  class="progress-line-mark"
                  :style="getSynthesisStudentStyle(synthesis)"
                >
                  <i class="icon icon-run"></i>
                </div>
              </div>
            </div>
          </div>
          <div class="progress-item" v-if="synthesis.clazzAvgScore !== null">
            <span>课堂平均分</span>
            <span>{{ synthesis.clazzAvgScore }}</span>
            <div class="progress-line">
              <div class="progress-line-body">
                <div
                  class="progress-line-progress"
                  :style="getSynthesisStyle(synthesis, 'clazzAvgScore')"
                ></div>
              </div>
            </div>
          </div>
          <div class="progress-item" v-if="synthesis.clazzMaxScore !== null">
            <span>课堂最高分</span>
            <span>{{ synthesis.clazzMaxScore }}</span>
            <div class="progress-line">
              <div class="progress-line-body">
                <div
                  class="progress-line-progress"
                  :style="getSynthesisStyle(synthesis, 'clazzMaxScore')"
                ></div>
              </div>
            </div>
          </div>
          <div class="progress-item">
            <span>本院最高分</span>
            <span>{{ synthesis.collegeMaxScore }}</span>
            <div class="progress-line">
              <div class="progress-line-body">
                <div
                  class="progress-line-progress"
                  :style="getSynthesisStyle(synthesis, 'collegeMaxScore')"
                ></div>
              </div>
            </div>
          </div>
          <div class="progress-item">
            <span>试卷满分</span>
            <span>{{ synthesis.fullScore }}</span>
            <div class="progress-line">
              <div class="progress-line-body">
                <div class="progress-line-progress" style="width: 100%;"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- result -->
      <div class="student-result report-part">
        <h3 class="report-part-title">
          <i class="icon icon-diagnosis"></i>整体诊断说明
        </h3>
        <div
          :class="[
            'result-content',
            { 'result-content-error': !student.result }
          ]"
        >
          <i :class="['icon', student.result ? 'icon-smile' : 'icon-cry']"></i>
          <p>{{ student.result ? "通过" : "不通过" }}</p>
          <p>本次测验分别从以下方面进行诊断</p>
        </div>
        <div class="result-menu">
          <div
            :class="[
              'result-menu-item',
              { 'result-menu-item-act': curModuleIndex === mindex }
            ]"
            v-for="(info, mindex) in modules"
            :key="mindex"
            @click="changeModule(mindex)"
          >
            {{ info.name }}
          </div>
        </div>
        <div class="result-body">
          <div class="result-chart">
            <v-chart
              :option="curKnowledgeRatesOption"
              v-if="curKnowledgeRatesOption"
            ></v-chart>
          </div>
          <div class="result-desc report-part-intro">
            <h5 class="report-part-intro-title">
              <i class="icon icon-notice"></i>{{ curModuleDesc.info }}
            </h5>
            <div class="report-part-intro-content">
              <p v-for="(intro, idx) in curModuleDesc.remark" :key="idx">
                <b>{{ intro.name }}：</b>
                <span>{{ intro.desc }}。</span>
              </p>
            </div>
          </div>
        </div>
      </div>
      <!-- module -->
      <template v-for="(info, mindex) in modules">
        <div
          class="student-module module-knowledge report-part"
          :key="mindex"
          v-if="info.subDios && info.subDios.length"
        >
          <h3 class="report-part-title">
            <i class="icon icon-diagnosis"></i>{{ info.name }}分析
          </h3>
          <div class="knowledge-result">
            <div class="knowledge-progress" ref="KnowledgeProgress">
              <tree-progress :progress="info.masteryRate * 1"></tree-progress>
            </div>
            <div
              :class="[
                'knowledge-nums',
                { 'knowledge-nums-hide': student.isAssignedScore }
              ]"
            >
              <!-- <p class="knowledge-score">{{ info.myScore }}<span>分</span></p>
              <p>{{ info.name }}个人得分</p> -->
              <p class="knowledge-rate">{{ info.masteryRate }}%</p>
              <p>{{ info.name }}整体掌握率</p>
              <!-- <div class="knowledge-full">
                <i class="icon icon-angle"></i>{{ info.name }}维度总分{{
                  info.dioFullScore
                }}分
              </div> -->
            </div>
          </div>
          <div
            class="knowledge-chart"
            :style="info.knowledgeDetailRatesChartStyle"
          >
            <v-chart
              :option="info.knowledgeDetailRatesOption"
              v-if="info.knowledgeDetailRatesOption"
            ></v-chart>
          </div>
          <div class="knowledge-legend">
            <div
              class="knowledge-legend-row"
              v-for="(group, gindex) in info.subDios"
              :key="gindex"
            >
              <div
                class="knowledge-legend-item"
                v-for="(dios, sindex) in group"
                :key="sindex"
              >
                <span
                  :class="[
                    'knowledge-legend-tag',
                    `knowledge-legend-tag-${dios.proficiency}`
                  ]"
                  >{{ dios.code }}</span
                >
                <span class="knowledge-legend-cont">{{ dios.name }}</span>
              </div>
            </div>
          </div>
          <div
            class="knowledge-intro report-part-intro"
            v-if="info.masterys.length"
          >
            <h5 class="report-part-intro-title">
              <i class="icon icon-notice"></i>说明
            </h5>
            <div class="report-part-intro-content">
              <p v-for="(content, cindex) in info.masterys" :key="cindex">
                {{ content }}
              </p>
            </div>
          </div>
        </div>
      </template>
      <!-- suggest -->
      <div class="student-suggest report-part">
        <h3 class="report-part-title">
          <i class="icon icon-star"></i>诊断结果
        </h3>
        <div class="suggest-part">
          <div class="suggest-part-tag">
            <div class="suggest-part-tag-body">
              <i class="icon icon-overall"></i>
            </div>
          </div>
          <h4>整体情况</h4>
          <p>
            本次考试难度系数为
            <span>{{ synthesis.difficult }}</span>
            ，属于
            <span>{{ synthesis.difficultInfo }}</span>
            ，本院实考人数为
            <span>{{ synthesis.actualCount }}</span>
            人，满分
            <span>{{ synthesis.fullScore }}</span>
            分，最高分
            <span>{{ synthesis.collegeMaxScore }}</span>
            分，课堂最高分
            <span>{{ synthesis.clazzMaxScore }}</span>
            分，个人成绩
            <span>{{ synthesis.myScore }}</span>
            分。
          </p>
        </div>
        <div class="suggest-part">
          <div class="suggest-part-tag">
            <div class="suggest-part-tag-body">
              <i class="icon icon-file"></i>
            </div>
          </div>
          <h4>诊断说明</h4>
          <div v-if="student.diagnoseIntros && student.diagnoseIntros.length">
            <p v-for="(intro, index) in student.diagnoseIntros" :key="index">
              <span>{{ intro.name }}：</span>{{ intro.result }}
            </p>
          </div>
          <p v-else>老师可能更期待和你面对面沟通哦！</p>
        </div>
        <div class="suggest-part">
          <div class="suggest-part-tag">
            <div class="suggest-part-tag-body">
              <i class="icon icon-suggest"></i>
            </div>
          </div>
          <h4>学习建议</h4>
          <div v-if="student.advices && student.advices.length">
            <p v-for="(item, index) in student.advices" :key="index">
              <span>{{ item.name }}：</span>{{ item.advice }}
            </p>
          </div>
          <p v-else>老师可能更期待和你面对面沟通哦！</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import flexible from "../flexible";
import TreeProgress from "./TreeProgress";
import LevelChart from "./LevelChart";
import { findReportByStudent } from "../api";

export default {
  name: "report-detail",
  components: { TreeProgress, LevelChart },
  props: {
    data: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      showBody: false,
      student: {},
      hasAdvice: false,
      levelInfo: null,
      levelAvgRate: "",
      synthesis: null,
      modules: null,
      curModuleIndex: null,
      curKnowledgeRatesOption: null,
      curModuleDesc: {}
    };
  },
  mounted() {
    this.getDetail();
  },
  methods: {
    async getDetail() {
      const data = await findReportByStudent(this.data);
      if (!data) return;

      this.parseData(data);
      this.showBody = true;
      this.$nextTick(() => {
        this.changeModule(0);
      });
    },
    parseData(datas) {
      const serials = { 知识: 0, 能力: 1 };
      if (datas.college.diagnosis.list.length > 1) {
        datas.college.diagnosis.list.sort(
          (a, b) => serials[a.name] - serials[b.name]
        );
      }
      this.student = datas.student;
      this.student.result = datas.college.diagnosis.result;
      this.student.isAssignedScore = datas.college.diagnosis.isAssignedScore;
      this.student.advices = datas.college.diagnosis.list
        .map(item => {
          return {
            name: item.name,
            advice: item.advice
          };
        })
        .filter(item => !!item.advice);
      this.student.diagnoseIntros = datas.college.diagnosis.list
        .map(item => {
          return {
            name: item.name,
            result: item.result
          };
        })
        .filter(item => !!item.result);

      this.levelInfo = {
        curLevel: datas.student.level,
        levels: datas.student.levels.map(item => {
          return {
            name: item.level,
            range: item.grade
          };
        })
      };
      this.levelAvgRate = (100 / datas.student.levels.length).toFixed(2) * 1;
      this.synthesis = datas.college.synthesis;
      this.modules = datas.college.diagnosis.list.map(item => {
        const subDios =
          item.detail.subDios && item.detail.subDios.length
            ? item.detail.subDios
            : [];
        const knowledgeRates = this.getKnowledgeRatesData(item.modules.dios);
        const knowledgeDetailRates = this.getKnowledgeDetailRatesData(subDios);
        const knowledgeDetailRatesChartStyle = this.getKnowledgeDetailRatesChartStyle(
          subDios.length
        );
        return {
          name: item.name,
          info: item.modules.info,
          remark: item.modules.dios
            .filter(item => item.interpretation)
            .map(item => {
              return {
                name: item.name,
                desc: item.interpretation
              };
            }),
          myScore: item.detail.myScore.toFixed(1),
          masteryRate: item.detail.masteryRate.toFixed(1),
          dioFullScore: item.detail.dioFullScore,
          subDios: this.getGroupList(subDios),
          masterys: item.detail.define.filter(item => !!item),
          knowledgeRatesOption: this.getKnowledgeRatesOption(knowledgeRates),
          knowledgeDetailRatesOption: this.getKnowledgeDetailRatesOption(
            knowledgeDetailRates
          ),
          knowledgeDetailRatesChartStyle
        };
      });
    },
    getGroupList(dataList) {
      if (!dataList.length) return [];
      const groupSize = 2;
      const groupNum = Math.ceil(dataList.length / groupSize);
      let groups = [];
      for (let i = 0; i < groupNum; i++) {
        groups.push(dataList.slice(i * groupSize, (i + 1) * groupSize));
      }
      return groups;
    },
    changeModule(index) {
      if (this.curModuleIndex === index) return;
      const item = this.modules[index];
      this.curModuleIndex = index;
      this.curKnowledgeRatesOption = this.modules[index].knowledgeRatesOption;
      this.curModuleDesc = {
        info: item.info,
        remark: item.remark
      };
    },
    getSynthesisStyle(data, key) {
      return {
        width: this.getPercentRate(data[key] / data.fullScore) + "%"
      };
    },
    getSynthesisStudentStyle(data) {
      const rate = this.getPercentRate(data.myScore / data.fullScore);
      return rate > 10 ? { right: 100 - rate + "%" } : { left: "0%" };
    },
    getPercentRate(num) {
      return (num * 100).toFixed(2) * 1;
    },
    getKnowledgeRatesData(list) {
      if (!list || !list.length) return [];
      const rates = [
        {
          name: "个人得分率",
          key: "rate"
        },
        {
          name: "本院平均得分率",
          key: "collegeRate"
        }
      ];
      return rates.map(item => {
        return {
          name: item.name,
          datas: list.map(elem => {
            return {
              name: elem.name,
              value: elem[item.key]
            };
          })
        };
      });
    },
    getKnowledgeDetailRatesData(list) {
      if (!list || !list.length) return [];
      const rates = [
        {
          name: "个人得分率",
          key: "scoreRate"
        },
        {
          name: "本院平均得分率",
          key: "collegeAvgScore"
        }
      ];
      return rates.map(item => {
        return {
          name: item.name,
          datas: list.map(elem => {
            return {
              name: elem.name,
              label: elem.code,
              value: elem[item.key]
            };
          })
        };
      });
    },
    getKnowledgeDetailRatesChartStyle(num) {
      let height = 7.34;
      if (num > 7) {
        height += (num - 7) * 0.6;
      }
      return {
        height: `${height}rem`
      };
    },
    getMasterys(list) {
      const masterysMap = {
        H: "熟练",
        M: "基本熟练",
        L: "不熟练"
      };

      return list.map(item => {
        const name = masterysMap[item.level];
        let content;
        if (item.level === "H") {
          content = `${name}（个人得分率大于等于${item.grade[0]}%）`;
        } else if (item.level === "M") {
          content = `${name}（个人得分率介于${item.grade[0]}%~${item.grade[1]}%之间）`;
        } else {
          content = `${name}（个人得分率小于${item.grade[1]}%）`;
        }

        return content;
      });
    },
    splitStr(content, len) {
      if (content.length <= len) return content;

      const partCount = Math.ceil(content.length / len);
      const partLen = Math.ceil(content.length / partCount);
      let conts = [];
      for (let i = 0; i < partCount; i++) {
        conts.push(content.slice(i * partLen, (i + 1) * partLen));
      }
      return conts.join("\n");
    },
    getKnowledgeRatesOption(datas) {
      if (!datas.length) return {};
      const _this = this;
      const aUrl =
        "image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4T2OUubTQk4GBYSbDfwZZBlIAI8NjBgaGdEaZSwsfkawZZhEjw2NGmYsL/5NiMbpa6hvwj+GfHz4XMTEwbUKWx3DBqAEMDMMgDEhNlVRIiRRnJgqzMwD3xkk/e5j4JAAAAABJRU5ErkJggg==";
      const bUrl =
        "image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAVUlEQVQ4T2N8cOf//wPbGRi+fGYgCfDwMjA4eDIwMC6Y/P8/qZphNoEMYZzS9v8/SVajKaa+AV4h+N2zbQ2qPIYLRg1gYBgGYUBqqqQ8JVKcmSjNzgDyMU8HIsfp2AAAAABJRU5ErkJggg==";
      const indicator = datas[0].datas.map(item => {
        return {
          name: item.name,
          max: 100
        };
      });
      const seriesDatas = datas.map(item => {
        return {
          name: item.name,
          value: item.datas.map(elem => elem.value)
        };
      });
      return {
        color: ["#1CD1A1", "#9486FF"],
        legend: {
          top: flexible.rem2px(0.53),
          right: flexible.rem2px(0.7),
          itemWidth: flexible.rem2px(0.21),
          itemHeight: flexible.rem2px(0.21),
          itemGap: flexible.rem2px(0.64),
          data: [
            {
              name: datas[0].name,
              icon: aUrl
            },
            {
              name: datas[1].name,
              icon: bUrl
            }
          ],
          textStyle: {
            color: "#626A82",
            fontSize: flexible.rem2px(0.32)
          }
        },
        radar: {
          center: ["50%", "56%"],
          name: {
            textStyle: {
              fontSize: flexible.rem2px(0.28),
              color: "#6F6C7B"
            },
            formatter: function(value) {
              return _this.splitStr(value, 5);
            }
          },
          indicator,
          axisLine: {
            show: true,
            lineStyle: {
              color: "#EEEEF6",
              width: flexible.rem2px(0.03)
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#EEEEF6",
              width: flexible.rem2px(0.03)
            }
          },
          splitArea: {
            show: false
          },
          shape: "circle",
          radius: "60%"
        },
        series: [
          {
            type: "radar",
            symbolSize: 2,
            symbol: "rect",
            itemStyle: {
              borderWidth: flexible.rem2px(0.05)
            },
            areaStyle: {
              opacity: 0.3
            },
            lineStyle: {
              width: flexible.rem2px(0.05)
            },
            data: seriesDatas
          }
        ]
      };
    },
    getKnowledgeDetailRatesOption(datas) {
      if (!datas.length) return {};
      const aUrl =
        "image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAECAYAAADvRz3UAAAAM0lEQVQoU2MMubnX8x/Dv5kM/xlkGegJGBkeMzEwpTMG3dz9iO6WwzzKyPB44B0w0FEAAKw+F/srGrt6AAAAAElFTkSuQmCC";
      const bUrl =
        "image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAECAYAAADvRz3UAAAAQ0lEQVQoU2P8U1XsyfD//8z/DAyyDEiAkYHhMQMjYzpLW+92ZHFqq2f8U1n0CN1ymIUgR7C098mhOIDK6geBAwY4CgDxfVP7RdGL6gAAAABJRU5ErkJggg==";
      return {
        color: ["#52D8BB", "#FB7972"],
        legend: {
          right: 0,
          top: flexible.rem2px(0.53),
          itemWidth: flexible.rem2px(0.43),
          itemHeight: flexible.rem2px(0.05),
          itemGap: flexible.rem2px(0.64),
          data: [
            {
              name: datas[0].name,
              icon: aUrl
            },
            {
              name: datas[1].name,
              icon: bUrl
            }
          ],
          textStyle: {
            color: "#6F6C7B",
            fontSize: flexible.rem2px(0.32)
          }
        },
        grid: {
          top: flexible.rem2px(2.16),
          bottom: flexible.rem2px(0.55),
          left: "12%",
          right: "4%"
        },
        yAxis: {
          type: "category",
          boundaryGap: false,
          axisLine: {
            show: false
          },
          inverse: true,
          splitLine: {
            show: true,
            lineStyle: {
              color: "#EEEEF6",
              width: flexible.rem2px(0.03)
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: "#151026",
            interval: 0,
            fontSize: flexible.rem2px(0.27),
            margin: flexible.rem2px(0.27)
          },
          data: datas[0].datas.map(item => item.label)
        },
        xAxis: {
          type: "value",
          min: 0,
          max: 100,
          position: "top",
          axisLine: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: "#6F6C7B",
            fontSize: flexible.rem2px(0.27),
            margin: flexible.rem2px(0.27),
            formatter: value => {
              return value + "%";
            }
          }
        },
        series: [
          {
            type: "line",
            name: datas[0].name,
            data: datas[0].datas.map(item => item.value),
            symbolSize: flexible.rem2px(0.05),
            symbol: "rect",
            areaStyle: {
              color: {
                type: "linear",
                x: 1,
                y: 0,
                x2: 0,
                y2: 0,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(82, 216, 187, 1)"
                  },
                  {
                    offset: 1,
                    color: "rgba(82, 216, 187, 0)"
                  }
                ]
              }
            },
            lineStyle: {
              color: "#52D8BB",
              width: flexible.rem2px(0.05)
            }
          },
          {
            type: "line",
            name: datas[1].name,
            data: datas[1].datas.map(item => item.value),
            symbolSize: flexible.rem2px(0.05),
            symbol: "rect",
            lineStyle: {
              color: "#FB7972",
              type: "dashed",
              width: flexible.rem2px(0.05)
            }
          }
        ]
      };
    }
  }
};
</script>
