<template>
  <div>
    <div class="basic-info-title">
      <img src="@/assets/enterpriseLibrary/basic-info.png" alt="其他信息">
      <span>其他信息</span>
    </div>

    <el-form
      :model="formData"
      :rules="rules"
      ref="otherForm"
      label-width="110px"
      label-position="top"
    >
      <!-- 团队业绩证明 -->
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="团队业绩证明" prop="performanceFileList">
            <UploadFile
              ref="uploadFileComp"
              :fileList="formData.performanceFileList"
              @file-change="handleFileChange"
              @del-file="handleDelFile"
              :uploadType="uploadType"
              :maxFileTips="maxFileTips"
              :limitUploadNum="1"
              type="team_performance"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 项目信息 -->
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="项目经理" prop="projectManager">
            <el-select
              v-model="formData.projectManager"
              placeholder="请选择项目经理"
              class="form-control"
            >
              <el-option
                v-for="manager in projectManagerOptions"
                :key="manager.value"
                :label="manager.label"
                :value="manager.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="项目类型" prop="proType">
            <el-select
              v-model="formData.proType"
              placeholder="请选择项目类型"
              class="form-control"
            >
              <el-option
                v-for="type in proTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="电压等级" prop="voltageLevel">
            <el-select
              v-model="formData.voltageLevel"
              placeholder="请选择电压等级"
              class="form-control"
            >
              <el-option
                v-for="level in voltageLevelOptions"
                :key="level.value"
                :label="level.label"
                :value="level.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 项目概况 -->
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="项目概况" prop="projectOverview">
            <el-input
              v-model="formData.projectOverview"
              placeholder="请输入项目概况"
              type="textarea"
              rows="6"
              class="form-control"
              maxlength="500"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import UploadFile from '@/views/common/UploadFile.vue'

// 工具函数：安全获取数组
const safeGetArray = (value) => Array.isArray(value) ? value : []

export default {
  name: 'OtherInfo',
  components: { UploadFile },
  props: {
    projectManagerOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      uploadType: 'pdf、png、jpg',
      maxFileTips: '20MB',
      formData: {
        projectManager: '',
        proType: '',
        voltageLevel: '',
        projectOverview: '',
        performanceFileList: [], // 完全同步UploadFile的文件列表
        delFileList: [] // 记录删除/替换的文件路径
      },
      rules: {
        projectManager: [
          { required: true, message: '请选择项目经理', trigger: 'change' }
        ],
        proType: [
          { required: true, message: '请选择项目类型', trigger: 'change' }
        ],
        voltageLevel: [
          { required: true, message: '请选择电压等级', trigger: 'change' }
        ],
        projectOverview: [
          { required: true, message: '请输入项目概况', trigger: 'blur' },
          { max: 500, message: '项目概况不能超过500个字符', trigger: 'blur' }
        ],
        performanceFileList: [
          { required: true, message: '请上传团队业绩证明', trigger: ['change', 'blur'] }
        ]
      },
      proTypeOptions: [],
      voltageLevelOptions: []
    }
  },
  created() {
    this.loadVoltageLevelDict()
    this.loadProjcetTypeDict()
  },
  methods: {
    // 接收父组件数据并回显（完全对齐正常组件的getFileList逻辑）
    setFormData(data) {
      const teamFiles = Array.isArray(data.fileList)
        ? data.fileList.filter(file => file && file.businessType === 'team_performance')
          .map(file => ({
          name: file.fileName,
          filePath: file.filePath,
          lsFilePath: file.lsFilePath,
          fileType: file.fileType,
          // 不手动生成uid，由UploadFile处理
        }))
        : [];

      this.formData = {
        projectManager:data.projectManager,
        proType:data.proType,
        voltageLevel:data.voltageLevel,
        projectOverview:data.projectOverview,
        performanceFileList: teamFiles,
        delFileList: []
      };
    },

    // 加载字典数据
    loadVoltageLevelDict() {
      this.getDicts('voltage_level').then(response => {
        this.voltageLevelOptions = response.data.map(item => ({
          label: item.dictLabel,
          value: item.dictLabel
        }))
      }).catch(error => {
        console.error('加载电压等级字典失败：', error)
      })
    },

    loadProjcetTypeDict() {
      this.getDicts('project_type').then(response => {
        this.proTypeOptions = response.data.map(item => ({
          label: item.dictLabel,
          value: item.dictLabel
        }))
      }).catch(error => {
        console.error('加载项目类型字典失败：', error)
      })
    },

    // 关键修改：仅在文件上传成功（有response）后更新列表
    handleFileChange(files, type) {
      if (type === 'team_performance' && files instanceof Array) {
        // 仅在文件上传成功后才更新（对齐正常组件逻辑）
        if (files.length > 0 && files[0].response) {
          this.formData.performanceFileList = files;
        }
      }
    },

    // 处理文件删除（与正常组件逻辑一致）
    handleDelFile(file) {
      const delPath = file?.response?.fileRes?.filePath || file?.filePath || null;
      if (delPath) {
        this.formData.delFileList.push(delPath);
      }
    },

    // 表单验证
    validate() {
      return new Promise((resolve, reject) => {
        if (!this.$refs.otherForm) {
          reject(new Error('表单实例未加载完成'))
          return
        }

        this.$refs.otherForm.validate((valid) => {
          if (valid) {
            resolve(this.formData)
          } else {
            reject(new Error('其他信息填写不完整'))
          }
        })
      })
    },

    // 重置表单
    resetForm() {
      this.$nextTick(() => {
        if (this.$refs.uploadFileComp) {
          this.$refs.uploadFileComp.clearFiles();
        }
        if (this.$refs.otherForm) {
          this.$refs.otherForm.resetFields()
        }
        this.formData = {
          projectManager: '',
          proType: '',
          voltageLevel: '',
          projectOverview: '',
          performanceFileList: [],
          delFileList: []
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
.basic-info-title {
  display: flex;
  align-items: center;
  margin: 10px 0;
  span {
    margin: 0 5px;
    font-size: 20px;
  }
  img {
    width: 24px;
    height: 24px;
    object-fit: contain;
  }
}

.el-form {
  margin-top: 15px;
  padding: 0 15px;
}

.form-control {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
