<template>
  <el-dialog
    v-dialog-drag
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogVisible"
    width="800px"
    append-to-body
    @close="handleCancel"
  >
    <el-steps :active="active" finish-status="success">
      <el-step title="下载模板" />
      <el-step title="上传图片" />
      <el-step title="上传表格" />
    </el-steps>
    <div v-show="active === 0" class="import-content">
      <p>第一步：下载模板并按要求填写</p>
      <div class="warning-tips warning">
        <p>1、为了避免导入失败，请在每次批量导入时下载最新的模板。</p>
        <p>2、请先下载并安装VBA插件，并且打开文件的时候选择“启用宏”(wps)或“启用内容”(office)
          <el-popover placement="top-start" :width="200" trigger="hover">
            <div>
              <img class="tips-image" src="@/assets/images/import_wps.png" alt="启用宏">
              <img class="tips-image" src="@/assets/images/import_office.png" alt="启用内容">
            </div>
            <span />
            <i slot="reference" class="el-icon-warning-outline" />
          </el-popover>
        </p>
      </div>
      <el-button size="mini" type="primary" @click="handleDownloadTemplate">下载模板</el-button>
      <el-button size="mini" plain>下载WPS VBA插件</el-button>
    </div>
    <div v-show="active === 1" class="import-content">
      <p>第二步：上传导入文件中所需图片</p>
      <div class="warning-tips warning">
        <p>请提前命名好图片，名称不能重复，最多可上传500张。</p>
      </div>

      <el-card class="card-wrapper">
        <el-tabs v-model="activeTabName" class="upload-result-tabs" @tab-click="handleTabClick">
          <el-tab-pane label="上传成功" :name="uploadPictureMap.success">
            <div v-for="file in successImageList" :key="file.id" class="d-flex upload-list-item">
              <div>
                <el-image
                  :src="file.url"
                  fit="cover"
                  :style="`width: 20px;height: 20px;marginRight: 6px`"
                  :preview-src-list="[file.url]"
                />
                <span>{{ file.fileName }}</span>
              </div>
              <!--              <i class="el-icon-delete warning" @click="handleRemoveSuccessImage(file, i)" />-->
            </div>
          </el-tab-pane>
          <el-tab-pane label="上传失败" :name="uploadPictureMap.uploading">
            <div v-for="(file, index) in errorImageList" :key="file.id" class="d-flex upload-list-item">
              <div class="error-tips d-flex">
                <p>{{ file.name }}</p>
                <span class="warning" style="font-size: 14px">{{ file.remark }}</span>
              </div>
              <i class="el-icon-circle-close warning" @click="handleRemoveErrorImage(file, index)" />
            </div>
          </el-tab-pane>
        </el-tabs>
        <div class="card-header-options">
          <slot name="upload-image" />
          <upload-button
            ref="uploadImageRef"
            :action="imageAction"
            :accept="'.jpg,.jpeg,.png,.gif'"
            :show-file-list="false"
            list-type="text"
            :limit="500"
            :multiple="true"
            :http-request="handleUploadImage"
          >
            <el-button size="mini">上传图片</el-button>
          </upload-button>
          <!--          <el-button style="margin-left: 6px" size="mini" type="danger">删除</el-button>-->
        </div>
      </el-card>

    </div>
    <div v-show="active === 2" class="import-content">
      <div v-if="!localUploadExcelTag">
        <p>第三步：按照模板格式填写后上传Excel文件</p>
        <upload-button
          ref="uploadExcel"
          :action="excelAction"
          :drag="true"
          :show-file-list="true"
          :file-list.sync="successExcelList"
          :upload-data="uploadData"
          :accept="'.xlsx, .xls, .xlsm'"
          :before-upload="() => { }"
          :auto-upload="false"
          :http-request="handleUploadExcel"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </upload-button>
      </div>
      <div v-else>
        <div v-if="localExcelError">
          <slot name="error-result" />
        </div>
        <el-result v-else icon="success" title="导入成功" />
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button v-show="active !== 0 && !localUploadExcelSuccess" size="mini" @click="handleLast">上一步</el-button>
      <el-button :loading="uploadExcelLoading" size="mini" type="primary" @click="handleNext">{{ active >= 2 ?
        localExcelError ? '重新导入' : localUploadExcelSuccess ? '完成' : '提交' : '下一步' }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import UploadButton from '@/components/Upload/UploadButton'
import SnowflakeId from 'snowflake-id'
import { compressImg } from '@/utils'

const uploadPictureMap = {
  uploading: '1',
  success: '2'
}
const errorType = {
  repeat: '1', // 图片重复不可以下一步
  error: '2'
}
export default {
  components: {
    UploadButton
  },
  props: {
    imageAction: {
      type: String,
      default: ''
    },
    excelAction: {
      type: String,
      default: ''
    },
    uploadImageFn: {
      type: Function,
      default: () => { }
    },
    uploadExcelFn: {
      type: Function,
      default: () => { }
    },
    uploadExcelTag: {
      type: Boolean,
      default: () => false
    },
    excelError: {
      type: Boolean,
      default: () => false
    },
    // 成功导入 且 无措
    uploadExcelSuccess: {
      type: Boolean,
      default: () => false
    },
    excelErrorTableData: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      uploadExcelLoading: false,
      uploadPictureMap,
      title: '批量导入',
      dialogVisible: false,
      active: 0,
      activeTabName: uploadPictureMap.success,
      successImageList: [],
      successExcelList: [],
      errorImageList: [],
      uploadData: {
        uploadTag: null
      } // 匹配上传的图片和excel
    }
  },
  computed: {
    // 是否上传过excel
    localUploadExcelTag: {
      get() {
        return this.uploadExcelTag
      },
      set(val) {
        this.$emit('update:uploadExcelTag', val)
      }
    },
    localUploadExcelSuccess: {
      get() {
        return this.uploadExcelSuccess
      },
      set(val) {
        this.$emit('update:uploadExcelSuccess', val)
      }
    },
    localExcelError() {
      return this.excelError
    },
    localExcelErrorTableData: {
      get() {
        return this.excelErrorTableData
      },
      set(val) {
        this.$emit('update:excelErrorTableData', val)
      }
    }
    // localExcelErrorColumns() {
    //   return this.excelErrorColumns
    // }
  },
  methods: {
    handleOpen() {
      this.dialogVisible = true
      this.uploadData.uploadTag = new SnowflakeId({ mid: 42, offset: (2019 - 1970) * 31536000 * 1000 }).generate()
    },
    handleCancel() {
      this.dialogVisible = false
      this.active = 0
      this.localUploadExcelTag = false
      this.successImageList = []
      this.errorImageList = []
      this.localExcelErrorTableData = []
      this.localUploadExcelTag = false
      this.localUploadExcelSuccess = false
      this.successExcelList = []
    },
    handleNext() {
      // 上传图片
      if (this.active === 1 && this.errorImageList && this.errorImageList.find(err => err.type === errorType.repeat)) {
        this.$modal.msgError('请先删除重复图片，重新上传')
      } else if (this.active === 2) {
        if (!this.localExcelError) return this.$refs.uploadExcel.upload()
        // 重新导入
        this.localExcelErrorTableData = []
        this.localUploadExcelTag = false
        this.localUploadExcelSuccess = false
      } else {
        if (this.active++ > 2) {
          this.active = 0
          this.$emit('ok')
          this.handleCancel()
        }
      }
    },
    handleLast() {
      if (this.active-- < 1) this.active = 0
    },
    handleDownloadTemplate() {
      this.$emit('download')
    },
    // TODO
    handleRemoveSuccessImage(file, index) {
      this.successImageList.splice(index, 1)
    },
    handleRemoveErrorImage(file, index) {
      this.errorImageList.splice(index, 1)
    },
    handleUploadImage(value) {
      const find = this.successImageList.find(item => item.name === value.file.name.split('.')[0])
      if (find) {
        this.errorImageList = this.errorImageList.concat({
          name: value.file.name,
          remark: '图片名称重复',
          type: errorType.repeat
        })
      } else {
        compressImg(value.file, null, 300).then(res => {
          const formData = new FormData()
          formData.append('file', res.file)
          formData.append('uploadTag', this.uploadData.uploadTag)
          this.uploadImageFn(formData).then(({ data }) => {
            data.name = data.fileName
            data.url = data.fileUrl
            this.successImageList = this.successImageList.concat(data)
          }).catch(err => {
            console.log('err', err)
          })
        })
      }
    },
    handleUploadExcel(value) {
      const formData = new FormData()
      formData.append('file', value.file)
      formData.append('uploadTag', this.uploadData.uploadTag)
      this.uploadExcelLoading = true
      this.$emit('upload-excel', formData)
    },
    handleTabClick(tab) { },
    onResetLoading() {
      this.uploadExcelLoading = false
    }
  }
}
</script>

<style scoped lang="scss">
.warning-tips {
  font-size: 12px;
  margin: 10px 0 25px 0;

  p {
    margin: 4px 0;
  }
}

.card-wrapper {
  ::v-deep.el-card__body {
    position: relative;

    .card-header-options {
      position: absolute;
      top: 25px;
      right: 20px;
      display: flex;
    }
  }
}

.upload-result-tabs {
  ::v-deep.el-tabs__content {
    height: 150px;
    overflow-y: auto;
  }
}

.upload-list-item {
  justify-content: space-between;
}

.upload-list-item .error-tips {
  p {
    width: 120px;
  }
}

.el-icon-warning-outline {
  color: #606266;
  margin-left: 6px;
}

.tips-image {
  width: 180px;
  height: auto;
}
</style>
