<template>
  <div>
    <div>
      <el-form ref="importForm" :model="temp" label-position="top" label-width="90px">
        <el-form-item label="文件模板(请按照模板格式填写数据)">
          <el-button
            size="small"
            icon="el-icon-download"
            class="down-btn"
            @click="downloadTemplate"
          >点击下载模板</el-button>
        </el-form-item>
        <el-form-item label="导入文件(文件大小不可超过8MB)" class="import-box">
          <!-- “文件大小不可超过8MB”、“请上传格式为以.xlsx或.xls结尾的excel文件” -->
          <el-upload
            action="#"
            class="upload-demo"
            ref="upload"
            :on-preview="handlePreview"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :file-list="fileList"
            :auto-upload="false"
            accept=".xls, .xlsx"
          >
            <!-- <i class="el-icon-upload" slot="trigger"></i> -->
            <el-button slot="trigger" icon="el-icon-upload" class="upload-btn" size="small">点击导入文件</el-button>
            <el-button
              v-show="0"
              style="margin-left: 10px;"
              size="small"
              type="success"
              @click="submitUpload"
            >上传到服务器</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer text-center">
      <el-button @click="saveData(0)">取消</el-button>
      <el-button type="primary" @click="saveData(1)">确定</el-button>
    </div>
    <el-dialog
      title="导入数据结果"
      :visible.sync="dialogResultVisible"
      :append-to-body="true"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      width="30%"
    >
      <div class="result-box">
        <div>
          <i
            v-if="failTotal>0"
            class="el-icon-warning"
            :class="[successTotal===0&&failTotal>0?'fail-all-bgc':'fail-bgc']"
          ></i>
          <i v-else class="el-icon-success"></i>
        </div>
        <div>成功导入{{successTotal}}个号码，{{failTotal}}个号码导入失败</div>
        <div v-if="failTotal>0">
          <span>失败数据文件：</span>
          <a class="down-txt" @click="downloadFail">点击下载</a>
        </div>
      </div>
      <div slot="footer" class="dialog-footer text-center">
        <el-button type="primary" @click="handleResultClose">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { importExcelData, downloadModel } from '@/api/article'

export default {
  name: 'ImprtData',
  props: ['temp'],
  data() {
    return {
      failDataFile: '',
      successTotal: 0,
      failTotal: 0,
      dialogResultVisible: false,
      fileList: [],
      dialogFormVisible: false
    }
  },
  created() {},
  methods: {
    validateFiles() {
      let nv =
        this.fileList.length &&
        Object.prototype.toString.call(this.fileList[0]) === '[object Object]'
          ? this.fileList[0].raw
          : { size: 0 }
      if (Number(nv.size / 1024 / 1024) > 8) {
        this.$message.warning('文件大小不可超过8MB')
        return false
      } else {
        return true
      }
    },
    downloadFail() {
      // failDataFile
      console.log(this)
    },
    handleResultClose(va) {
      this.dialogResultVisible = false
      debugger
      if (this.temp.isAddGo) {
        if (va) {
          this.$emit('addSave', this.fileList[0].raw)
        } else {
          this.$emit('addSave')
        }
      } else {
        if (va) {
          this.$emit('indexSave', va)
        }
      }
    },
    downloadTemplate() {
      downloadModel({
        user_sn: this.$publicTools.decrypt(localStorage.getItem('user_sn'))
      })
    },
    addCallback(status) {},
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleChange(file, fileList) {
      // 替换为最新的
      console.log(arguments)
      this.fileList = [file]
      this.validateFiles()
    },
    submitUpload() {
      if (this.temp.isAddGo) {
        this.$emit('addSave', this.fileList[0].raw)
      } else {
        var form = new FormData()
        form.append(
          'user_sn',
          this.$publicTools.decrypt(localStorage.getItem('user_sn'))
        )
        form.append('strategy_sn', this.temp.strategy_sn)
        form.append('upload', this.fileList[0].raw)
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.9)'
        })
        importExcelData(form)
          .then(res => {
            loading.close()
            this.dialogResultVisible = true
            this.failDataFile = res.info.failDataFile || ''
            this.failTotal = res.info.failTotal || 0
            this.successTotal = res.info.successTotal || 0
          })
          .catch(err => {
            loading.close()
            this.$message.warning(err)
          })
      }
    },
    handleDownload() {},
    saveData(status) {
      // 0 cancel/close 1 addSave  dialogStatus/create/update
      if (status) {
        this.$refs['importForm'].validate(valid => {
          if (!this.fileList.length) {
            this.$message.warning('请先导入文件')
            return
          }
          if (valid && this.validateFiles()) {
            this.submitUpload()
          }
        })
      } else {
        this.$emit('addSave', 0)
        this.$emit('indexSave', 0)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.el-icon-upload {
  color: mediumblue;
  font-size: 24px;
  vertical-align: middle;
}
.result-box {
  line-height: 30px;
  text-align: center;
  .down-txt {
    color: rgb(77, 193, 244);
  }
  .el-icon-success {
    color: rgb(3, 182, 21);
    font-size: 33px;
  }
  .el-icon-warning {
    font-size: 33px;
  }
  .fail-all-bgc {
    color: #d9001b;
  }
  .fail-bgc {
    color: #f59a23;
  }
}
.down-btn,
.upload-btn {
  color: #3691ff;
}

label {
  font-weight: normal;
}
.import-box::before {
  content: '*';
  color: #ff4949;
  margin-right: 4px;
  display: inline-block;
}
</style>
