<template>
  <a-modal
    title="数据导入"
    :visible="open"
    :zIndex="1001"
    :confirm-loading="uploading"
    @cancel="importExcelHandleCancel"
  >
    <a-spin tip="上传中..." :spinning="uploading">
      <a-upload-dragger
        name="file"
        accept=".xlsx, .xls"
        :file-list="fileList"
        :multiple="false"
        :remove="handleRemove"
        :before-upload="beforeUpload"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text">
          请将文件拖拽到此处上传
        </p>
        <p class="ant-upload-hint">
          支持单个上传，也可以点击后选择文件上传
        </p>
      </a-upload-dragger>
      <a-divider v-if="$slots.importExcelSlot"/>
      <a-collapse :bordered="false" v-if="$slots.importExcelSlot">
        <a-collapse-panel key="0" header="查看导入说明">
          <slot name="importExcelSlot"></slot>
        </a-collapse-panel>
      </a-collapse>
    </a-spin>
    <template slot="footer">
      <a-row>
        <a-button type="link" icon="download" v-if="queryParamsName !== 'none'" @click="importTemplate">
          下载导入模板
        </a-button>
        <a-button key="back" @click="importExcelHandleCancel">
          取消
        </a-button>
        <a-button key="submit" type="primary" :loading="uploading" @click="importExcelHandleChange">
          导入
        </a-button>
      </a-row>
    </template>
  </a-modal>
</template>

<script>

import { importData, downloadImportExcel } from '@vue2-client/services/api/common'
import { mapState } from 'vuex'

export default {
  name: 'XImportExcel',
  props: {
    serviceName: {
      type: String,
      default: undefined
    },
    env: {
      type: String,
      default: 'prod'
    },
    queryParamsName: {
      type: String,
      default: 'none'
    },
    // 业务名称
    title: {
      type: String,
      default: ''
    },
    extraData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  components: {
  },
  data () {
    return {
      open: false,
      uploadStatus: '',
      fileList: [],
      // 是否禁用上传
      uploading: false
    }
  },
  filters: {
  },
  created () {
  },
  computed: {
    ...mapState('account', { currUser: 'user' })
  },
  watch: {
  },
  methods: {
    /** 导入excel窗体关闭 */
    importExcelHandleCancel (e) {
      this.open = false
      this.fileList = []
      // 关闭后刷新列表
      this.$emit('ok')
    },
    /** 下载模板操作 */
    importTemplate () {
      downloadImportExcel({
        queryParamsName: this.queryParamsName
      }, this.serviceName, this.env === 'dev').then(res => {
        if (!res || !res.value) {
          this.$message.warn('导入模板不存在，请检查配置')
           return
        }
        window.open(res.value)
      })
    },
    /** 导入excel窗体开启 */
    importExcelHandleOpen (e) {
      this.open = true
    },
    beforeUpload (file) {
      this.fileList = [file]
      return false
    },
    /** 导入excel */
    importExcelHandleChange () {
      const { fileList } = this
      const formData = new FormData()
      if (!fileList[0]) {
        this.$message.warn('请选择需要上传的文件')
        return
      }
      this.uploading = true
      const userData = {
        currUserName: this.currUser.name,
        currUserId: this.currUser.id,
        orgId: this.currUser.orgid,
        orgName: this.currUser.orgs,
        depId: this.currUser.depids,
        depName: this.currUser.deps
      }
      formData.append('file', fileList[0])
      formData.append('queryParamsName', this.queryParamsName)
      formData.append('userData', JSON.stringify(userData))
      // __EXPORT_TASK_NAME__ 异步导入任务名称
      Object.assign(this.extraData, { __EXPORT_TASK_NAME__: this.title || '导出' })
      formData.append('otherParams', JSON.stringify(this.extraData))
      importData(formData, this.serviceName, this.env === 'dev').then(res => {
        this.fileList = []
        const msg = res.msg || '导入成功'
        if (res?.successLen && !res?.msg) {
          this.$message.success(`${msg}，成功导入${res.successLen}条数据`)
        } else {
          this.$message.success(msg)
        }
        this.open = false
        this.$emit('ok', res)
      }).catch(e => {
        this.$message.error(e)
      }).finally(() => {
        this.uploading = false
      })
    },
    handleRemove () {
      this.fileList = []
      this.uploading = false
    }
  }
}
</script>
