<template>
  <el-dialog
    :title="`补训训练计划 - 训练明细`"
    :visible.sync="dialogVisible"
    custom-class="new-edition-dialog"
    width="60%"
    @closed="closed"
    @open="open"
  >
    <div class="detailed-container">
      <el-form
        v-model="queryParam.querys"
        :inline="true"
        class="search-form"
        size="small"
      >
        <el-form-item label="考生姓名：">
          <el-input
            v-model="queryParam.querys[1].value"
            clearable
            maxlength="128"
            placeholder="请输入指标名称"
          />
        </el-form-item>
        <el-form-item label="训练状态：">
          <el-select
            v-model="queryParam.querys[2].value"
            clearable
            placeholder="请选择训练状态"
          >
            <el-option
              v-for="item in getDictionaryByCode('xlzt')"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="handleSearch"
            >搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="btn-box">
        <el-upload
          ref="upload"
          :action="actionUrl"
          :before-upload="beforeUpload"
          :headers="headers"
          :multiple="false"
          :on-error="handleError"
          :on-success="handleSuccess"
          :show-file-list="false"
          class="avatar-uploader"
        >
          <el-button
            :loading="uploadLoading"
            icon="el-icon-download"
            size="small"
            style="margin-right: 10px;"
            type="primary"
          >
            导入
          </el-button>
        </el-upload>
        <el-button
          icon="el-icon-upload2"
          size="small"
          type="warning"
          @click="exportFile"
          >导出
        </el-button>

        <el-button
          icon="el-icon-document"
          size="small"
          type="info"
          @click="templateDownload"
        >
          模版下載
        </el-button>
      </div>
      <el-table
        ref="multipleSelection"
        v-loading="loading"
        :cell-style="{'text-align': 'center'}"
        :data="tableData"
        :header-cell-style="{'text-align': 'center'}"
        :max-height="500"
        :style="{width: '100%'}"
        size="mini"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column
          :index="
            index =>
              index +
              1 +
              (queryParam.pageBean.page - 1) * queryParam.pageBean.pageSize
          "
          fixed
          label="序号"
          type="index"
          width="55"
        />
        <el-table-column
          :formatter="({userName}) => userName || '-'"
          label="考生姓名"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          :formatter="({status}) => dictionaryEscape('xlzt', status) || '-'"
          label="训练状态"
          min-width="60"
          show-overflow-tooltip
        />

        <el-table-column
          :formatter="({hour}) => (isNotEmpty(hour) ? hour : '-') || '-'"
          label="训练时长(小时)"
          show-overflow-tooltip
        />
        <el-table-column
          :formatter="({createTime}) => createTime || '-'"
          label="创建时间"
          min-width="130"
          prop="createTime"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column label="操作" min-width="80">
          <template v-slot="{row}">
            <el-button size="small" @click="showDialog('addEdit', row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-pagination
        :current-page="queryParam.pageBean.page"
        :page-size="queryParam.pageBean.pageSize"
        :page-sizes="[20, 30, 40, 50]"
        :total="queryParam.pageBean.total"
        align="right"
        background
        layout="prev, pager, next,total, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </span>

    <!--  新增修改弹层  -->
    <AddEditDialog
      v-model="dialogs.addEditDialog"
      :row-info="rowInfo"
      @submit="dialogSubmit"
    />
  </el-dialog>
</template>

<script>
import * as api from '@/api/examDataMenu/examManagerData'
import {
  getSorterDirection,
  refineRequestBody,
  setQueryValue
} from '@/utils/requestWrappers'
import {TableMixin} from '@/mixins/tableMixin'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {mapState} from 'vuex'
import {isNotEmpty} from '@/utils/helpers'
import AddEditDialog from './components/AddEditDialog.vue'

export default {
  name: 'TrainingDetailsDialog',
  components: {AddEditDialog},
  mixins: [TableMixin],
  props: {
    value: {
      type: Boolean,
      default: false
    },
    rowDetails: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      queryParam: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {property: 'planId'},
          {operation: 'LIKE', property: 'userName'},
          {property: 'status'}
        ],
        sorter: [{direction: 'DESC', property: 'createTime'}]
      },
      tableData: [],
      isCalcTableHeight: false,
      // 统一管理多个弹层
      dialogs: {
        addEditDialog: false // 新增修改弹层
      },
      rowInfo: {}, // 保存行信息
      uploadLoading: false,
      noLoadData: true
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    id() {
      return this.rowDetails?.id || ''
    },
    actionUrl: _ => window.context.portal + '/biz/userTrain/data/importExcel',
    ...mapState({
      headers: state => ({
        Authorization: `Bearer ${state.login.currentUser.token}`
      })
    })
  },
  created() {},
  methods: {
    isNotEmpty,
    dictionaryEscape,
    getSorterDirection,
    getDictionaryByCode,

    // 打开弹层
    open() {
      if (this.id) {
        this.saveLoading = true
        setQueryValue(this.queryParam, 'planId', this.id)
        const {prop, order} = getSorterDirection(this.queryParam, true)
        this.$nextTick(() => this.$refs.multipleSelection?.sort(prop, order))
      }
    },

    // 关闭弹层后
    closed() {
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this))
    },

    // 获取表格数据
    async loadData() {
      try {
        this.loading = true
        const {total = 0, rows = []} = await api.tableData(
          refineRequestBody(this.queryParam)
        )
        this.queryParam.pageBean.total = total
        const {name, unit} = this.rowDetails
        this.tableData = rows.map(i => ({...i, name, unit}))
      } finally {
        this.loading = false
      }
    },

    // 重置搜索
    resetSearch() {
      this.queryParam = this.$options.data().queryParam
      setQueryValue(this.queryParam, 'subjectId', this.id)
      this.loadData()
    },

    //  导入文件上传前
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        this.uploadLoading = true
        const {size, name} = file
        let passedOrNot = true // 是否通过验证
        const maxSize = 500 * 1024 * 1024 // 20MB
        const typeRegular = /\.(xls|xlsx)$/i
        const verification = [
          {
            condition: !typeRegular.test(name),
            result: () => this.$message.error('只能上传xls或xlsx文件类型')
          }
        ]
        verification.forEach(item => {
          if (item.condition) {
            item.result()
            passedOrNot = false
            this.uploadLoading = false
          }
        })

        passedOrNot ? resolve() : reject()
      })
    },

    // 导入文件上传成功
    async handleSuccess() {
      this.$message.success('训练明细导入成功')
      this.uploadLoading = false
      await this.loadData()
    },

    // 导入文件上传失败
    handleError() {
      this.$message.error('训练明细导入失败，请重试')
      this.uploadLoading = false
    },

    // 导出数据
    async exportFile() {
      await api.exportData(refineRequestBody(this.queryParam))
    },

    // 模板下载
    async templateDownload() {
      window.open(this.portal + '/biz/userTrain/plan/downModel', '_blank')
    },

    // 新增修改弹层提交成功后
    dialogSubmit(type) {
      switch (type) {
        case 'add':
          this.queryParam.pageBean.page = 1
          break
        case 'edit':
          break
      }
      this.loadData()
    }
  }
}
</script>

<style lang="scss" scoped>
.new-edition-dialog {
  .detailed-container {
    display: flex;
    flex-direction: column;
    row-gap: 10px;

    .btn-box {
      display: flex;
    }
  }
}
</style>
