<template>
  <div class="drawer-content-wrapper" :class="{ 'no-pointer-events': showUploadAnimation || showSaveAnimation }">
    <!-- 文件上传动画 -->
    <div v-if="showUploadAnimation" class="global-upload-animation">
      <div class="animation-mask"></div>
      <div class="animation-content">
        <div class="spinner"></div>
        <div class="animation-text">{{ animationText }}</div>
        <div class="animation-subtext">正在处理文件，请稍候...</div>
      </div>
    </div>

    <!-- 保存动画 -->
    <div v-if="showSaveAnimation" class="global-upload-animation">
      <div class="animation-mask"></div>
      <div class="animation-content">
        <div class="spinner"></div>
        <div class="animation-text">数据上传中</div>
        <div class="animation-subtext">请稍后，正在保存数据...</div>
      </div>
    </div>

    <!-- 可滚动的内容区域 -->
    <div class="drawer-scrollable-content">
      <div class="content-body">
        <QualificationFormChild ref="qualificationFormChild" />
      </div>
    </div>

    <!-- 固定在底部的操作栏 -->
    <div class="action-footer">
      <el-button class="reset-btn" @click="$emit('cancel')" :disabled="showSaveAnimation">取消</el-button>
      <el-button class="search-btn" @click="handleSave()" :loading="showSaveAnimation">保存</el-button>
    </div>
  </div>
</template>

<script>
import { decryptWithSM4 } from '@/utils/sm'
import QualificationFormChild from './child/QualificationFormChild.vue'
import { addDataAPI, editDataAPI, getDetailDataAPI } from "@/api/enterpriseLibrary/qualification/qualification";

// 工具函数：安全获取数组（避免非数组类型导致的错误）
const safeGetArray = (value) => Array.isArray(value) ? value : []

export default {
  name: 'QualificationForm',
  components: { QualificationFormChild },
  props: {
    type: {
      type: String,
      default: 'add' // add:新增, edit:编辑
    },
    qualificationId: {
      type: String,
    },
    enterpriseId: {
      type: String,
    },
    drawerVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showUploadAnimation: false, // 上传动画控制
      showSaveAnimation: false,   // 保存动画控制
      animationText: '识别中',
      uploadQueue: 0
    }
  },
  methods: {
    // 保存表单（核心优化：完善文件处理逻辑）
    async handleSave() {
      if (this.showSaveAnimation) return;
      this.showSaveAnimation = true;

      try {
        // 1. 获取子组件表单数据（包含文件列表和删除列表）
        const formData = await this.$refs.qualificationFormChild.validate();
        formData.enterpriseId = this.enterpriseId || '0';
        formData.qualificationId = this.qualificationId || null;

        // 2. 组装完整的文件元数据（提取fileRes中的信息）
        const fileList = safeGetArray(formData.files);
        const completeFiles = fileList.map(file =>
          file.response?.fileRes ? {...file.response.fileRes} : null
        ).filter(Boolean)

        // 3. 处理删除文件列表
        const delFiles = [...new Set(safeGetArray(formData.delFileList))];

        // 4. 构建最终提交数据
        const submitData = {
          ...formData,
          files: completeFiles, // 替换为完整文件元数据
          delFiles: delFiles,   // 传递待删除文件路径（去重后）
          delFileList: undefined // 移除临时字段
        };

        // 5. 区分新增/编辑接口提交
        if (this.type === 'add') {
          await addDataAPI(submitData);
          this.$message.success('新增资质成功！'); // 新增成功提示
        } else {
          await editDataAPI(submitData);
          console.log('submitData',submitData)
          this.$message.success('编辑资质成功！'); // 编辑成功提示
        }

        this.$emit('save-success'); // 触发保存成功事件
      } catch (error) {
        this.$message.error(error.message || '请完善表单信息');
      } finally {
        this.showSaveAnimation = false;
      }
    },

    // 处理文件上传开始
    handleStartUpload(text) {
      this.animationText = text || '识别中';
      this.uploadQueue++;
      this.showUploadAnimation = true;
    },

    // 处理文件上传结束（支持批量上传场景）
    handleEndUpload() {
      if (this.uploadQueue > 0) this.uploadQueue--;
      if (this.uploadQueue === 0) this.showUploadAnimation = false;
    },

    // 加载编辑数据（优化：确保文件回显时包含完整路径）
    async loadQualificationData() {
      try {
        const validParams = {
          qualificationId: this.qualificationId || '0',
          enterpriseId: this.enterpriseId || '0'
        };
        const response = await getDetailDataAPI(validParams);
        const qualificationData = response.data || {};

        // 关键：确保文件列表包含完整路径信息（适配后端字段）
        if (Array.isArray(qualificationData.fileList)) {
          qualificationData.fileList = qualificationData.fileList.map(file => ({
            ...file,
            lsFilePath: file.lsFilePath || file.fileUrl || '', // 预览路径
            name: file.fileName || file.name || '', // 文件名
            status: 'success', // 标记为已上传状态
            businessType: 'qualification_certificate',
            // 补充上传组件所需的响应结构（用于删除时获取路径）
            response: {
              fileRes: {
                uploadPath: file.filePath || file.uploadPath || '',
                filePath: file.filePath || file.uploadPath || ''
              }
            }
          }));
        }

        // 传递处理后的完整数据给子表单
        this.$refs.qualificationFormChild.setFormData(qualificationData);
      } catch (error) {
        this.$message.error('加载资质信息失败：' + error.message);
      }
    },

    // 重置表单（供父组件调用）
    resetForm() {
      this.$refs.qualificationFormChild?.resetForm();
      this.showUploadAnimation = false;
      this.showSaveAnimation = false;
      this.uploadQueue = 0;
    }
  },

  watch: {
    drawerVisible: {
      handler(newVal) {
        // 条件：抽屉打开 + 编辑模式 + 有资质ID和企业ID
        if (newVal && this.type === 'edit' && this.qualificationId && this.enterpriseId) {
          this.loadQualificationData();
        }
      },
      immediate: true // 初始化时立即执行
    }
  },

  mounted() {
    // 监听文件上传事件（优化：先解绑再绑定，避免重复监听）
    this.$bus.$off('startUpload', this.handleStartUpload);
    this.$bus.$off('endUpload', this.handleEndUpload);
    this.$bus.$on('startUpload', this.handleStartUpload);
    this.$bus.$on('endUpload', this.handleEndUpload);
  },
  beforeDestroy() {
    // 移除事件监听，避免内存泄漏
    this.$bus.$off('startUpload', this.handleStartUpload);
    this.$bus.$off('endUpload', this.handleEndUpload);
  }
}
</script>

