<template>
  <el-dialog
    :title="dialogTitle"
    width="75%"
    :visible.sync="dialogVisible"
    custom-class="create-dialog"
    @close="activeStep = 0"
  >
    <y-step
      :active="activeStep"
      class="steps"
      size="medium"
    >
      <y-step-item title="上传模板"></y-step-item>
      <y-step-item title="确认信息"></y-step-item>
      <y-step-item title="完成"></y-step-item>
    </y-step>
    <div class="content-wrapper">
      <template v-if="activeStep === 0">
        <div class="upload-wrapper">
          <slot name="tips" class="tips">

          </slot>
          <div>
            <el-upload
              class="upload-area"
              drag
              action=""
              :multiple="false"
              :show-file-list="false"
              :http-request="httpRequest"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div slot="tip" class="el-upload__tip">
                <p>只能上传excel文件<span v-if="size">，且不超过{{ size }}kb</span></p>
                <el-button style="margin-top:10px" class="mt-10" type="primary" @click="handleDownload">下载模板文件</el-button>
              </div>
            </el-upload>
          </div>
        </div>
      </template>
      <template v-else-if="activeStep === 1">
        <slot name="confirm"></slot>
      </template>
    </div>

    <template #footer>
      <y-button
        v-if="showLastStep"
        @click="activeStep--"
      >上一步</y-button>
      <y-button
        v-if="showSubmit"
        type="primary"
        :loading="submitLoading"
        @click="handleSubmit"
      >提 交</y-button>
    </template>

  </el-dialog>
</template>

<script>
import XLSX from 'xlsx'
import { Message } from 'element-ui'
import { find, round } from 'lodash'
import moment from 'moment'

export default {
  name: 'YBatchUpload',
  props: {
    dialogTitle: {
      type: String,
      default: '批量上传'
    },
    size: {
      type: [String, Number],
      default: 0
    },
    downloadUrl: {
      type: String,
      required: true
    },
    range: {
      type: Number,
      default: 1
    },
    columns: {
      type: Array,
      default: () => []
    },
    showSubmitButton: {
      type: Boolean,
      default: true
    },
    handleFunc: {
      type: Function
    },
    submitFunc: {
      type: Function
    }

  },
  data() {
    return {
      dialogVisible: false,
      activeStep: 0,
      submitLoading: false,
      dbData: []
    }
  },
  computed: {
    showLastStep() {
      return this.activeStep !== 0
    },
    showSubmit() {
      return this.$props.showSubmitButton && this.activeStep === 1
    }
  },
  methods: {
    handleDownload() {
      window.open(this.downloadUrl, '_parent')
    },
    httpRequest(e) {
      const file = e.file // 文件信息
      if (!file) {
        // 没有文件
        return false
      } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        // 格式根据自己需求定义
        this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }

      const fileReader = new FileReader()
      fileReader.onload = async(ev) => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary' // 以字符编码的方式解析
          })
          const exlname = this.sheetName || workbook.SheetNames[0] // 根据传人的表名读取，否则读第一张
          const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname], { defval: '', range: this.range }) // 生成json表格内容
          if (!exl) {
            this.$message.error('未找到对应表格，请重新上传！')
            return false
          }
          // 将 JSON 数据挂到 data 里
          this.dbData = this.formatDbData(exl)

          const res = await this.handleFunc(this.dbData)
          this.$emit('on-handle', res)
          this.activeStep = 1
          // await this.submitFunc(res)

          // document.getElementsByName('file')[0].value = '' // 根据自己需求，可重置上传value为空，允许重复上传同一文件
        } catch (e) {
          Message({
            showClose: true,
            message: e.message,
            type: 'error'
          })
          console.log('出错了', e.message)
          this.initData()
          return false
        }
      }
      fileReader.readAsBinaryString(file)
    },
    // 格式化dbData， 将excel文件的内容，转成后端需要的格式
    formatDbData(dbData) {
      if (!Array.isArray(dbData)) {
        throw new TypeError('传入类型不是Array类型')
      }
      const res = dbData.map(item => {
        const obj = {}
        Object.keys(item).forEach(key => {
          // 查找与key相同的column
          const column = find(this.columns, col => {
            return col.label.trim().includes(key)
          })
          if (typeof item[key] === 'number') {
            // 如果是数字类型，保留8位小数
            item[key] = round(item[key], 8)
          }
          if (column) {
            if (column.type === 'date-picker') {
              const format = column.format || 'YYYY-MM-DD'
              if (!isNaN(item[key])) {
                obj[column.prop] = this.formateDate(Number(item[key]), format)
              } else {
                obj[column.prop] = (moment(item[key]).format(format) === 'Invalid date' ? '' : moment(item[key]).format(format))
              }
            } else {
              const format = column.format
              if (format && format.includes('YYYY-MM-DD') && !isNaN(item[key])) {
                obj[column.prop] = this.formateDate(Number(item[key]), format)
              } else {
                if (item[key] && typeof item[key] === 'string') {
                  item[key] = item[key].trim()
                }
                obj[column.prop] = item[key]
              }
            }
          }
        })
        return obj
      })
      return res
    },
    async handleSubmit() {
      this.submitLoading = true
      try {
        await this.submitFunc()
        this.dialogVisible = false
        this.$emit('on-submit')
        this.activeStep = 0
      } catch (e) {
        console.log(e)
      } finally {
        this.submitLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .create-dialog {
  .el-dialog__body {
    padding: 0;
    .upload-area .el-upload{
      width: 100%;
      .el-upload-dragger {
        width: 100%;
      }
    }
  }
}

.steps {
  border-bottom: 2px solid #ccc;
}
.content-wrapper {
  padding: 12px;

  .tips {
    color: #333;
    font-weight: bolder;
    p:nth-child(2){
      margin-top: 10px;
    }
  }

  .upload-wrapper {
    padding: 0 10%;
  }
}
</style>
