<template>
  <div class="table-form">
    <Form :model="entity" ref="form" :rules="rules" :label-width="labelWidth">
      <Row :gutter="10" >
        <Col span="24">
          <FormItem label="Excel文件" prop="file" >
            <Upload ref="upload" action="uploadUrl" :show-upload-list="true"  :before-upload="handleUpload"   :on-success="handleSuccess">
                <Button icon="ios-cloud-upload-outline">选择文件</Button>{{file?file.name:""}}
            </Upload>
          </FormItem>
        </Col>
      </Row>
      <Row class="buttonDiv">
        <Button :loading="loading"
          @click="submitForm"
          type="primary"
        >确&nbsp;&nbsp;定</Button>
        <Button @click="cancel">关&nbsp;&nbsp;闭</Button>
      </Row>
    </Form>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Emit } from "vue-property-decorator";

@Component
export default class DeviceInstanceImport extends Vue {
  file: any = null;
  private entity: any ={
      name : ""
  };
 
  labelWidth: number = 120;
  rules : any={};
  uploadUrl : String = this.$msPrefix.psem +"/api/v1/psem/upload/instance";
   loading : boolean = false;

  @Emit("close-modal") close() {}
  cancel() {
    (this.$refs["form"] as any).resetFields();
    (this.$refs.upload as any).clearFiles()
    this.close();
  }
 
 handleUpload(file){
    if(!(file.name.endsWith(".xls")||file.name.endsWith(".xlsx"))){
        this.$tools.message('warning','文件 ' + file.name + ' 是不被允许的格式, 请上传Excel文件')
    }else{
        this.file=file;
    }
    return false;
}

handleSuccess(res, file){
    setTimeout(()=>{
      (this.$refs.upload as any).clearFiles()
    },500);
    if(res.code==-1){
      this.$tools.message('error',res.msg);
    }else{
      //this.getCarouselData()
    }
  }
  @Emit("get-data") getData(){}
  save() {
    let config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };
    let formData = new FormData();
    Object.keys(this.entity).forEach(item => {
      formData.append(item, this.entity[item]);
    });
    formData.append("file", this.file);


      this.getApiData('post',this.uploadUrl,formData,res=>{
        this.loading=!1;
        this.file=null;
        this.$tools.message('success',"导入成功！");
          this.getData();
          this.cancel();
      },err=>{
        this.loading=!1;
        this.file=null;
         //this.$tools.message('error',"导入失败！");
      },config)
  }
  /*提交*/
  submitForm() {
    (this.$refs["form"] as any).validate(valid => {
      if (valid) {
          if(this.file==null){
            this.$tools.message('info',"请上传Excel文件！")
          }else{
           if(!this.loading){
                this.loading=!0;
                this.save()
            }
          }
      } else {
         this.$tools.message('info',"请完善必填项！")
      }
    });
  }
}
</script>



