<template>
  <div class="app-container">
    <el-card class="mb10" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
        <el-form-item label="名称" prop="scoreName" class="form-item-readonly">
          <el-input v-model="queryParams.scoreName" placeholder="请输入导入名称" clearable size="small"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item class="form-item-readonly">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['mxjb:mxjbSelectedScore:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['mxjb:mxjbSelectedScore:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
                   v-hasPermi="['mxjb:mxjbSelectedScore:import']">上传
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="mini" @click="importTemplate"
                   v-hasPermi="['mxjb:mxjbSelectedScore:import']">下载模板
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mxjbSelectedScoreList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center" prop="importId"/>
      <el-table-column label="名称" align="center" prop="scoreName"/>
      <el-table-column label="状态" align="center" prop="message"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['mxjb:mxjbSelectedScore:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['mxjb:mxjbSelectedScore:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="fx-row mt20" v-if="enableSelection">
      <el-button plain type="primary" size="medium" :disabled="multiple" @click="handleSelection">确认导入
      </el-button>
    </div>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改选科分数对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="80px">
        <el-form-item label="名称" prop="scoreName">
          <el-input v-model="form.scoreName" placeholder="请输入导入名称"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '&name=' + upload.fileName + '&updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-change="handleFileChanged"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <div class="mt10 mb10">
            <el-input v-model="upload.fileName" placeholder="输入导入名称"></el-input>
          </div>
          <el-checkbox v-model="upload.updateSupport"/>
          是否更新已经存在的数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="detailVisible" :visible.sync="detailVisible" :title="detailTitle" width="70%" append-to-body>
      <round-score-import-detail :import-id="detailImportId"></round-score-import-detail>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMxjbSelectedScoreImport,
  getMxjbSelectedScoreImport,
  delMxjbSelectedScoreImport,
  addMxjbSelectedScoreImport,
  updateMxjbSelectedScoreImport,
  exportMxjbSelectedScoreImport
} from '@/api/webApi/mxjbSelectedScoreImport'
import {
  importTemplate
} from '@/api/webApi/mxjbSelectedScore'
import auth from '@/utils/auth'
import consts from '@/common/mx-const'
import RoundScoreImportDetail from '@/views/permission/round-score-import-detail'

export default {
  name: 'round-score-import',
  components: { RoundScoreImportDetail },
  props: {
    defaultShowSearch: {
      type: Boolean,
      default: true
    },
    enableSelection: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 展示明细
      detailVisible: false,
      detailImportId: 0,
      detailTitle: '',
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: this.defaultShowSearch,
      // 总条数
      total: 0,
      // 选科分数表格数据
      mxjbSelectedScoreList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 导入名称
        fileName: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + auth.getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/mxjb/mxjbSelectedScore/importData?type=' + consts.enum.scoreImportType.manual
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        scoreName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        scoreName: [{
          required: true,
          message: '导入名称必填'
        }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询选科分数列表 */
    getList() {
      this.loading = true
      listMxjbSelectedScoreImport(this.queryParams).then(response => {
        this.mxjbSelectedScoreList = response['rows']
        this.total = response['total']
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        importId: null,
        state: null,
        scoreName: null,
        createdTime: null,
        updatedTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.importId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.importId || this.ids
      getMxjbSelectedScoreImport(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改导入名称'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.importId != null) {
            updateMxjbSelectedScoreImport(this.form).then(_ => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addMxjbSelectedScoreImport(this.form).then(_ => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.importId || this.ids
      this.$confirm('是否确认删除选科分数编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delMxjbSelectedScoreImport(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有选科分数数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        return exportMxjbSelectedScoreImport(queryParams)
      }).then(response => {
        this.download(response['msg'])
        this.exportLoading = false
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '成绩上传'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response['msg'])
      })
    },
    // 文件选中
    handleFileChanged(file) {
      let pureName = file.name
      const dotIdx = pureName.lastIndexOf('.')
      if (dotIdx > -1) pureName = pureName.substring(0, dotIdx)
      this.upload.fileName = pureName
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg || '导入成功', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.upload.fileName) {
        this.$alert('请输入导入名称')
        return
      }
      this.$refs.upload.submit()
    },
    /** 打开详情页 */
    handleDetail(row) {
      this.detailImportId = row.importId
      this.detailTitle = row.scoreName + '详情'
      this.detailVisible = true
    },
    handleSelection() {
      const selects = this.mxjbSelectedScoreList.filter(i => this.ids.includes(i.importId))
      const invalids = selects.filter(i => i.state != 1)
      if (invalids.length > 0) {
        this.$alert(`您选择的[${invalids.map(i => i.scoreName)}]数据不正确，不能用作选科成绩`)
        return
      }
      this.$emit('selectionChanged', selects)
    }
  }
}
</script>
