<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>
      <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-contract">
          <ContractInfo ref="contractInfo" />
        </el-col>
      </el-row>
      <el-row :gutter="24" class="content-row">
        <!-- 竣工报告与中标通知书 -->
        <el-col :span="8" class="form-pane-CAB">
          <CompletionAndBidInfo ref="completionAndBidInfo" />
        </el-col>
      </el-row>
      <el-row :gutter="24" class="content-row">
        <!-- 其他信息 -->
        <el-col :span="8" class="form-pane-otherInfo">
          <OtherInfo
            ref="otherInfo"
            :project-manager-options="projectManagerOptions"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { decryptWithSM4, encryptWithSM4 } from '@/utils/sm'
import ContractInfo from './child/ContractInfo.vue'
import CompletionAndBidInfo from './child/CompletionAndBidInfo.vue'
import OtherInfo from './child/OtherInfo.vue'
import { listAPI } from "@/api/enterpriseLibrary/personnel/personnel";
import {
  addPerformance,
  updatePerformance,
  getPerformance,
  checkProNameUnique
} from "@/api/enterpriseLibrary/performance/performance";

export default {
  name: 'PerformanceForm',
  components: {
    ContractInfo,
    CompletionAndBidInfo,
    OtherInfo
  },
  data() {
    return {
      enterpriseId: decryptWithSM4(this.$route.query.enterpriseId),
      projectManagerOptions: [],
      id: decryptWithSM4(this.$route.query.id),
      type: decryptWithSM4(this.$route.query.type) || 'add',
      showUploadAnimation: false,
      showSaveAnimation: false,
      uploadQueue: 0,
      animationText: '识别中',
      originalProName: '' // 存储原始项目名称，用于编辑时唯一性校验
    }
  },

  created() {
    this.loadProjectManagers();
  },

  mounted() {
    // 监听上传事件（先解绑再绑定，避免重复监听）
    this.$bus.$on('startUpload', this.handleStartUpload)
    this.$bus.$off('endUpload', this.handleEndUpload)
    this.$bus.$on('endUpload', this.handleEndUpload)

    // 编辑时加载数据（与财务表单逻辑一致）
    if (this.type === 'edit' && this.id && this.enterpriseId) {
      this.loadPerformanceData()
    }
  },

  beforeDestroy() {
    // 移除所有事件监听，重置状态（对齐财务表单）
    this.$bus.$off('startUpload', this.handleStartUpload)
    this.$bus.$off('endUpload', this.handleEndUpload)
    this.showUploadAnimation = false
    this.showSaveAnimation = false
    this.uploadQueue = 0
  },

  methods: {
    // 返回（逻辑保持不变，与财务表单一致）
    handleClose() {
      const obj = {
        path: "/performanceList/index",
        query: {
          enterpriseId: encryptWithSM4(this.enterpriseId)
        }
      };
      this.$tab.closeOpenPage(obj)
    },

    // 保存（优化文件处理逻辑，对齐财务表单）
    async handleSave() {
      if (this.showSaveAnimation) return
      this.showSaveAnimation = true

      try {
        await this.$nextTick();
        // 1. 校验所有子组件表单
        const [contractData, completionBidData, otherData] = await Promise.all([
          this.$refs.contractInfo.validate(),
          this.$refs.completionAndBidInfo.validate(),
          this.$refs.otherInfo.validate()
        ])
        console.log('contractData',contractData)
        console.log('completionBidData',completionBidData)
        console.log('otherData',otherData)

        // 3. 初始化提交数据
        const formData = {
          ...contractData,
          ...completionBidData,
          ...otherData,
          enterpriseId: this.enterpriseId,
          id: this.id || null,
          files: [], // 统一存储所有文件
          delFiles: [] // 统一存储所有删除文件路径
        }

        console.log('formData',formData)


        // 4. 处理合同附件
        if (contractData.fileList && contractData.fileList.length) {
          const contractFiles = contractData.fileList.map(file =>
            file.response?.fileRes ? { ...file.response.fileRes, businessType: 'contract' } : null
          ).filter(Boolean)
          formData.files.push(...contractFiles)
        }
        if (contractData.delFileList && contractData.delFileList.length) {
          formData.delFiles.push(...contractData.delFileList)
        }

        // 5. 处理竣工报告附件
        if (completionBidData.completionReportFileList && completionBidData.completionReportFileList.length) {
          const completionFiles = completionBidData.completionReportFileList.map(file =>
            file.response?.fileRes ? { ...file.response.fileRes, businessType: 'completion_report' } : null
          ).filter(Boolean)
          formData.files.push(...completionFiles)
        }

        // 6. 处理中标通知书附件
        if (completionBidData.bidNoticeFileList && completionBidData.bidNoticeFileList.length) {
          const bidFiles = completionBidData.bidNoticeFileList.map(file =>
            file.response?.fileRes ? { ...file.response.fileRes, businessType: 'bid_notice' } : null
          ).filter(Boolean)
          formData.files.push(...bidFiles)
        }
        if (completionBidData.delFileList && completionBidData.delFileList.length) {
          formData.delFiles.push(...completionBidData.delFileList)
        }

        // 7. 处理团队业绩证明附件
        if (otherData.performanceFileList && otherData.performanceFileList.length) {
          const performanceFiles = otherData.performanceFileList.map(file =>
            file.response?.fileRes ? { ...file.response.fileRes, businessType: 'team_performance' } : null
          ).filter(Boolean)
          formData.files.push(...performanceFiles)
        }
        if (otherData.delFileList && otherData.delFileList.length) {
          formData.delFiles.push(...otherData.delFileList)
        }

        // 8. 删除临时文件字段
        ['fileList', 'completionReportFileList', 'bidNoticeFileList', 'performanceFileList', 'delFileList'].forEach(key => {
          delete formData[key]
        })

        // 9. 调用接口
        if (this.type === 'add') {

          await addPerformance(formData)
        } else {
          console.log('编辑后的数据',formData)
          await updatePerformance(formData)
        }

        this.$message.success(`${this.type === 'add' ? '新增' : '修改'}成功`)
        this.handleClose()

      } catch (error) {
        this.$message.error(error.message || '请完善表单信息')
      } finally {
        this.showSaveAnimation = false
      }
    },

    // 加载业绩数据（编辑时）
    async loadPerformanceData() {
      try {
        const response = await getPerformance({
          performanceId: this.id,
          enterpriseId: this.enterpriseId
        })
        const performanceData = response.data || {}
        this.originalProName = performanceData.proName // 保存原始项目名称

        // 按业务类型筛选文件
        const fileList = performanceData.fileList || []
        const contractFiles = fileList.filter(f => f.businessType === 'contract')
        const completionFiles = fileList.filter(f => f.businessType === 'completion_report')
        const bidFiles = fileList.filter(f => f.businessType === 'bid_notice')
        const teamFiles = fileList.filter(f => f.businessType === 'team_performance')


        // 传递数据给子组件
        this.$refs.contractInfo.setFormData({
          ...performanceData,
          fileList: contractFiles
        })
        this.$refs.completionAndBidInfo.setFormData({
          ...performanceData,
          completionReportFileList: completionFiles,
          bidNoticeFileList: bidFiles
        })
        this.$refs.otherInfo.setFormData({
          ...performanceData,
          performanceFileList: teamFiles
        })
      } catch (error) {
        this.$message.error('加载业绩信息失败：' + error.message)
      }
    },

    // 加载项目经理列表
    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 = [];
      });
    },

    // 上传动画控制
    handleStartUpload(text) {
      this.animationText = text || '识别中'
      this.uploadQueue++
      this.showUploadAnimation = true
    },

    handleEndUpload() {
      if (this.uploadQueue > 0) this.uploadQueue--
      if (this.uploadQueue === 0) this.showUploadAnimation = false
    }
  }
}
</script>

<style scoped lang="scss">
.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-contract, .form-pane-CAB, .form-pane-otherInfo {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0px 4px 20px 0px rgba(31, 35, 55, 0.1);
  padding: 0;
  margin-bottom: 20px;
  flex: 1;
  min-width: 300px;
}

.form-pane-contract { min-height: 600px; }
.form-pane-CAB { min-height: 500px; }
.form-pane-otherInfo { min-height: 400px; }

.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-contract, .form-pane-CAB, .form-pane-otherInfo {
    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>
