<template>
  <div>
    <el-card>
      <mx-condition ref="condition" :query-params="queryParams" :require-fields="requireFields" @query="handleQuery"
                    @invalid="handleInvalidQuery"></mx-condition>
    </el-card>
    <div class="mt20">
      <el-button type="primary" plain icon="el-icon-plus" size="mini" class="mb5" @click="handleSettingAdd">新增
      </el-button>
      <mx-table :prop-defines="tableDefines" :rows="dataList">
        <template #actions="{row}">
          <el-button type="text" @click="handleSettingEdit(row)">
            <i class="el-icon-edit"></i>编辑
          </el-button>
          <el-button type="text" @click="handleSettingDelete(row)">
            <i class="el-icon-delete"></i>删除
          </el-button>
        </template>
      </mx-table>
      <pagination v-show="total>queryParams.pageSize" :total="total" :limit.sync="queryParams.pageSize"
                  :page.sync="queryParams.pageNum" @pagination="handleQuery"></pagination>
    </div>
    <el-drawer v-if="stepsVisible" :visible.sync="stepsVisible" :title="modifyTitle" :append-to-body="true" size="70%">
      <round-setting-steps :settingModel="settingModel" :default-active-step="activeStep" :year-options="yearOptions"
                           @do-post="handleSubmit" v-loading="loading"></round-setting-steps>
    </el-drawer>
  </div>
</template>

<script>
import * as ext from '@/utils'
import selectTranslateMixin from '@/components/Cache/modules/mx-select-translate-mixin'
import RoundModelConvert from './round-model-convert'
import MxCondition from '@/components/MxCondition/mx-condition'
import { deleteRound, getScoreImportConfig, roundList, saveScoreImportConfig } from '@/api/webApi/selection'
import RoundSettingSteps from '@/views/elective/publish/components/steps/round-setting-steps'

export default {
  mixins: [selectTranslateMixin, RoundModelConvert],
  name: 'round-settings',
  components: { RoundSettingSteps, MxCondition },
  data() {
    return {
      loading: false,
      // drawer
      stepsVisible: false,
      activeStep: 0,
      // query list
      requireFields: ['year'],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        year: ''
      },
      dataList: [],
      total: 0,
      tableDefines: {
        'year': {
          label: '学年'
        },
        'name': {
          label: '次数'
        },
        'groupIdsName': {
          label: '选科组合'
        },
        'beginTime': {
          label: '开始'
        },
        'endTime': {
          label: '结束'
        },
        'stateName': {
          label: '状态'
        },
        'actions': {
          label: '操作',
          slot: 'actions'
        }
      },
      // modify
      settingModel: {},
      settingDialogVisible: false
    }
  },
  computed: {
    modifyTitle() {
      const type = this.settingModel.roundId ? '编辑' : '新增'
      return type + '/' + this.settingModel.year + '/' + this.settingModel.name
    },
    yearOptions() {
      return this.$refs.condition.conditions.find(c => c.key === 'year').list || []
    }
  },
  mounted() {
    console.log('round-settings mounted')
  },
  methods: {
    handleSettingsOpen() {
      this.settingsVisible = !this.settingsVisible
    },
    handleInvalidQuery() {
      this.dataList = []
    },
    handleQuery() {
      roundList(this.queryParams).then(res => {
        this.total = res.total
        this.dataList = res.rows || []
        this.dataList.forEach(r => {
          this.translateStateName(r)
          this.translateGroupIds(r)
        })
      })
    },
    translateStateName(row) {
      this.$set(row, 'stateName', row.allowSelect ? '开启' : '关闭')
    },
    translateGroupReady() {
      this.dataList.forEach(this.translateGroupIds)
    },
    // modify
    handleSettingAdd() {
      this.settingModel = {
        year: this.queryParams.year,
        name: `第${this.dataList.length + 1}次选科`,
        groupModels: [],
        dateRange: ext.getDefaultSelectRange(),
        state: true,
        importWeight: [],
        roundGroups: [],
        enableEsign: false,
        enablePaperSign: false,
        preferenceCount: 1,
        rankInvisible: false,
        scoreInvisible: false
      }
      this.activeStep = 0
      this.stepsVisible = true
    },
    handleSettingEdit(row) {
      getScoreImportConfig(row.roundId).then(res => {
        const model = this.fromApiModel(res.data)
        this.settingModel = model
        this.activeStep = model.importWeight.length ? 1 : 0
        this.stepsVisible = true
      })
    },
    handleSettingDelete(row) {
      const fullName = row.year + row.name
      this.$confirm('确认删除' + fullName + '?').then(() => {
        deleteRound(row.roundId).then(res => {
          this.msgSuccess('删除成功')
          this.queryParams.pageNum = 1
          this.handleQuery()
        })
      })
    },
    handleSubmit(commit) {
      this.loading = true
      const round = this.toApiModel(commit)
      // 提交
      saveScoreImportConfig(round).then(res => {
        this.stepsVisible = false
        this.msgSuccess('保存成功')
        this.handleQuery()
      }).finally(() => this.loading = false)
    }
  }
}
</script>

<style lang="scss">

</style>
<style scoped>

</style>
