<template>
  <el-dialog v-loading="loading" v-if="visible" :visible.sync="visible" title="上传" width="30%">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <div style="padding-left: 100px;padding-bottom: 10px">
        {{ '提示:每次最多上传100条数据' }}
      </div>
      <el-form-item label="文件:" prop="FILE">
        <upload-file :file-list.sync="form.FILE" :limit="1" :file-size="200" append-to-body accept=".xlsx"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="downloadTemplate">下载模板</el-button>
      <el-button @click="goBack">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import { upload } from '@/utils/upload'
import uploadFile from '../../../../components/UploadFile/index.vue'

export default {
  components: { Pagination, uploadFile },
  directives: { waves },
  data() {
    return {
      config: config,
      visible: false,
      form: {
        FILE: []
      },
      rules: {
        FILE: [{ required: true, message: '请选择文件', trigger: 'blur' }]
      },
      loading: false
    }
  },
  methods: {
    init(e) {
      this.visible = true
    },
    goBack() {
      this.form = {
        FILE: []
      }
      this.visible = false
    },
    save() {
      const loading = this.$loading({
        lock: true,
        text: '上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const formData = new FormData()
      for (let i = 0; i < this.form.FILE.length; i++) {
        if (this.form.FILE[i].raw) {
          formData.append('FILE', this.form.FILE[i].raw)
        }
      }
      upload(
        '/hiddenLibrary/readExcel',
        formData
      ).then((data) => {
        loading.close()
        if (data.code !== '0') {
          this.$message.error(data.errorMessage)
        } else {
          this.visible = false
          this.$emit('logical-end', { result: 'OK' })
          this.form.FILE = ''
          this.$message.success('导入成功')
        }
      }).catch((e) => {
        loading.close()
        console.log(e)
      })
    },
    downloadTemplate() {
      window.open(config.fileUrl + '/uploadFiles/file/admin/20230829/隐患库导入模板.xlsx')
    }
  }
}

</script>