<style scoped lang="scss">
// 抽屉内容总容器（flex布局）
.drawer-content-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 24px;
  position: relative; // 用于定位动画元素
}

// 可滚动内容区域（占满剩余空间）
.drawer-scrollable-content {
  flex: 1;
  overflow-y: auto;
  padding-right: 12px; // 预留滚动条空间，避免内容被遮挡

  // 滚动条样式优化
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-track {
    background: #f5f5f5;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
    &:hover {
      background: #909399;
    }
  }
}

// 操作栏（固定在底部）
.action-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  margin-top: 16px;
  border-top: 1px solid #f5f5f5; // 添加分割线，区分内容和操作栏
  flex-shrink: 0; // 防止被压缩
}

.global-upload-animation {
  position: absolute; // 相对于drawer-content-wrapper定位
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: auto;

  .animation-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.6);
    backdrop-filter: blur(4px);
    transition: opacity 0.3s ease;
  }

  .animation-content {
    position: relative;
    z-index: 10000;
    text-align: center;
    background: linear-gradient(135deg, #ffffff 0%, #f8faff 100%);
    padding: 40px 50px;
    border-radius: 20px;
    box-shadow:
      0 10px 40px rgba(31, 114, 234, 0.15),
      0 0 0 1px rgba(31, 114, 234, 0.1);
    min-width: 280px;
    animation: slideInUp 0.3s ease-out;

    .spinner {
      width: 60px;
      height: 60px;
      border: 4px solid #f3f7ff;
      border-top: 4px solid #409EFF;
      border-radius: 50%;
      animation: spin 1.2s linear infinite;
      margin: 0 auto 20px;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        top: -4px;
        left: -4px;
        right: -4px;
        bottom: -4px;
        border: 4px solid transparent;
        border-top: 4px solid #66b1ff;
        border-radius: 50%;
        animation: spin 0.8s linear infinite reverse;
      }
    }

    .animation-text {
      font-size: 20px;
      font-weight: 600;
      color: #409EFF;
      margin-bottom: 8px;
      background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }

    .animation-subtext {
      font-size: 14px;
      color: #666;
      opacity: 0.8;
    }
  }
}

.content-body {
  padding-bottom: 20px; // 与底部操作栏保持间距
}

.content-row {
  margin: 0;
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
}

.form-pane {
  background: #fff;
  border-radius: 16px;
  min-height: 500px;
  padding: 20px;
  margin-bottom: 20px;
  flex: 1;
  min-width: 300px;
}

.search-btn {
  background: #409EFF;
  border-color: #409EFF;
  color: #fff;
  font-weight: 600;
  padding: 12px 24px;
  border-radius: 6px;
  box-shadow: 0px 4px 12px 0px rgba(64, 158, 255, 0.4);
  letter-spacing: 0.5px;
  font-size: 14px;
  transition: all 0.3s ease;

  &:hover {
    background: #66b1ff;
    border-color: #66b1ff;
    box-shadow: 0px 6px 16px 0px rgba(64, 158, 255, 0.5);
    transform: translateY(-1px);
  }

  &.is-loading {
    opacity: 0.8;
    pointer-events: none;
  }
}

.reset-btn {
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  font-weight: 600;
  padding: 12px 24px;
  border-radius: 6px;
  box-shadow: 0px 4px 12px 0px rgba(0, 0, 0, 0.1);
  letter-spacing: 0.5px;
  font-size: 14px;
  transition: all 0.3s ease;

  &:hover {
    background: #f5f7fa;
    border-color: #c0c4cc;
    color: #409EFF;
    box-shadow: 0px 6px 16px 0px rgba(0, 0, 0, 0.15);
    transform: translateY(-1px);
  }
}

// 禁止点击样式
.no-pointer-events {
  pointer-events: none;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}
</style>
