<template>
  <div class="bg-page fx-column fx-cen-cen">
    <div class="index-block bg-white fx-column pt30 pb30 sticky-container">
      <div class="bar">
        <!--  步骤条-->
        <div class="step-list line">
          <div v-for="(item, index) in topStep" :key="index" class="step-item right">
            <div v-if="active.index < item.index" class="step-number" :class="{'curindex':currentStep==index}">
              {{ item.index + 1 }}
            </div>
            <i v-else class="el-icon-check" />
            <div class="step-label">{{ item.label }}</div>
          </div>
        </div>
        <div class="text-center f-primary f24 bold">
          {{ active.title }}
        </div>
      </div>
      <div class="content">
        <score
          v-show="active.index==0"
          ref="score"
          :form="form"
          :disable-watch="active.index>0"
          :province-name="currentUser.provinceName"
          :keep-value="true"
          @voluntary-ready="keepVoluntaryData"
        />
        <phase v-if="active.index==1" :list="zytbBatchesList" :form-subject="form" @onFillIn="onFillIn" />
        <recommend
          v-if="active.index==2"
          ref="recommend"
          :batch.sync="batch"
          :batch-list.sync="zytbBatchesList"
          :form-subject.sync="form"
          :selected-list="selectedList"
        />
      </div>
      <div class="text-center" :class="{'mt30':currentStep>0}">
        <el-button plain @click="toReport">查看记录</el-button>
        <el-button v-if="currentStep>0" type="primary" @click="toBackPage">上一步</el-button>
        <el-button v-if="currentStep<=1" type="primary" @click="next">下一步</el-button>
        <el-button v-if="currentStep==2" :loading="saving" type="primary" @click="confirmSave">保存</el-button>
      </div>
      <div v-if="currentStep==0" class="fx-column">
        <el-divider />
        <div class="f18 bold pf f-primary pl100">
          模拟志愿填报须知
          <i class="el-icon el-icon-info" />
        </div>
        <div class="txt f-333 f14">
          <div v-for="(item,index) in tips" :key="index">
            <i>{{ index + 1 }}</i>
            {{ item }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import Score from './components/SimulateScore'
import Phase from './components/phase'
import Recommend from './components/recommend'
import { zytbBatches } from '@/api/webApi/webQue'
import TransferMixin from '@/components/TransferMixin'
import SearchMajorProviderMixin from '@/views/career/zhiyuan/components/SearchMajorProviderMixin'
import VoluntarySaveRouteGuard from '@/views/career/zhiyuan/components/VoluntarySaveRouteGuard'
import VoluntaryIdentifierProvider from '@/views/career/zhiyuan/components/VoluntaryIdentifierProvider'
import MxConst from "@/common/MxConst";
import MxConfig from "@/common/MxConfig";
import {MessageBox} from "element-ui";
import router from "@/router";
import {debounce} from "@/utils";

export default {
  components: {
    Recommend,
    Phase,
    Score
  },
  mixins: [TransferMixin, SearchMajorProviderMixin, VoluntarySaveRouteGuard, VoluntaryIdentifierProvider],
  data() {
    return {
      input: '',
      show: false,
      topStep: [
        { index: 0, label: '高考分数', title: '(一)输入高考的成绩' },
        { index: 1, label: '填报批次', title: '(二)选择填报批次' },
        { index: 2, label: '院校专业', title: '(三)选择院校专业' },
        { index: 3, label: '保存志愿', title: '(四)我的志愿' }
      ],
      voluntaryData: null,
      batch: {},
      form: {
        score: '',
        firstSubject: '',
        lastSubject: [],
        rank: '',
        seatInput: '',
        init: false
      },
      zytbBatchesList: [],
      currentStep: 0,
      // add for edit feature
      selectedList: [],
      id: 0,
      subTitle: '',
      defaultSort: [],
      saving: false,
      //
      tips: [
        '当系统在非正式志愿模拟填报阶段，您可输入不同分数进行多次志愿智能模拟，找准自己的目标院校和专业。当系统在正式填报阶段，您可以修改和保存一次成绩，但填报次数不受限制。',
        '期中、期末考试是对阶段性学习成果的考验，也是检验自己的目标院校或专业是否设定合理，请阶段性进行志愿模拟填报以便及时调整目标院校和专业。',
        '各地的高考政策不同，模拟志愿填报会根据当前注册用户所属地自动匹配。',
        '模拟填报共有四个步骤。'
      ]
    }
  },
  computed: {
    ...mapGetters(['currentUser', 'scoreLocked']),
    active() {
      return this.topStep.find(item => item.index == this.currentStep)
    },
    voluntaryDataCalculate() {
      // NOTE: will override by history voluntary data in edit mode
      const param = this.voluntaryData || {}
      const defaultLimit = { groups: 9999, profession: 9999 }
      // noinspection JSUnresolvedVariable
      const firedLimit = param.batches?.find(i => i.batch == this.batch.batch) || defaultLimit
      return {
        ...param,
        firedLimit
      }
    },
    batchScoreRangeCalculate() {
      return this.calculateScoreBatchRange()
    }
  },
  provide() {
    return {
      fetchVoluntaryData: () => this.voluntaryDataCalculate,
      fetchScoreBatchRange: () => this.batchScoreRangeCalculate
    }
  },
  mounted() {
    this.prepareData()
    this.reloadScoreAndMode()
  },
  methods: {
    prepareData() {
      // do nothing, hook for edit mode
    },
    calculateScoreBatchRange() {
      // for re-use
      if (!this.voluntaryData || !this.batch.batch) return [0, 0]
      const maxScore = this.voluntaryData.maxScore
      const minBatch = this.batch.score2 || this.batch.score1
      let maxBatch = maxScore
      const batchIndex = this.zytbBatchesList.indexOf(this.batch)
      if (batchIndex > 0) {
        const upBatch = this.zytbBatchesList[batchIndex - 1]
        maxBatch = upBatch.score2 || upBatch.score1
      }
      return [minBatch, Math.min(maxScore, maxBatch)]
    },
    reloadScoreAndMode() {
      if (this.prevData.score && this.prevData.firstSubject) {
        this.form = this.prevData
        this.currentStep = 0
        // this.next() 暂不用跳下一步，因为无法输入位次
      } else {
        const modeParams = this.currentUser.mode?.split(',') || []
        this.form.score = this.currentUser.score
        this.form.firstSubject = modeParams.first()
        this.form.lastSubject = modeParams.slice(1)
      }
      // Fill seatInput with current user's cached seat. This value may be changed by setRankByScore feature
      this.$set(this.form, 'seatInput', this.currentUser.seatInput || 0) // init reactive seatInput
      if (!this.form.seatInput * 1 || this.scoreLocked) this.form.init = true
      else setTimeout(() => this.form.init = true, 800)
    },
    keepVoluntaryData(data) {
      this.voluntaryData = data
    },
    toReport() {
      this.transferTo('/zhiyuan/volunteerList')
    },
    onFillIn(item) {
      this.batch = item
      this.selectedList = [] // reset the selected list
      this.currentStep = 2
    },
    next() {
      const currentActive = this.currentStep
      switch (currentActive) {
      case 0:
        this.submitScore()
        break
      case 1:
        this.$message.warning('请点击批次按钮进行填写')
        break
      }
    },
    async submitScore() {
      await this.$refs.score.validate()
      this.loadRecommendBatchList()
    },
    toBackPage() {
      if (this.currentStep <= 0) {
        this.$router.back()
        return
      }
      const next = () => this.currentStep--
      if (this.currentStep < 2) {
        next()
        return
      }
      this.processConfirmThenSave(next)
    },
    loadRecommendBatchList() {
      const mode = [this.form.firstSubject, ...this.form.lastSubject].filter(i => !!i).toString()
      zytbBatches({
        score: this.form.score,
        mode: mode
      }).then((res) => {
        this.zytbBatchesList = res.rows
        this.currentStep = 1
      })
    },
    isSelectedListChanged() {
      // judge whether the selected list is modified by the user
      return this.selectedList.length > 0
    },
    async confirmSave() {
      if (!this.isSelectedListChanged()) {
        this.msgError('还未填报任何院校/专业组')
        return
      }
      this.saving = true
      try {
        await this.processSave()
      } finally {
        this.saving = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.bar {
  padding: 0 100px 20px;
  border-bottom: 1px solid #d6d6d6;
}

.step-list {
  display: flex;
  justify-content: space-between;
  position: relative;
  margin-bottom: 50px;
}

.step-list.line::before {
  position: absolute;
  content: "";
  width: 100%;
  height: 2px;
  top: 50%;
  background: var(--themeColor);
  z-index: 0;
}

.step-item {
  position: relative;
  background: #fff;
  z-index: 2;
  border: 1px solid var(--themeColor);
  border-radius: 50%;
  color: var(--themeColor);
  width: 36px;
  height: 36px;
  line-height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.step-label {
  font-weight: bolder;
  color: #555555;
  width: 100px;
  text-align: center;
  font-size: 14px;
  position: absolute;
  bottom: -40px;
}

.step-number {
  line-height: 36px;
  text-align: center;
}

.step-number.curindex {
  width: 36px;
  height: 36px;
  flex-shrink: 0;
  background: var(--themeColor);
  border-radius: 50%;
  color: #fff;
}

.sticky-container {
  overflow-y: scroll;
  height: calc(100vh - 70px);
}

.txt {
  padding: 20px 100px;
}

.txt div {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  line-height: 1.6;
}

.txt div i {
  display: block;
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  margin-right: 30px;
  text-align: center;
  line-height: 24px;
  color: #fff;
  border-radius: 50%;
  background-color: var(--themeColor);
}
</style>
