<template>
  <el-dialog
    :title="'导入'"
    :visible.sync="dialog"
    width="500px"
    append-to-body
    @close="cancelForm"
  >
    <div class="demo-drawer__content" style="padding: 0 20px">
      <el-form
        ref="formRef"
        :model="form"
        label-position="left"
        label-width="50px"
        :rules="rules"
        hide-required-asterisk
      >
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="日期" prop="reportYear">
              <el-date-picker
                v-model="form.reportYear"
                type="year"
                format="yyyy"
                value-format="yyyy"
                placeholder="选择年"
                :clearable="false"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文件">
              <el-upload
                class="upload-demo"
                ref="upload"
                accept=".xls,.xlsx"
                :limit="1"
                :multiple="false"
                action="#"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-change="handleChange"
                :before-upload="beforeUpload"
                :http-request="uploadHttpRequest"
                :auto-upload="false"
              >
                <el-button slot="trigger" size="small" plain type="primary"
                  >选取文件</el-button
                >
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelForm">取 消 </el-button>
      <el-button type="primary" @click="handleClose" :loading="loading">{{
        loading ? "提交中 ..." : "确 定"
      }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { importF } from "@/api/powerdistribution/power-outage-control";
export default {
  data() {
    return {
      form: {
        reportYear: `${new Date().getFullYear()}`,
      },
      loading: false,
      dialog: false,
      fileList: [],
      rules: {
        reportYear: [
          { required: true, message: "请选择日期", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    openModel() {
      this.dialog = true;
    },
    // 文件上传之前的操作
    beforeUpload(file) {
      // 文件类型
      const isType = file.type === "application/vnd.ms-excel";
      const isTypeComputer =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const fileType = isType || isTypeComputer;
      if (!fileType) {
        console.log("上传文件只能是xls/xlsx格式！");
      }

      // 文件大小限制为20M
      const fileLimit = file.size / 1024 / 1024 < 20;
      if (!fileLimit) {
        console.log("上传文件大小不超过20M！");
      }
      // 返回判断条件,false停止上传
      return fileType && fileLimit;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList = [];
    },
    handlePreview(file) {
      console.log(file);
    },
    // 自定义上传方法，param是默认参数，可以取得file文件信息，具体信息如下图
    uploadHttpRequest(param) {
      this.loading = true;
      let data = new FormData();
      data.append("file", param.file);
      data.append("reportYear", this.form.reportYear);
      importF(data)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("导入成功");
            this.dialog = false;
            this.$emit("refresh");
          } else {
            this.$message.error("导入失败" || res.msg);
          }
        })
        .catch((err) => {
          console.log(err);
          this.$refs.upload.clearFiles();
          this.fileList = [];
        });
      this.loading = false;
    },
    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.$refs.formRef.validate(async (v) => {
        if (!v) return;
        if (!this.fileList.length) {
          this.$message.warning("请选择文件");
          return;
        }
        this.$refs.upload.submit();
      });
    },
    cancelForm() {
      this.form = {
        reportYear: `${new Date().getFullYear()}`,
      };
      this.fileList = [];
      this.loading = false;
      this.dialog = false;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-drawer.ttb,
  .el-drawer.btt {
    height: 90% !important;
  }
}
</style>
