<template>
  <el-card :class="{ 'type-card-no-padding': noPadding }">
    <div v-if="!nameHighlight" class="type-title" :class="[typeIconClasses[type]]">
      <div>
        <span>{{ name }}</span>
      </div>
      <div class="type-title-important" v-if="important">{{ important }}</div>
    </div>
    <div v-else class="type-title-hightlight" :class="'type-title-hightlight-' + type">
      {{ name }}
    </div>
    <div class="type-table" :class="
        nameHighlight
          ? [typeTableClass[type], typeTableClass[type] + '-light']
          : [typeTableClass[type]]
      ">
      <slot name="prefix"></slot>
      <div class="type-table-paging" v-if="pagingKeys.length > 1" style="text-align: right">
        <el-radio-group v-model="pagingKey" @change="pagingToggle" size="mini">
          <el-radio-button v-for="item in pagingKeys" :key="item" :label="item">{{ item }}</el-radio-button>
        </el-radio-group>
      </div>
      <el-table v-if="displayColumns.length" :data="displayRows" :border="border">
        <el-table-column v-for="(col, idx) in displayColumns" :key="col + idx" :label="col" align="center">
          <template #header>
            <slot v-if="headerTemplateConfig[col]||headerTemplateConfig.applyAll"
              :name="headerTemplateConfig[col]||headerTemplateConfig.applyAll"
              v-bind="{columnName: col, columnIndex: idx}">{{col}}
            </slot>
            <label v-else>{{col}}</label>
          </template>
          <template slot-scope="scope">
            <template v-if="columnTemplateConfig[col]||rowTemplateConfig[scope.$index]">
              <slot :name="columnTemplateConfig[col]||rowTemplateConfig[scope.$index]"
                v-bind="{...scope, columnName:col, columnIndex: idx, value:scope.row[idx], data:displayRows}">
                {{scope.row[idx]}}
              </slot>
            </template>
            <div class="type-table-cell-array" v-else-if="(scope.row[idx] instanceof Array)">
              <div v-for="(subItem,subIdx) in scope.row[idx]" :key="`${subItem}${subIdx}`">{{subItem}}</div>
            </div>
            <span v-else-if="idx != starConfig.index" :class="{
                'type-table-cell-highlight':
                  highlightRowIndexes.includes(scope.$index) ||
                  highlightColumnIndexes.includes(idx),
              }">{{ scope.row[idx] }}</span>
            <div v-else class="type-table-star">
              <el-rate :value="Math.min(scope.row[idx] * 1, starConfig.max)" :max="starConfig.max" disabled></el-rate>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <slot name="suffix"></slot>
    </div>
  </el-card>
</template>
<script>
  export default {
    props: {
      border: {
        type: Boolean,
        default: true,
      },
      noPadding: {
        type: Boolean,
        default: false,
      },
      name: {
        type: String,
        default: "",
      },
      important: {
        type: String,
        default: "",
      },
      nameHighlight: {
        type: Boolean,
        default: false,
      },
      type: {
        type: String,
        default: "type",
      },
      columns: {
        type: Array,
        default: () => ["考试题型", "题量", "占比", "分数"],
      },
      rows: {
        type: Array,
        default: () => [
          ["选择题", "1", "20%", "20"]
        ],
      },
      autoPageEnable: {
        type: Boolean,
        default: false,
      },
      autoPageConfig: {
        type: Object,
        default: () => {},
      },
      rowHighlight: {
        type: Function,
        default: (row) => false,
      },
      starColumnConfig: {
        type: Object,
        default: () => ({}),
      },
      columnTemplateConfig: {
        type: Object,
        default: _ => ({})
      },
      rowTemplateConfig: {
        type: Object,
        default: _ => ({})
      },
      headerTemplateConfig: {
        type: Object,
        default: _ => ({})
      }
    },
    data() {
      return {
        typeIconClasses: {
          type: "paper-type-bg",
          difficult: "paper-diffi-bg",
          knowledge: "paper-knowledge-bg",
        },
        typeTableClass: {
          type: "paper-type-tb",
          difficult: "paper-diffi-tb",
          knowledge: "paper-knowledge-tb",
        },
        displayColumns: [],
        displayRows: [],
        pagingKeys: [], // 分页页码
        pagingKey: "", // 当前页码
        pagingSource: {}, // 按pagingKey为属性的分页数据
        pagingConfig: {
          pagingSize: 10,
          pagingTabNameFormatter: (rows, idx) => {
            if (!rows || !rows.length) return "";
            if (rows.length == 1) return rows[0][0] + "题";
            const start = rows[0][0];
            const end = rows[rows.length - 1][0];
            return `${start}-${end}题`;
          },
          toggleRowColumn: true, // 显示时行列转换
          toggleFakeMode: true, // 行列转换后, 如果不足分页, 假数据补齐
        },
        highlightRowIndexes: [],
        highlightColumnIndexes: [],
        starConfig: {
          index: -1,
          max: 5,
        },
      };
    },
    watch: {
      autoPageEnable: function(val) {
        if (val) {
          console.log("watch autoPageEnable", this.columns, this.rows);
        }
      },
    },
    mounted() {
      if (!this.autoPageEnable) {
        this.displayColumns = this.columns;
        this.displayRows = this.rows;
        // todo calculate hightlight row by need.
      } else {
        this.pagingData();
      }
      // star
      this.starConfig = {
        ...this.starConfig,
        ...this.starColumnConfig
      };
    },
    methods: {
      pagingData() {
        // config
        const config = (this.pagingConfig = {
          ...this.pagingConfig,
          ...this.autoPageConfig,
        });
        // reset
        this.pagingKeys = [];
        this.pagingSource = {};
        // paging
        let myRows;
        let myIndex = -1;
        for (let index = 0; index < this.rows.length; index++) {
          const row = this.rows[index];
          const pagingIdx = Math.floor(index / config.pagingSize);
          if (myIndex != pagingIdx) {
            if (myRows && myRows.length) {
              const key = config.pagingTabNameFormatter(myRows, myIndex);
              this.pagingSource[key] = myRows;
              this.pagingKeys.push(key);
            }
            myRows = [];
            myIndex = pagingIdx;
          }
          myRows.push(row);
          if (this.rowHighlight(row)) {
            if (!config.toggleRowColumn) this.highlightRowIndexes.push(index);
            else this.highlightColumnIndexes.push(index + 1); // +1 for header
          }
        }
        if (myRows && myRows.length) {
          const key = config.pagingTabNameFormatter(myRows, myIndex);
          this.pagingSource[key] = myRows;
          this.pagingKeys.push(key);
        }
        // show first page
        if (this.pagingKeys.length > 0) this.pagingKey = this.pagingKeys[0];
        this.pagingToggle();
      },
      pagingToggle() {
        if (!this.pagingKey) return;
        const config = this.pagingConfig;
        const pagingRows = this.pagingSource[this.pagingKey];

        this.highlightColumnIndexes = []
        pagingRows.forEach((row, index) => {
          if (this.rowHighlight(row)) {
            if (!config.toggleRowColumn) this.highlightRowIndexes.push(index);
            else this.highlightColumnIndexes.push(index + 1); // +1 for header
          }
        })

        if (config.toggleRowColumn) {
          let newColumns = [];
          let newRows = [];
          for (let rowIdx = 0; rowIdx < this.columns.length; rowIdx++) {
            const rowName = this.columns[rowIdx];
            const newRow = [rowName];
            for (let colIdx = 0; colIdx < config.pagingSize; colIdx++) {
              var row = colIdx < pagingRows.length ? pagingRows[colIdx] : [];
              var val = rowIdx < row.length ? row[rowIdx] : "";
              newRow.push(val);
            }
            if (rowIdx == 0) newColumns = newRow;
            else newRows.push(newRow);
          }
          this.displayColumns = newColumns;
          this.displayRows = newRows;
        } else {
          this.displayColumns = this.columns;
          this.displayRows = pagingRows;
        }
      },
    },
  };
