<template>
  <dynamic-table ref="table" :rows="tableList" :columns="columns" row-class-name="recommend-voluntary-row" @expand-change="expand">
    <template #wrap-header="{columnDef: col}">
      <div>{{ col.label.replace(col.wrapBy, '') }}</div>
      <div>{{ col.wrapBy }}</div>
    </template>
    <template #推荐类型="{row}">
      <type-cell :row="row" />
    </template>
    <template #院校="{row}">
      <college-cell :row="row" />
    </template>
    <template #招生计划="{row}">
      <recruit-cell :row="row" />
    </template>
    <template #投档线年份="{row}">
      <shift-line-cell :row="row" />
    </template>
    <template #年份="{row, columnDef:col}">
      <history-year-cell :row="row" :col="col" />
    </template>
    <template #最低分="{row, columnDef:col}">
      <lowest-score-cell :row="row" :col="col" />
    </template>
    <template #位次="{row, columnDef:col}">
      <ranking-cell :row="row" :col="col" />
    </template>
    <template #录取人数="{row, columnDef:col}">
      <enroll-plan-cell :row="row" :col="col" />
    </template>
    <template #填报="{row}">
      <form-status-cell :row="row" @click="handleExpand(row)" />
    </template>
    <template #expand="{row: recommend}">
      <!-- although we used table-draggable here, the outer `sortable` props controls the draggable column. -->
      <table-draggable v-loading="recommend.loading" :drag-options="{handle: '.move-group'}" class="pl50 pr50">
        <dynamic-table :columns="majorCol" :show-header="false" :rows="recommend.majors" class="major-table">
          <template #推荐类型="{row}">
            <div class="pl25">
              <type-cell :row="row" tag-disabled dark-style />
            </div>
          </template>
          <template #院校="{row}">
            <major-cell :row="row" />
          </template>
          <template #招生计划="{row}">
            <recruit-major-cell :row="row" />
          </template>
          <template #投档线年份="{row}">
            <shift-line-major-cell :row="row" />
          </template>
          <template #录取人数="{row}">
            <enroll-plan-cell :row="row" />
          </template>
          <template #年份="{row, columnDef:col}">
            <history-year-cell :row="row" :col="col" />
          </template>
          <template #最低分="{row, columnDef:col}">
            <lowest-score-cell :row="row" :col="col" />
          </template>
          <template #位次="{row, columnDef:col}">
            <ranking-cell :row="row" :col="col" />
          </template>
          <template #录取人数="{row, columnDef:col}">
            <enroll-plan-cell :row="row" :col="col" />
          </template>
          <template v-if="!readonly" #填报="{row}">
            <el-button :type="row.selected ? 'danger' : 'primary'" @click="apply(row,recommend)">
              {{ row.selected ? '取消' : '填报' }}
            </el-button>
            <div v-if="shouldDisplayLimitationTags(row)" class="f-red mt5">有填报要求</div>
          </template>
          <template #sort="{row, $index}">
            <div class="fx-column">
              <!-- NOTE：说明此处排序不支持分页方式 -->
              <el-button :disabled="$index==0" type="text" class="el-icon-caret-top" @click="handleMajorMove(recommend, row, $index, $index-1)" />
              <i class="el-icon-rank move move-group f-primary" />
              <el-button :disabled="$index==recommend.majors.length-1" type="text" class="el-icon-caret-bottom" @click="handleMajorMove(recommend, row, $index, $index+1)" />
            </div>
          </template>
        </dynamic-table>
      </table-draggable>
    </template>
    <template #sort="{row, $index}">
      <div class="fx-column">
        <!-- NOTE：说明此处排序不支持分页方式 -->
        <el-button :disabled="$index==0" type="text" class="el-icon-caret-top" @click="handleMove(row, $index, $index-1)" />
        <i class="el-icon-rank move move-group f-primary" />
        <el-button :disabled="$index==tableList.length-1" type="text" class="el-icon-caret-bottom" @click="handleMove(row, $index, $index+1)" />
      </div>
    </template>
    <template #sequence="{row, $index}">
      <span v-if="!sortable">{{ generateSeq($index) }}</span>
      <el-select v-else :value="$index" @change="$emit('sequence-change', $index, $event)">
        <el-option v-for="opt in sequenceOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
      </el-select>
    </template>
  </dynamic-table>
</template>
<script>
import DynamicTable from '@/components/dynamic-table'
import TypeCell from '@/views/career/zhiyuan/components/PreferenceCells/TypeCell'
import CollegeCell from '@/views/career/zhiyuan/components/PreferenceCells/CollegeCell'
import RecruitCell from '@/views/career/zhiyuan/components/PreferenceCells/RecruitCell'
import ShiftLineCell from '@/views/career/zhiyuan/components/PreferenceCells/ShiftLineCell'
import EnrollPlanCell from '@/views/career/zhiyuan/components/PreferenceCells/EnrollPlanCell'
import HistoryYearCell from '@/views/career/zhiyuan/components/PreferenceCells/HistoryYearCell'
import LowestScoreCell from '@/views/career/zhiyuan/components/PreferenceCells/LowestScoreCell'
import RankingCell from '@/views/career/zhiyuan/components/PreferenceCells/RankingCell'
import FormStatusCell from '@/views/career/zhiyuan/components/PreferenceCells/FormStatusCell'
import MajorCell from '@/views/career/zhiyuan/components/PreferenceCells/MajorCell'
import RecruitMajorCell from '@/views/career/zhiyuan/components/PreferenceCells/RecruitMajorCell'
import ShiftLineMajorCell from '@/views/career/zhiyuan/components/PreferenceCells/ShiftLineMajorCell'
import TableDraggable from '@/components/TableDraggable/index.vue'

