<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="下载模板">
        <el-button icon="Bottom" type="success" round @click="downloadTemplate"
          >下载模板</el-button
        >
      </el-form-item>
      <el-form-item style="margin-top: -10px">
        <div style="color: #666666">请按数据模板的格式准备要导入的数据!</div>
      </el-form-item>
      <el-form-item label="上传文件">
        <el-upload
          ref="uploadRef"
          :show-file-list="true"
          :limit="1"
          :multiple="false"
          :action="action"
          :headers="headers"
          :data="uploadData"
          :on-success="onSuccess"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
        >
          <el-button icon="top" round type="primary">选择文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <div class="bottom-btn">
      <el-button
        style="width: 90px"
        @click="$emits('update:isImportDialog', false)"
        >取消</el-button
      >
      <el-button style="width: 90px" type="primary" @click="startImport"
        >开始导入</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import templateHooks from "@/Hooks/templateHooks.js";

const props = defineProps({
  templateUrl: String,
  action: String,
  districtId: Number || String,
  isImportDialog: Boolean,
});
let headers = ref({});
let uploadData = ref({});
let fileId = ref();
const $emits = defineEmits(["update:isImportDialog", "importSubmit"]);
const beforeUpload = (e) => {
  uploadData.value.districtId = props.districtId;
  headers.value = $common.getSignature();
  return new Promise((resolve) => {
    resolve(e);
  });
};

const downloadTemplate = () => {
  window.open(props.templateUrl, "blank");
};

const onSuccess = (res) => {
  fileId.value = "";
  if (res.code == 0) {
    fileId.value = res.data.fileId;
  } else {
    $message.error(res.err);
  }
};
const handleRemove = () => {
  fileId.value = "";
};
// 开始导入
const startImport = () => {
  if (!fileId.value) {
    $message.error("请上传正确格式的文件!");
    return;
  }
  if (!props.districtId) {
    $message.error("请选择站点后再进行导入!");
    return;
  }
  let uploadPar = {
    fileId: fileId.value,
    districtId: props.districtId,
  };
  $emits("importSubmit", uploadPar);
};
const { $message, $common } = templateHooks();
</script>

<style lang="scss" scoped>
.bottom-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 40px;
  margin-bottom: -20px;
}
</style>
