<template>
  <div class="app-container" :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="content-header">
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item>投标人主体库</el-breadcrumb-item>
        <el-breadcrumb-item>企业知识库</el-breadcrumb-item>
        <el-breadcrumb-item>业绩库</el-breadcrumb-item>
        <el-breadcrumb-item>编辑业绩</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="header-actions">
        <el-button class="reset-btn" @click="handleClose()" :disabled="showSaveAnimation">返回</el-button>
        <el-button class="search-btn" @click="handleSave()" :loading="showSaveAnimation">保存</el-button>
      </div>
    </div>

    <div class="content-body">
      <el-row :gutter="24" class="content-row">
        <!-- 合同信息编辑 -->
        <el-col :span="8" class="form-pane">
          <ContractInfoEdit ref="contractInfo" />
        </el-col>
        <!-- 竣工报告与中标通知书编辑 -->
        <el-col :span="8" class="form-pane">
          <CompletionAndBidInfoEdit ref="completionAndBidInfo" />
        </el-col>
        <!-- 其他信息编辑 -->
        <el-col :span="8" class="form-pane">
          <OtherInfoEdit
            ref="otherInfo"
            :project-manager-options="projectManagerOptions"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { decryptWithSM4,encryptWithSM4 } from '@/utils/sm'
import ContractInfoEdit from './child/ContractInfoEdit.vue'
import CompletionAndBidInfoEdit from './child/CompletionAndBidInfoEdit.vue'
import OtherInfoEdit from './child/OtherInfoEdit.vue'
import { getPerformance, updatePerformance } from "@/api/enterpriseLibrary/performance/performance";
import { listAPI } from "@/api/enterpriseLibrary/personnel/personnel";

export default {
  name: 'PerformanceEdit',
  components: {
    ContractInfoEdit,
    CompletionAndBidInfoEdit,
    OtherInfoEdit
  },
  data() {
    return {
      enterpriseId: decryptWithSM4(this.$route.query.enterpriseId),
      id: decryptWithSM4(this.$route.query.id), // 解密获取业绩ID
      projectManagerOptions: [],
      detailData: {}, // 存储详情数据（与详情页结构一致）
      showUploadAnimation: false,
      showSaveAnimation: false,
      uploadQueue: 0,
      animationText: '识别中'
    }
  },
  created() {
    this.fetchDetailData() // 加载详情数据
    this.loadProjectManagers();
  },
  methods: {
    // 获取详情数据并分发到子组件（与详情页保持一致的数据结构）
    async fetchDetailData() {
      try {
        const response = await getPerformance({
          performanceId: this.id,
          enterpriseId: this.enterpriseId
        })
        this.detailData = response.data || {}

        // 向子组件传递完整的detailData（包含fileList），与详情页保持一致
        // 子组件内部根据businessType筛选对应文件
        this.$refs.contractInfo.setFormData(this.detailData)
        this.$refs.completionAndBidInfo.setFormData(this.detailData)
        this.$refs.otherInfo.setFormData(this.detailData)
      } catch (error) {
        this.$message.error('获取数据失败：' + (error.message || '网络错误'))
      }
    },

    // 返回列表页
    handleClose() {
      const obj = {
        path: "/performanceList/index",
        query: {
          enterpriseId: encryptWithSM4(this.enterpriseId)  // 补充传递企业ID
        }
      };
      this.$tab.closeOpenPage(obj)
    },

    async handleSave() {
      if (this.showSaveAnimation) return;
      this.showSaveAnimation = true;

      try {
        // 获取子组件数据
        const [contractData, completionBidData, otherData] = await Promise.all([
          this.$refs.contractInfo.validate(),
          this.$refs.completionAndBidInfo.validate(),
          this.$refs.otherInfo.validate()
        ]);

        // 工具函数：过滤文件列表中的 lsFilePath 字段
        const filterFileList = (fileList) => {
          return (fileList || []).map(file => {
            // 解构删除 lsFilePath，保留其他必要字段（如 fileId、name、filePath 等）
            const { lsFilePath, ...validFileInfo } = file;
            return validFileInfo;
          });
        };

        // 过滤各文件列表
        const contractFiles = filterFileList(contractData.fileList);
        const completionFiles = filterFileList(completionBidData.completionReportFileList);
        const bidFiles = filterFileList(completionBidData.bidNoticeFileList);

        // 组装提交数据（不含 lsFilePath）
        const formData = {
          ...this.detailData,
          ...contractData,
          ...completionBidData,
          ...otherData,
          enterpriseId: this.enterpriseId,
          performanceId: this.id,
          fileList: [
            ...contractFiles,
            ...completionFiles,
            ...bidFiles
          ]
        };

        // 移除子组件原始文件列表（避免冗余）
        delete formData.contractFileList;
        delete formData.completionReportFileList;
        delete formData.bidNoticeFileList;

        // 调用更新接口
        await updatePerformance(formData);
        this.$message.success('修改成功');
        this.handleClose();

      } 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
    },
    loadProjectManagers() {

      const params = {
        enterpriseId: this.enterpriseId,
        personnelPosition: 'project_manager'
      };

      listAPI(params).then(response => {
        // 转换为下拉框需要的格式（与子组件原逻辑一致）
        this.projectManagerOptions = (response.rows || []).map(person => ({
          label: person.personnelName,
          value: person.personnelName
        }));
      }).catch(error => {
        console.error('主组件获取项目经理列表失败：', error);
        this.projectManagerOptions = [];
      });
    },

  },
  mounted() {
    // 监听子组件的文件上传事件
    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">
/* 与PerformanceDetail保持一致的样式规范 */
.app-container {
  padding: 24px;
  background: linear-gradient(180deg, #F1F6FF 20%, #E5EFFF 100%);
  min-height: 100vh;
  overflow-y: auto;
  position: relative;

  &.no-pointer-events {
    pointer-events: none;
    * { pointer-events: none; }
  }
}

.global-upload-animation {
  position: fixed;
  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;
    pointer-events: auto;
  }

  .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;
    pointer-events: auto;

    .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-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

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

  ::v-deep .el-breadcrumb__item:last-child .el-breadcrumb__inner {
    color: #303133;
    font-weight: 500;
  }
}

.header-actions {
  display: flex;
  gap: 12px;
}

.content-body {
  margin-top: 10px;
}

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

.form-pane {
  background: #fff;
  border-radius: 16px;
  min-height: 600px;
  box-shadow: 0px 4px 20px 0px rgba(31, 35, 55, 0.1);
  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);
  }
}

@media (max-width: 1200px) {
  .content-row { gap: 16px; }
}

@media (max-width: 992px) {
  .form-pane {
    flex: 0 0 100%;
    max-width: 100%;
  }
}

@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>
