<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="550px"
    center
    append-to-body
    @open="handleDialogOpen"
    @close="handleDialogClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    custom-class="import-dialog-wrapper"
  >
    <!-- 全屏Loading遮罩层 -->
    <div v-show="isUploading" class="import-loading-overlay">
      <i class="el-icon-loading"></i>
      <p>正在导入中,请稍候...</p>
    </div>

    <el-form :model="formData" label-position="top" size="medium">
      <!-- 导入类型 -->
      <el-form-item label="导入类型">
        <el-radio-group v-model="formData.importType" @change="handleImportTypeChange" style="width: 100%">
          <el-radio label="person" border>个人中介</el-radio>
          <el-radio label="entity" border>机构中介</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 文件上传 -->
      <el-form-item label="选择文件">
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="headers"
          :action="uploadUrl"
          :disabled="isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            仅支持 .xls 和 .xlsx 格式,文件大小不超过 10MB
          </div>
        </el-upload>
      </el-form-item>

      <!-- 其他选项 -->
      <el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-checkbox v-model="formData.updateSupport" :disabled="isUploading">
              更新已存在的数据
            </el-checkbox>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-link type="primary" :underline="false" @click="handleDownloadTemplate">
              <i class="el-icon-download"></i>
              下载导入模板
            </el-link>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        icon="el-icon-upload2"
        :loading="isUploading"
        :disabled="!isFileSelected"
        @click="handleSubmit"
      >
        {{ isUploading ? '导入中...' : '开始导入' }}
      </el-button>
      <el-button icon="el-icon-close" @click="visible = false" :disabled="isUploading">
        取 消
      </el-button>
    </div>
  </el-dialog>
</template>

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

export default {
  name: "ImportDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: "数据导入"
    }
  },
  data() {
    return {
      formData: {
        importType: "person",
        updateSupport: 0
      },
      headers: { Authorization: "Bearer " + getToken() },
      isUploading: false,
      isFileSelected: false
    };
  },
  computed: {
    uploadUrl() {
      const baseUrl = process.env.VUE_APP_BASE_API;
      const updateSupport = this.formData.updateSupport ? 1 : 0;
      if (this.formData.importType === 'person') {
        return `${baseUrl}/ccdi/intermediary/importPersonData?updateSupport=${updateSupport}`;
      } else {
        return `${baseUrl}/ccdi/intermediary/importEntityData?updateSupport=${updateSupport}`;
      }
    }
  },
  watch: {
    visible(val) {
      this.$emit("update:visible", val);
    }
  },
  methods: {
    handleDialogOpen() {
      this.isFileSelected = false;
    },
    handleDialogClose() {
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
      this.isFileSelected = false;
      this.$emit("close");
    },
    handleImportTypeChange() {
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
      this.isFileSelected = false;
    },
    handleDownloadTemplate() {
      if (this.formData.importType === 'person') {
        this.download('ccdi/intermediary/importPersonTemplate', {}, `个人中介黑名单模板_${new Date().getTime()}.xlsx`);
      } else {
        this.download('ccdi/intermediary/importEntityTemplate', {}, `机构中介黑名单模板_${new Date().getTime()}.xlsx`);
      }
    },
    handleFileUploadProgress() {
      this.isUploading = true;
    },
    handleFileChange(file, fileList) {
      this.isFileSelected = fileList.length > 0;
    },
    handleFileRemove(file, fileList) {
      this.isFileSelected = fileList.length > 0;
    },
    handleFileSuccess(response) {
      this.isUploading = false;
      this.visible = false;
      this.$emit("success");

      // 解析后端返回的消息，只展示错误部分
      let displayMessage = response.msg;

      // 如果消息包含"恭喜您，数据已全部导入成功"，说明全部成功，不展示详细列表
      if (displayMessage.includes('恭喜您，数据已全部导入成功')) {
        // 全部成功，使用简洁提示
        displayMessage = '导入成功！';
      }
      // 如果消息包含"很抱歉，导入失败"，说明有错误，只展示错误部分
      else if (displayMessage.includes('很抱歉，导入失败')) {
        // 只保留错误部分，移除成功统计信息
        const lines = displayMessage.split('<br/><br/>');
        displayMessage = lines[0]; // 只取错误部分
      }

      this.$msgbox({
        title: '导入结果',
        dangerouslyUseHTMLString: true,
        message: `<div style="overflow-y: auto; max-height: 60vh; padding-right: 10px; line-height: 1.6;">${displayMessage}</div>`,
        confirmButtonText: '确定',
        customClass: 'import-result-dialog'
      });
      this.$refs.upload.clearFiles();
    },
    handleFileError() {
      this.isUploading = false;
      this.$modal.msgError("导入失败,请检查文件格式是否正确");
      this.$refs.upload.clearFiles();
    },
    handleSubmit() {
      this.$refs.upload.submit();
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-form-item {
    margin-bottom: 22px;
  }

  .el-radio-group {
    display: flex;

    .el-radio {
      flex: 1;
      text-align: center;
      margin-right: 0;

      &:first-child {
        .el-radio__label {
          border-top-right-radius: 0;
          border-bottom-right-radius: 0;
        }
      }

      &:last-child {
        .el-radio__label {
          border-top-left-radius: 0;
          border-bottom-left-radius: 0;
        }
      }

      &.is-bordered {
        padding: 10px 0;
        height: auto;
      }
    }
  }

  .el-upload {
    width: 100%;

    .el-upload-dragger {
      width: 100% !important;
      height: 140px;
      box-sizing: border-box;

      .el-icon-upload {
        font-size: 50px;
        color: #409EFF;
        margin: 15px 0 10px;
      }

      .el-upload__text {
        font-size: 14px;
        color: #606266;

        em {
          color: #409EFF;
          font-style: normal;
        }
      }
    }
  }

  .el-upload__tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
    line-height: 1.5;
  }
}

.dialog-footer {
  text-align: center;
  padding: 5px 0 0;

  .el-button {
    min-width: 110px;
    margin: 0 8px;
  }
}

.import-loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10000;

  .el-icon-loading {
    font-size: 48px;
    color: #409EFF;
    animation: rotating 2s linear infinite;
  }

  p {
    margin-top: 15px;
    font-size: 14px;
    color: #606266;
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
