<template>
  <el-dialog
    v-loading="defaultLoading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    :visible.sync="dialogVisible"
    :title="title"
    :before-close="handleCloses"
    :width="
      title === '异常详情' ? '750px' : title === '异常描述' ? '1120px' : '500px'
    "
  >
    <!-- 根据 emptyFlag 和 title 显示不同的内容 -->
    <!-- <slot v-if="emptyFlag" name="tableEl"></slot> -->
    <abnormal-detail
      v-if="title === '异常描述'"
      ref="abnormalDetailRef"
      :batchCode="rowInfo.batchCode"
    ></abnormal-detail>
    <div class="dialogBox" v-if="title === '异常详情'">
      <el-card shadow="always">
        <i class="el-icon-warning"></i> {{ errorInfo }}
      </el-card>
    </div>
    <div v-if="title === '上传报告'">
      <el-upload
        class="upload-demo"
        action=""
        multiple
        :http-request="customUpload"
        :on-remove="handleRemove"
        :on-change="handleChange"
        :before-upload="checkFileType"
        :show-file-list="false"
        :file-list="fileList"
      >
        <el-button size="small" type="primary">选择文件</el-button>
        <!-- <div slot="tip" class="el-upload__tip">只能上传pdf文件</div> -->
      </el-upload>
      <div>
        <span style="color: red">展示文件列表区域(双击修改文件名称)：</span>
        <ul style="margin-top: 10px">
          <li v-for="(file, index) in fileList" :key="index">
            <el-select
              size="small"
              v-model="file.reportType"
              placeholder="请选择文件类型"
            >
              <el-option
                v-for="item in rportTypeList"
                :key="item.reportType"
                :label="item.reportTypeName"
                :value="item.reportType"
              >
              </el-option>
            </el-select>
            <!-- 双击切换编辑状态 -->
            <span v-if="editIndex !== index" @dblclick="editFileName(index)">
              {{ file.name }}
            </span>

            <!-- 输入框模式 -->
            <el-input
              style="width: 150px"
              v-if="editIndex === index"
              placeholder="请输入文件名"
              size="small"
              v-model="file.name"
              @blur="validateAndSaveFileName(file)"
              @keydown.enter="validateAndSaveFileName(file)"
              clearable
            ></el-input>

            <!-- 移除文件按钮 -->
            <el-button size="mini" type="text" @click="removeFile(index)">
              移除
            </el-button>
          </li>
        </ul>
      </div>
    </div>

    <div
      slot="footer"
      v-if="title === '异常详情' || title === '上传报告'"
      class="dialog-footer"
    >
      <el-button @click="handleClose">取消</el-button>
      <el-button v-if="title === '上传报告'" @click="handleUpload">
        确定上传
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import AbnormalDetail from "./abnormalDetail.vue";
import { uploadFile, saveReportBatch, getRportType } from "@/api/performance";
export default {
  components: {
    AbnormalDetail,
  },
  props: {
    title: String,
    visible: Boolean, // 控制对话框显示隐藏
    errorInfo: String,
    rowInfo: {
      type: Object,
      default: () => ({}), // Set default value as an empty object
    },
  },
  data() {
    return {
      defaultLoading: false,
      dialogVisible: this.visible,
      emptyFlag: false,
      batchCode: "",
      input: "",
      fileList: [], // 文件列表
      editIndex: -1, // 当前处于编辑状态的文件索引
      rportTypeList: [], //文件类型
    };
  },
  created() {
    this.getfileRportType();
  },
  watch: {
    visible(newVal) {
      this.dialogVisible = newVal;
      this.checkEmptyFlag();
    },
    rowInfo: {
      handler(newVal, oldVal) {
        if (newVal && newVal.batchCode) {
          this.batchCode = newVal.batchCode;
        } else {
          console.warn("rowInfo or batchCode is undefined");
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    async getfileRportType() {
      try {
        const res = await getRportType();

        this.rportTypeList = res.data;
      } catch (err) {
        console.error(err);
      }
    },
    async handleUpload() {
      if (this.fileList.length > 0) {
        try {
          this.defaultLoading = true;
          const results = await this.uploadFiles();
          const fileDatas = results.map((item, ind) => {
            return {
              reportName: this.fileList[ind].name,
              reportAddr: item.data,
              batchCode: this.batchCode,
              reportType: this.fileList[ind].reportType
                ? this.fileList[ind].reportType
                : null,
            };
          });
          const reportTypes = new Set();
          let hasDuplicates = false;

          fileDatas.forEach((item) => {
            if (reportTypes.has(item.reportType)) {
              hasDuplicates = true;
            } else {
              reportTypes.add(item.reportType);
            }
          });
          const nullFileDatas = fileDatas.filter(
            (item) => item.reportType === null
          );
          if (nullFileDatas.length > 0) {
            this.defaultLoading = false;
            this.$message.warning("请检查是否选择了文件类型");
          } else {
            if (hasDuplicates) {
              this.defaultLoading = false;
              this.$message.warning("不可选择的相同文件类型，请重新选择！");
            } else {
              const res = await saveReportBatch(fileDatas);
              if (res.code === 200) {
                this.$message.success("保存成功");
                this.fileList = [];
                this.$emit("getTableList");
                this.handleClose();
              } else {
                this.$message.error(res.msg + "上传失败请重新上传");
              }
              this.defaultLoading = false;
            }
          }
        } catch (err) {
          this.defaultLoading = false;
          console.error("error");
        }
      } else {
        this.defaultLoading = false;
        this.$message.warning("请选择上传文件");
      }
    },
    //调用单个上传接口
    uploadFiles() {
      return Promise.all(
        this.fileList.map((item) => {
          const form = new FormData();
          form.append("file", item.raw);
          return uploadFile(form);
        })
      );
    },
    // 进入编辑模式
    editFileName(index) {
      this.editIndex = index;
    },
    //判断上传文件类型
    checkFileType(file) {
      const isPdf =
        file.type === "application/pdf" || file.name.endsWith(".pdf");
      if (!isPdf) {
        this.$message.error("只能上传PDF文件");
      }
      return isPdf;
    },
    //判断修改文件名称是否以.pdf 后缀
    validateAndSaveFileName(file) {
      if (file.name.trim().endsWith(".pdf")) {
        this.saveFileName(file);
      } else {
        this.$message.error("文件名必须以 .pdf 结尾");
      }
    },
    // 保存文件名并退出编辑模式
    saveFileName() {
      this.editIndex = -1; // 退出编辑模式
    },
    removeFile(index) {
      // const fileToRemove = this.fileList[index];
      this.fileList.splice(index, 1);
    },
    // 自定义上传方法
    customUpload(file) {
      const formData = new FormData();
      formData.append("file", file);
      // 使用 axios 自定义上传逻辑
    },
    // 移除文件时的处理
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    // 文件变化时的处理
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleClose() {
      this.fileList = [];
      this.$emit("confirm");
    },
    handleCloses(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.fileList = [];
          this.$emit("confirm");
        })
        .catch((_) => {});
    },
    handleConfirm() {
      // 获取插槽内容并传递出去
      const slotContent = this.$slots.tableEl;
      this.$emit("confirm", slotContent);
    },
    checkEmptyFlag() {
      this.$nextTick(() => {
        if (this.$refs.abnormalDetailRef) {
          const tableData = this.$refs.abnormalDetailRef.tableData;
          this.emptyFlag = !tableData || tableData.length === 0;
        }
      });
    },
  },
};
</script>
<style scoped>
::v-deep .el-loading-spinner .path {
  stroke: #009688 !important;
}
</style>
