var tmpl = window.template;
tmpl.config({ sTag: "<#", eTag: "#>", compress: true });
var $bodyMain = $("#body-main");
var echartList = [];

build();
publishReady();

function build() {
  if (dataStatic.code && dataStatic.code === "500") {
    var hTmpl = $("#page-error").html();
    var $dom = tmpl(hTmpl, {
      message: dataStatic.message
    });
    $bodyMain.append(createNewBox($dom));
    return;
  }
  var datas = dataParse(dataStatic);

  createCover(datas.cover);

  // 客观题成绩分析
  createTableList(
    datas.basic_question_objective,
    32,
    "客观题成绩分析",
    "question-table"
  );
  createBarPointChart(
    datas.basic_question_objective,
    26,
    "客观题成绩分析",
    "barPointTopic"
  );

  // 主观题成绩分析
  createTableList(
    datas.basic_question_subjective,
    32,
    "主观题成绩分析",
    "question-table"
  );
  createBarPointChart(
    datas.basic_question_subjective,
    26,
    "主观题成绩分析",
    "barPointTopic"
  );

  // 机组成绩分析
  createTableList(datas.basic_class, 32, "机组成绩分析", "classes-table");
  createBarPointChart(datas.basic_class, 22, "机组成绩分析", "barPointGrade");

  // 老师成绩分析
  createTeacherScore(datas.basic_teacher);
  createTeacherGrade(datas.basic_teacher);

  // 电厂成绩分析;
  createTableList(datas.basic_college, 32, "电厂成绩分析", "college-table");
  createBarPointChart(datas.basic_college, 22, "电厂成绩分析", "barPointGrade");

  // 大题难度分析
  createLineChart(datas.basic_main_question);

  // 小题难度分析
  createTableList(
    datas.basic_question,
    32,
    "小题难度分析",
    "question-difficulty-table"
  );
  createLineReverseChart(datas.basic_question); // basic_sub_question

  // 区分度分析
  createDiscriminationDifficultyLevel(
    datas.discrimination_level,
    "discrimination"
  );

  // 大题难度等级构成分析
  createDiscriminationDifficultyLevel(datas.difficulty_level, "difficulty");

  // 大题结构特征
  createBasicMainQuestion(datas.basic_main_question);

  // 题目统计特征
  createBasicQuestion(datas.basic_question);

  // 选项分析
  createBasicQuestionOption(datas.basic_question_option);

  // 考生分段比例;
  createRangeLevel(datas.range_level);

  // 频率分布分析
  createRange10TotalScore(datas.range_10_totalScore);

  // 一分一段分析
  createRangeTotalScore(datas.range_1_totalScore);

  // 六段频率
  createRangeSegment(datas.range_segment_6);
  createEchart();
  fillCatalogNum();
}

function publishReady() {
  var eventEmitInterval = setInterval(function() {
    document.body.dispatchEvent(new Event("view-ready"));
  }, 25);

  document.body.addEventListener("view-ready-acknowledged", function() {
    clearInterval(eventEmitInterval);
  });
}

function createCover(cover) {
  var hTmpl = $("#cover").html();
  var $dom = $(tmpl(hTmpl, cover));
  $bodyMain.append($dom);
}

// 题型成绩分析，机组成绩分析，电厂成绩分析, 题目难度
function createTableList(dataList, splitRange, title, tableType) {
  var hTmpl = $("#" + tableType).html();
  sectionArr(dataList, splitRange).forEach(function(item) {
    var $dom = tmpl(hTmpl, {
      title: title,
      pageTableClass: tableType + " level-table",
      dataList: item
    });
    $bodyMain.append(createNewBox($dom));
  });
}

// 题型成绩分析，机组成绩分析，电厂成绩分析
function createBarPointChart(dataList, splitRange, title, chartType) {
  var hTmpl = $("#page-chart").html();
  var labelHeight = Math.round(1170 / splitRange);
  sectionArr(dataList, splitRange).forEach(function(item) {
    var chartId = getEchartId();
    var $dom = tmpl(hTmpl, {
      title: title,
      chartId: chartId,
      height: 220 + labelHeight * item.length + "px"
    });
    $bodyMain.append(createNewBox($dom));
    addEchart({
      chartId: chartId,
      chartType: chartType,
      datas: item
    });
  });
}

