<template>
  <ych-modal
    :fullscreen="dialogSize === 'full'"
    :size="dialogSize === 'default' ? 'middle' : dialogSize"
    :title="title"
    :visible="visible"
    :destroyOnClose="true"
    @cancel="handleCancel">
    <a-upload-dragger
      name="file"
      :headers="tokenHeader"
      :multiple="false"
      :showUploadList="false"
      :action="importXlsUrl + '&boKey=' + objectCode"
      @change="handleImportXls"
    >
      <p class="ant-upload-drag-icon">
        <a-icon type="inbox"/>
      </p>
      <p class="ant-upload-text">
        {{ $locale('m.eform.formDesign.label.dian-ji-huo-tuo-zhuai-wen-jian-dao-ru') }} </p>
      <p class="ant-upload-hint">
        {{ $locale('m.eform.formDesign.label.import_button_tip') }} </p>
    </a-upload-dragger>

    <template slot="footer">
      <a-button type="primary" key="file-excel" @click="handleExportTemplate">{{ $locale('m.eform.formDesign.label.xia-zai-dao-ru-mo-ban') }}</a-button>
      <a-button key="close" @click="handleCancel">{{ $locale('m.common.button.close') }}</a-button>
    </template>
  </ych-modal>
</template>

<script>

  import {downFile} from '../../utils/manage'
  import YchConstant from "../../utils/YchConstant";
  import {handleCreateFunc, handleExecFunc} from '../../utils/actions'
  import TokenStorageUtil from "../../utils/TokenStorageUtil";
  import locleUtil from "../../utils/LocleUtil";

  export default {
    name: 'ImportDialog',
    components: {},
    props: {
      viewCode: String,
      viewName: String
    },
    data() {
      return {
        title: this.$locale('m.common.button.import'),
        visible: false,
        objectCode: null,
        afterScript:null,
        tokenHeader: {'X-Access-Token': TokenStorageUtil.get()},
        url: {
          importXlsUrl: YchConstant.PREFIX_EFORM + '/engine/viewEngine/importXls',
          exportTemplateUrl: YchConstant.PREFIX_EFORM + '/engine/viewEngine/exportTemplate'
        },
        dialogSize: 'default'
      }
    },
    computed: {
      importXlsUrl: function () {
        const prefix = window.location.origin;
        return `${prefix}${this.url.importXlsUrl}?viewCode=` + this.viewCode
      }
    },
    methods: {
      $locale(params){
        return locleUtil.getLocale(params)
      },
      handleCancel() {
        this.visible = false
      },
      handleImportXls(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList)
        }
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            // this.$message.success(`${info.file.name} 文件上传成功`);
            if (info.file.response.code === 201) {
              let {message, result: {msg, fileUrl, fileName}} = info.file.response
              let href = bootConfig[process.env.NODE_ENV].VUE_APP_API + fileUrl
              this.$warning({
                  title: message,
              //     content: (
              //       < div >
              //       < span > {msg} < /span><br/ >
              //       < span > {this.$locale('m.eform.formDesign.label.ju-ti-xiang-qing-qing')} < a href = {href} target = '_blank' download = {fileName} > { this.$locale('m.eform.formDesign.label.dian-ji-xia-zai') } < /a></span >
              //   < /div>
              // )
            })
            } else {
              this.$message.success(info.file.response.message || `${info.file.name} `+this.$locale('m.common.tip.file_upload_sucess') )
            }
            this.$emit("loadData")
            this.handleCancel();
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}.`)
          }

          if (this.afterScript) {
            const func = handleCreateFunc(this.afterScript, this)
            handleExecFunc(func, { info })
          }
        } else if (info.file.status === 'error') {
          this.$message.error(this.$locale('m.common.tip.file_upload_error') +`: ${info.file.msg} `)
        }
      },
      handleExportTemplate() {
        const fileName = this.viewName + this.$locale('m.eform.formDesign.label.dao-ru-mo-ban')

        downFile(this.url.exportTemplateUrl + '?viewCode=' + this.viewCode, {}, "POST").then((data) => {
          if (!data) {
            this.$message.warning(this.$locale('m.eform.formDesign.label.wen-jian-xia-zai-shi-bai'))
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], {type: 'application/vnd.ms-excel'}), fileName + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], {type: 'application/vnd.ms-excel'}))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
      }
    },
  }
</script>