</script>
<style lang="scss">
  .type-table-cell-highlight {
    color: #F5AB86;
  }

  .type-table-cell-array {
    display: flex;
    justify-content: space-around;
  }
</style>
<style scoped>
  .paper-type-bg {
    background-image: url("../../../assets/images/paper_type_label_bg.png");
    background-repeat: no-repeat;
  }

  .paper-diffi-bg {
    background-image: url("../../../assets/images/paper_diffi_label_bg.png");
    background-repeat: no-repeat;
  }

  .paper-knowledge-bg {
    background-image: url("../../../assets/images/paper_knowlege_label_bg.png");
    background-repeat: no-repeat;
  }

  .type-table {
    position: relative;
  }

  .type-table-paging {
    position: absolute;
    right: 0;
    top: -40px;
  }

  /deep/.type-card-no-padding .el-card__body {
    padding: 0;
  }

  .type-title {
    font-size: 14px;
    font-family: "PingFangSC-Medium", "PingFang SC";
    font-weight: bolder;
    color: #171640;
    margin-bottom: 20px;

    display: flex;
    justify-content: space-between;
    align-items: baseline;
  }

  .type-title-hightlight {
    font-size: 16px;
    font-weight: bold;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60px;
  }

  .type-title span {
    border: #171640 dashed 1px;
    padding-left: 24px;
    padding-right: 75px;
  }

  .type-title-important {
    font-size: 12px;
    color: #F5AB86;
    text-align: right;
    font-weight: normal;
  }

  /deep/.el-table .el-table__row:nth-child(even) {
    background: white;
  }

  /deep/.el-table .el-table__row:nth-child(odd) {
    background: white;
  }

  .type-title-hightlight-type,
  /deep/.paper-type-tb .el-table .el-table__header-wrapper th {
    background: #51c9a7 !important;
    color: #fff !important;
  }

  /deep/.paper-type-tb .el-table .el-table__body-wrapper {
    color: #51c9a7;
  }

  .type-title-hightlight-difficult,
  /deep/.paper-diffi-tb .el-table .el-table__header-wrapper th {
    background: #f5ab86 !important;
    color: #fff !important;
  }

  /deep/.paper-diffi-tb .el-table .el-table__body-wrapper {
    color: #f5ab86;
  }

  .type-title-hightlight-knowledge,
  /deep/.paper-knowledge-tb .el-table .el-table__header-wrapper th {
    background: #a4cab0 !important;
    color: #fff !important;
  }

  /deep/.paper-knowledge-tb .el-table .el-table__body-wrapper {
    color: #a4cab0;
  }

  /deep/.paper-type-tb-light .el-table .el-table__body-wrapper,
  /deep/.paper-diffi-tb-light .el-table .el-table__body-wrapper {
    color: #808080;
  }

  /deep/.paper-type-tb-light .el-table .el-table__header-wrapper th {
    background: #D4F2E9 !important;
    color: #555555 !important;
  }

  /deep/.paper-diffi-tb-light .el-table .el-table__header-wrapper th {
    background: #FDEAE1 !important;
    color: #555555 !important;
  }
</style>