// 老师成绩分析
function createTeacherScore(dataList) {
  var hTmpl = $("#teacher-score").html();
  var splitList = sectionArr(dataList, 6);
  splitList.forEach(function(item) {
    var chartId = getEchartId();
    var $dom = tmpl(hTmpl, {
      chartId: chartId,
      dataList: item,
      teacherScoreTableTpl: tmpl($("#teacher-score-table").html())
    });
    $bodyMain.append(createNewBox($dom));
    addEchart({
      chartId: chartId,
      chartType: "barTeachers",
      datas: item
    });
  });
  // 总明细表
  if (splitList.length > 1) {
    var hTmpl2 = $("#teacher-score-table").html();
    sectionArr(dataList, 26).forEach(function(item) {
      var $dom = tmpl(hTmpl2, {
        dataList: item,
        pageTableClass: "teacher-table"
      });
      $bodyMain.append(createNewBox($dom));
    });
  }
}
// 老师机组成绩分析
function createTeacherGrade(dataList) {
  var hTmpl = $("#teacher-grade").html();
  var sectionDataList = [];
  dataList.map(function(item) {
    if (item.classes.length <= 8) {
      sectionDataList.push(item);
    } else {
      sectionArr(item.classes, 7).forEach(function(elem) {
        sectionDataList.push({
          name: item.name,
          classes: elem
        });
      });
    }
  });
  // class-table
  var classHTmpl = $("#teacher-class-table").html();
  groupSectionArrDynamic(dataList, 32, "classes").forEach(function(item) {
    var $dom = tmpl(classHTmpl, {
      dataList: item,
      pageTableClass: "teacher-class-table level-table"
    });
    $bodyMain.append(createNewBox($dom));
  });

  // class-chart
  sectionArr(sectionDataList, 3).forEach(function(item) {
    var chartList = item.map(function(elem) {
      var chartId = getEchartId();
      addEchart({
        chartId: chartId,
        chartType: "barTeacherGrade",
        datas: elem
      });
      return chartId;
    });
    var $dom = tmpl(hTmpl, {
      chartList: chartList
    });
    $bodyMain.append(createNewBox($dom));
  });
}

