<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-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"
              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="400px"
    >
      <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">
          <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,
  downloadFailExcel
} from '@/api/article'

export default {
  name: 'ImprtData',
  props: ['temp'],
  data() {
    return {
      failDataFile: '',
      successTotal: 0,
      failTotal: 0,
      dialogResultVisible: false,
      fileList: [],
      dialogFormVisible: false
    }
  },
  created() {
    if (this.temp.upload && this.temp.uploadname) {
      this.fileList = [this.temp.upload]
    }
  },
  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() {
      downloadFailExcel({
        user_sn: this.$publicTools.decrypt(localStorage.getItem('user_sn')),
        filename: this.failDataFile
      })
    },
    handleResultClose() {
      this.dialogResultVisible = false
      if (this.temp.isAddGo) {
        this.$emit('addSave', this.fileList[0].raw)
      } else {
        this.$emit('indexSave', 1)
      }
    },
    downloadTemplate() {
      downloadModel({
        user_sn: this.$publicTools.decrypt(localStorage.getItem('user_sn'))
      })
    },
    handleRemove(file, fileList) {
      this.fileList = []
    },
    handleChange(file, fileList) {
      // 替换为最新的
      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.isAddGo ? '' : 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)
          })
      }
    },
    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>
