<template>
  <div>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" :before-close="handleBeforeClose"  append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :data="getUploadData()"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div
            class="order-type-radio"
            v-if="showTrdcCheckbox && dict.type.inbound_outbound_type.length"
            style="margin-bottom: 8px; text-align: left; padding-left: 20px;"
          >
            <el-radio-group v-model="upload.orderType">
              <el-radio
                v-for="item in dict.type.inbound_outbound_type"
                :key="item.value"
                :label="item.value"
                style="margin-right: 20px;"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </div>
          <!-- 加载中提示 -->
          <div
            v-else-if="showTrdcCheckbox && !dict.type.inbound_outbound_type.length"
            style="margin-bottom: 8px; text-align: left; padding-left: 20px;"
          >
            <i class="el-icon-loading" style="font-size: 14px;"></i> 加载入库类型...
          </div>
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :disabled="upload.isUploading">确 定</el-button>
        <el-button @click="upload.open = false" :disabled="upload.isUploading">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth"

export default {
  name: "ImportExcel",
  dicts: ['inbound_outbound_type'],
  props: {
    // 导入标题
    title: {
      type: String,
      default: "导入数据"
    },
    // 导入接口地址
    importUrl: {
      type: String,
      required: true
    },
    // 模板下载地址
    templateUrl: {
      type: String,
      required: true
    },
    // 模板文件名前缀
    templateName: {
      type: String,
      default: "template"
    },
    showTrdcCheckbox: {
      type: Boolean,
      default: false
    },
     // 新增：是否要求orderType为必传项
    orderTypeRequired: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: "",
        // 入库类型字段
        orderType: ""
      }
    }
  },
  watch: {
    // 监听orderType变化，实时传递给父组件
    "upload.orderType": {
      handler(newVal) {
        this.$emit("orderTypeChange", newVal)
      },
      immediate: true
    },
    // 监听弹窗打开，设置单选框默认值
    "upload.open"(val) {
      if (val && this.showTrdcCheckbox) {
        // 取字典第一个作为默认值
        const defaultType = this.dict.type.inbound_outbound_type[0]?.value || ""
        this.upload.orderType = defaultType
      }
    }
  },
  methods: {
    /** 打开导入对话框 */
    show() {
      this.upload.title = this.title
      this.upload.url = process.env.VUE_APP_BASE_API + this.importUrl
      this.upload.open = true
      // 恢复原有重置
      this.upload.updateSupport = 0
      // 重置入库类型
      this.upload.orderType = this.showTrdcCheckbox
        ? (this.dict.type.inbound_outbound_type[0]?.value || "")
        : ""
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(this.templateUrl, {orderType: this.upload.orderType}, `${this.templateName}_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log(response)
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      )
      // 触发父组件的成功回调
      this.$emit("success", {
        orderType: this.upload.orderType,
        updateSupport: this.upload.updateSupport
      })
    },
    // 返回要追加到FormData的参数
    getUploadData() {
      const data = {
        updateSupport: this.upload.updateSupport
      };
      // 如果显示单选框，追加orderType到FormData
      if (this.showTrdcCheckbox) {
        data.orderType = this.upload.orderType;
      }
      return data;
    },
    // 提交上传文件
    submitFileForm() {
      this.upload.isUploading = true
      const file = this.$refs.upload.uploadFiles
      if (
        !file ||
        file.length === 0 ||
        (!file[0].name.toLowerCase().endsWith(".xls") &&
          !file[0].name.toLowerCase().endsWith(".xlsx"))
      ) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
        return
      }
      // 校验orderType（如果是必传项）
      if (this.showTrdcCheckbox && this.orderTypeRequired && !this.upload.orderType) {
        this.$modal.msgError("请选择入库/出库类型！")
        return
      }
      // 提交前通知父组件
      this.$emit("orderTypeChange", this.upload.orderType)
      // 提交上传
      this.$refs.upload.submit()
    },
    // 在 methods 中添加
    handleBeforeClose(done) {
      if (this.upload.isUploading) {
        this.$modal.msgWarning("正在上传中，请等待上传完成后再关闭！")
        return  // 停止关闭
      }
      done()  // 执行关闭
    }
  }
}
</script>

<style scoped>

</style>