// 大题难度分析
function createLineChart(dataList) {
  if (!dataList.length) return;
  // table-parse
  createTableList(dataList, 32, "大题难度分析", "question-difficulty-table");

  if (dataList.length > 6) {
    createLineReverseChart(dataList, "大题难度分析");
    return;
  }

  var hTmpl = $("#page-chart").html();
  var chartId = getEchartId();
  var $dom = tmpl(hTmpl, {
    title: "大题难度分析",
    chartId: chartId,
    chartClassName: "chart-line"
  });
  $bodyMain.append(createNewBox($dom));
  addEchart({
    chartId: chartId,
    chartType: "line",
    datas: dataList
  });
}
// 小题难度分析
function createLineReverseChart(dataList, tableName) {
  // table-parse
  var hTmpl = $("#page-chart").html();
  sectionArr(dataList, 46).forEach(function(item) {
    var chartId = getEchartId();
    var $dom = tmpl(hTmpl, {
      title: tableName || "小题难度分析",
      chartId: chartId,
      height: 200 + 26 * item.length + "px"
    });
    $bodyMain.append(createNewBox($dom));
    addEchart({
      chartId: chartId,
      chartType: "lineReverse",
      datas: item
    });
  });
}
// 区分度等级分布，难度等级分布
function createDiscriminationDifficultyLevel(dataList, type) {
  var hTmpl = $("#" + type + "-level-table").html();
  groupSectionArrDynamic(dataList, 30, "groups").forEach(function(item) {
    var $dom = tmpl(hTmpl, {
      dataList: item
    });
    $bodyMain.append(createNewBox($dom));
  });
}
// 题目统计特征
function createBasicQuestion(dataList) {
  var hTmpl = $("#basic-question-table").html();
  sectionArr(dataList, 33).forEach(function(item) {
    var $dom = tmpl(hTmpl, {
      dataList: item
    });
    $bodyMain.append(createNewBox($dom));
  });
}
// 大题结构特征
function createBasicMainQuestion(dataList) {
  var hTmpl = $("#basic-main-question-table").html();
  sectionArr(dataList, 33).forEach(function(item) {
    var $dom = tmpl(hTmpl, {
      dataList: item
    });
    $bodyMain.append(createNewBox($dom));
  });
}
// 选项分析
function createBasicQuestionOption(data) {
  if (!data.options || !data.options.length) return;
  var hTmpl = $("#basic-question-option-table").html();
  // 选项多余7个会分组
  var options = sectionArr(data.options, 8);
  sectionArr(data.questions, 32).forEach(function(item) {
    options.map(function(elem) {
      var $dom = tmpl(hTmpl, {
        options: elem,
        questions: item
      });
      $bodyMain.append(createNewBox($dom));
    });
  });
}
// 考生分段比例
function createRangeLevel(dataList) {
  var hTmpl = $("#range-level-table").html();
  sectionArr(dataList, 31).forEach(function(item) {
    var $dom = tmpl(hTmpl, {
      dataList: item
    });
    $bodyMain.append(createNewBox($dom));
  });
}
// 总分频率分布
function createRange10TotalScore(datas) {
  var pageList = [];
  if (datas.total.length) {
    pageList.push({
      title: "总分频率分布分析",
      dataList: datas.total
    });
  }
  // 机组成绩频率分布
  pageList = pageList.concat(
    datas.classes.map(function(item) {
      return {
        title: item.name + " 总分频率分布",
        dataList: item.ranges
      };
    })
  );

  var hTmpl = $("#range-totalScore").html();
  pageList.forEach(function(item, index) {
    var chartId = getEchartId();
    addEchart({
      chartId: chartId,
      chartType: "lineSmooth",
      datas: {
        index: index,
        dataList: item.dataList
      }
    });
    sectionArrFirstPage(item.dataList, 32, 22).map(function(elem, index) {
      var pageTableClass =
        elem.length > 16 ? "table-ave-5 table-range-long" : "table-ave-5";
      if (index > 0) pageTableClass += " page-table-pad";
      var $dom = tmpl(hTmpl, {
        title: item.title,
        isOneStep: false,
        pageTableClass: pageTableClass,
        dataList: elem,
        chartId: index === 0 ? chartId : ""
      });
      $bodyMain.append(createNewBox($dom));
    });
  });
}
// 总分一分一段表
function createRangeTotalScore(datas) {
  var pageList = [];
  if (datas.total.length) {
    pageList.push({
      title: "总分一分一段表",
      dataList: datas.total
    });
  }
  // 机组成绩统计
  pageList = pageList.concat(
    datas.classes.map(function(item) {
      return {
        title: item.name + " 总分一分一段表",
        dataList: item.ranges
      };
    })
  );
  var hTmpl = $("#range-totalScore").html();
  pageList.forEach(function(item, index) {
    sectionArr(item.dataList, 32).forEach(function(elem) {
      var $dom = tmpl(hTmpl, {
        title: item.title,
        isOneStep: true,
        pageTableClass: "table-ave-5 page-table-pad",
        dataList: elem,
        chartId: ""
      });
      $bodyMain.append(createNewBox($dom));
    });
  });
}
// 六段频率统计
function createRangeSegment(dataList) {
  var hTmpl = $("#range-segment-table").html();
  dataList.map(function(item) {
    sectionArrDynamic(item.groups, 30, "segments").map(function(elem) {
      var $dom = tmpl(hTmpl, {
        title: item.name + " 六段频率统计",
        dataList: elem
      });
      $bodyMain.append(createNewBox($dom));
    });
  });
}

/**
 * 渲染模板
 * @param {Object} renderItem 渲染配置
 */
function renderTmp(renderItem) {
  var hTmpl = $("#" + renderItem.templateName).html();
  var $dom = $(tmpl(hTmpl, renderItem.datas || {}));
  return $dom;
}

/**
 * 创建新的box
 * @param {DomStr} bodyDom 页面填充内容
 * @param {String} boxType box类型，默认report-box
 */
