<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" style="padding-bottom: 30px;padding-top: 30px">

        <template>
          <a-form-item label="下载模板" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-button
              :ghost="true"
              type="primary"
              icon="download"
              size="small"
              @click="handleExportXls('用户模板')">
              下载
            </a-button>
          </a-form-item>
        </template>


        <a-form-item label="上传文件" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload name="file" :showUploadList="showUploadList" :fileList="fileList" :multiple="false" :headers="headers" :action="importExcelUrl()"  @change="handleImportExcel2">
          <a-button><a-icon type="upload"/>导入用户</a-button>
          </a-upload>
        </a-form-item>
        <template v-if="type==2">
          <a-form-item label="上传成功" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <p>上传成功</p>
          </a-form-item>
        </template>

        <template v-if="type==1">
          <a-form-item label="上传失败" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a @click="delrequire(dataError)">查看错误项</a>
          </a-form-item>
        </template>




      </a-form>
    </a-spin>
    <hlg-user-export-error-modal ref="modalSelectRequireForm"></hlg-user-export-error-modal>
  </a-modal>

</template>

<script>
  import { httpAction } from '@/api/manage'
  import JDate from '@/components/jeecg/JDate'
  import JUpload from '@/components/jeecg/JUpload'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { getAction, deleteAction, putAction, postAction,downFile } from '@/api/manage'
  import HlgUserExportErrorModal from './HlgUserExportErrorModal'

  const tyemplateGeneration = (params) => putAction('/hlguser/hlgUser/tyemplateGeneration', params)

  const FILE_TYPE_ALL = "all"
  const FILE_TYPE_PDF = 'pdf'
  const uidGenerator = () => {
    return '-' + parseInt(Math.random() * 10000 + 1, 10)
  }
  const getFileName = (path) => {
    if (path.lastIndexOf('\\') >= 0) {
      let reg = new RegExp('\\\\', 'g')
      path = path.replace(reg, '/')
    }
    return path.substring(path.lastIndexOf('/') + 1)
  }

  export default {
    name: 'HlgUserExportModal',
    components: {
      HlgUserExportErrorModal,
      JDate,
      JUpload,
      JSelectDepart,
      JDictSelectTag
    },
    data() {
      return {
        dataError:"",
        uploadAction: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
        urlDownload: window._CONFIG['domianURL'] + '/hpSys/common/ossDownload',
        headers: {},
        fileList: [],
        type:0,
        showUploadList:false,
        form: this.$form.createForm(this),
        title: '操作',
        width: 600,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        defaultFileList:[],
        accept:'.pdf',
        confirmLoading: false,
        validatorRules: {

        },
        url: {
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          edit: '/hlguser/hlgUser/edit',
          importExcelUrl: "/hlguser/hlgUser/importExcel",
          exportXlsUrl:"/hlguser/hlgUser/tyemplateGeneration"
        }

      }
    },

    watch: {

    },
    created() {
      this.type=0
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }

    },
    methods: {
      add() {
        this.edit({})
      },
      edit(record) {
        this.type=0
        this.model={}
        this.fileList=[]
        this.form.resetFields()
        this.model = record
        console.log(666666,record)
        this.visible = true
        this.showUploadList = false;
      },
      close() {
        this.$emit('ok')
        this.visible = false
      },
      handleOk() {
        this.$emit('ok')
        this.visible = false
      },
      handleCancel() {
        this.close()
      },
      popupCallback(row) {

      },

      importExcelUrl(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },

      /* 导入 */
      handleImportExcel2(info){
        this.showUploadList = true;
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        let fileList = info.fileList
        if (info.file.status === 'done') {
          if(info.file.response.success){
            this.type=2
            this.$message.success(`${info.file.name} 文件上传成功`);
          } else {
            this.type=1
            this.dataError=info.file.response.message
            console.log(this.dataError)
            this.$message.error(`导入失败`);
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`文件上传失败: ${info.file.msg} `);
        }
        this.fileList = fileList
      },

      delrequire(dataError){
        this.$refs.modalSelectRequireForm.edit(dataError)
        this.$refs.modalSelectRequireForm.title = '错误项'
        this.$refs.modalSelectRequireForm.disableSubmit = false
      },

      handleExportXls(fileName){
        if(!fileName || typeof fileName != "string"){
          fileName = "导出文件"
        }
        let param = {...this.queryParam};
        if(this.selectedRowKeys && this.selectedRowKeys.length>0){
          param['selections'] = this.selectedRowKeys.join(",")
        }
        console.log("导出参数",param)
        downFile(this.url.exportXlsUrl,param).then((data)=>{
          console.log("导出参数",param)

          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data]), fileName+'.xls')
          }else{
            let url = window.URL.createObjectURL(new Blob([data]))
            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>