export default {
  components: {
    TableDraggable,
    ShiftLineMajorCell,
    RecruitMajorCell,
    MajorCell,
    FormStatusCell,
    RankingCell,
    LowestScoreCell,
    HistoryYearCell,
    EnrollPlanCell,
    ShiftLineCell,
    RecruitCell,
    CollegeCell,
    TypeCell,
    DynamicTable
  },
  inject: {
    'fetchVoluntaryData': { default: () => ({}) },
    'fetchVoluntaryFilter': { default: () => ({}) }
  },
  props: {
    tableList: {
      type: Array,
      default: () => []
    },
    cols: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: () => []
    },
    readonly: {
      type: Boolean,
      default: false
    },
    sortable: {
      type: Boolean,
      default: false
    },
    showSequence: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: false,
      input: '',
      selectedList: []
    }
  },
  computed: {
    commonColumns() {
      const result = []
      const ignoreCols = ['投档线年份']
      const historyCols = this.cols.filter(c => c.includes('&'))
      const scoreAndRankCols = ['最低分', '位次', '录取人数']
      const shortNameCols = ['招生计划']
      const wrapHeaderCols = [
        { matcher: (col) => col.slotBody === '招生计划', wrapBy: '招生计划' },
        { matcher: (col) => col.slotBody === '投档线年份', wrapBy: '年份' }
      ]
      this.cols.forEach((c, idx) => {
        if (ignoreCols.includes(c)) return
        if (historyCols.includes(c)) return
        const slotName = shortNameCols.find(sc => c.includes(sc))
        const def = {
          label: c,
          slotBody: slotName || c
        }
        const wrapConfig = wrapHeaderCols.find(w => w.matcher(def))
        if (wrapConfig) {
          def.slotHeader = 'wrap-header'
          def.wrapBy = wrapConfig.wrapBy
        }
        if (scoreAndRankCols.includes(c)) def.subCols = historyCols
        if (idx != 1) def.width = '90px'
        if (idx == 2) def.width = '120px'
        if (idx == 4) def.width = '110px' // 最低在同时显示`分+?+collect`时宽度不够
        result.push(def)
      })
      result.splice(3, 0, {
        width: '90px',
        label: '年份',
        slotBody: '年份',
        subCols: historyCols
      })
      if (this.showSequence) {
        result.unshift({
          width: this.sortable ? '80px' : '60px',
          label: '序号',
          slotBody: 'sequence'
        })
      }
      if (this.sortable) {
        result.unshift({
          width: '60px',
          label: '排序',
          slotBody: 'sort'
        })
      }
      return result
    },
    columns() {
      const result = [...this.commonColumns]
      result.push({
        type: 'expand',
        slotBody: 'expand',
        label: '查看'
      })
      return result
    },
    majorCol() {
      return this.commonColumns
    },
    voluntaryData() {
      // noinspection JSUnresolvedFunction
      return this.fetchVoluntaryData()
    },
    sequenceOptions() {
      return this.tableList.map((item, index) => ({
        value: index,
        label: this.generateSeq(index)
      }))
    },
    filterLimitationTags() {
      return this.fetchVoluntaryFilter()?.limitationTags || []
    }
  },
  methods: {
    shouldDisplayLimitationTags(item) {
      // 志愿表详情下，全显；推荐列表时，根据筛选条件显示
      if (this.readonly) {
        return item.limitationTags?.length > 0
      }
      if (!item.limitationTags) return false
      const safeTags = item.limitationTags?.split(',') || []
      if (!safeTags.length) return false
      return safeTags.some(t => this.filterLimitationTags.includes(t))
    },
    generateSeq(index) {
      switch (this.voluntaryData.sort) {
      case 'letter':
        return String.fromCharCode(65 + index)
      default:
        return index + 1
      }
    },
    expand(item) {
      this.$emit('expand', item)
    },
    apply(item, parent) {
      this.$emit('apply', item, parent)
    },
    handleMove(row, index, target) {
      // directly change the order of tableList
      const temp = this.tableList[index]
      this.tableList.splice(index, 1)
      this.tableList.splice(target, 0, temp)
      this.$emit('move-change', row, index, target)
    },
    handleMajorMove(group, major, index, target) {
      // directly change the order of group.majors
      const temp = group.majors[index]
      group.majors.splice(index, 1)
      group.majors.splice(target, 0, temp)
      this.$emit('move-major-change', group, major, index, target)
    },
    handleExpand(row) {
      this.$refs.table.tableCore.toggleRowExpansion(row)
    }
  }
}
</script>
<style scoped lang="scss">
.f-9b {
  color: #9b9b9b;
}

::v-deep .el-table__expanded-cell {
  padding-top: 0;
  //padding-right: 50;
  padding-bottom: 0;
  padding-left: 0;
}

::v-deep .el-table__expand-icon {
  font-size: 18px;
  color: #666;

  .el-icon-arrow-right {
    font-weight: bold;
  }
}
</style>
<style lang="scss">
@import "~@/assets/styles/variables.scss";

.el-table .major-table td {
  background-color: mix($--color-primary, #fff, 5%);
}

.recommend-voluntary-row .history-item {
  height: 32px;
  line-height: 32px;
}
</style>