function createNewBox(bodyDom, boxType) {
  return renderTmp({
    templateName: "page-box",
    datas: {
      bodyDom: bodyDom || "",
      boxType: boxType || "report-box"
    }
  });
}

/**
 * 创建echart图表
 *
 */
function createEchart() {
  echartList.forEach(function(elem) {
    var charts = new Charts(
      document.getElementById(elem.chartId),
      elem.datas,
      elem.chartType
    );
    charts.renderChart();
  });
}

/**
 * 渲染页码
 */
function fillCatalogNum() {
  var hTmpl = $("#page-foot").html();
  $(".report-box").each(function(index) {
    var page = index + 1;
    var dom = tmpl(hTmpl, {
      name: cover.name,
      time: cover.time,
      pageNum: page < 10 ? "0" + page : page
    });
    $(this)
      .attr("id", "page-" + page)
      .append($(dom));
  });
}

/**
 *
 * @param {Array} arrayList 要分段的数组
 * @param {Number} sectionLength 每段的长度
 */
function sectionArr(arrayList, sectionLength) {
  var splitArr = [];
  for (var i = 0, len = arrayList.length; i < len; i += sectionLength) {
    splitArr.push(arrayList.slice(i, i + sectionLength));
  }
  return splitArr;
}

/**
 *
 * @param {Array} arrayList 要分段的数组
 * @param {Number} sectionLength 每段的长度
 * @param {Number} firstPageNum 第一段的长度
 */
function sectionArrFirstPage(arrayList, sectionLength, firstPageNum) {
  var splitArr = [];
  var currentSectionLength = 0;
  for (var i = 0, len = arrayList.length; i < len; i += currentSectionLength) {
    if (i === 0) {
      currentSectionLength = firstPageNum;
    } else {
      currentSectionLength = sectionLength;
    }
    splitArr.push(arrayList.slice(i, i + currentSectionLength));
  }
  return splitArr;
}

/**
 * 组元素个数少于10个时，此法更方便
 * @param {Array} arrayList 要分段的数组
 * @param {Number} sectionMaxItemLength 最大分段元素个数
 */
function sectionArrDynamic(arrayList, sectionMaxItemLength, childrenName) {
  var splitArr = [];
  var splitSectionItemLen = 0;
  var splitSectionArr = [];
  for (var i = 0, len = arrayList.length; i < len; i++) {
    if (
      splitSectionItemLen + arrayList[i][childrenName].length >
      sectionMaxItemLength
    ) {
      splitArr.push(splitSectionArr);
      splitSectionItemLen = 0;
      splitSectionArr = [];
    }
    splitSectionItemLen += arrayList[i][childrenName].length;
    splitSectionArr.push(arrayList[i]);
  }
  splitArr.push(splitSectionArr);
  return splitArr;
}
/**
 * 组元素过多，且无规律时，使用此方法更合理
 * @param {*} arrayList
 * @param {*} sectionMaxItemLength
 * @param {*} childrenName
 */
function groupSectionArrDynamic(arrayList, sectionMaxItemLength, childrenName) {
  var splitArr = [];
  var splitSectionItemLen = 0;
  var splitSectionArr = [];

  arrayList.map(function(item) {
    var groupsList = [];
    item[childrenName].map(function(elem) {
      splitSectionItemLen++;
      groupsList.push(elem);

      if (splitSectionItemLen >= sectionMaxItemLength) {
        splitSectionArr.push({
          name: item.name,
          [childrenName]: groupsList
        });
        splitArr.push(splitSectionArr);
        splitSectionItemLen = 0;
        splitSectionArr = [];
        groupsList = [];
      }
    });

    if (groupsList.length)
      splitSectionArr.push({
        name: item.name,
        [childrenName]: groupsList
      });
  });
  if (splitSectionArr.length) splitArr.push(splitSectionArr);

  return splitArr;
}

/**
 * 获取chartId
 */
function getEchartId() {
  return "chart-" + echartList.length;
}
/**
 * 添加chart渲染队列
 * @param {Object} option chart配置
 */
function addEchart(option) {
  echartList.push({
    chartId: option.chartId || getEchartId(),
    chartType: option.chartType,
    datas: option.datas
  });
}
