<template>
  <el-card class="labeling-task-form-container" shadow="never">
    <!-- 页面头部：返回+步骤导航+下一步按钮 -->
    <div class="page-header">
      <el-button @click="handleBack" class="back-btn">返回</el-button>
      <el-button
        v-show="activeStep === 1"
        type="primary"
        @click="goToNextStep"
        class="next-btn"
      >下一步</el-button>
      <el-button
        v-show="activeStep === 2"
        type="primary"
        @click="submitForm"
        class="next-btn"
      >提交</el-button>
    </div>

    <!-- 进度步骤条 -->
    <div class="progress-steps">
      <div class="step-item">
        <div class="step-dot active">01</div>
        <div class="step-text">基本信息</div>
      </div>
      <div class="step-line"></div>
      <div class="step-item" :class="{ active: activeStep === 2 }">
        <div class="step-dot" :class="{ active: activeStep === 2 }">02</div>
        <div class="step-text">团队人员信息</div>
      </div>
    </div>

    <!-- 表单容器：增加v-if确保form初始化后再渲染 -->
    <div class="form-container" v-if="form">
      <!-- 第一步：基本信息 -->
      <div v-show="activeStep === 1" class="form-step">
        <div class="form-title">任务信息</div>
        <el-form
          :model="form"
          :rules="rules"
          ref="basicForm"
          label-position="top"
          label-width="100%"
          class="basic-form"
        >
          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item label="标注任务名称" prop="labelingTaskName">
                <el-input
                  v-model="form.labelingTaskName"
                  placeholder="请输入标注任务名称"
                  maxlength="64"
                  show-word-limit
                  class="form-input"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="数据集名称" prop="datasetId" class="has-clear">
                <el-select
                  v-model="form.datasetId"
                  placeholder="请选择数据集"
                  filterable
                  clearable
                  class="form-select"
                >
                  <el-option
                    v-for="item in datasetList"
                    :key="`dataset-${item.datasetId}`"
                    :label="item.datasetName"
                    :value="item.datasetId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="数据集版本" prop="datasetVersionId" class="has-clear">
                <el-select
                  v-model="form.datasetVersionId"
                  placeholder="请选择版本"
                  clearable
                  filterable
                  :disabled="!form.datasetId"
                  class="form-select"
                >
                  <el-option
                    v-for="item in versionList"
                    :key="item.datasetVersionId"
                    :label="item.datasetVersion"
                    :value="item.datasetVersionId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="标签名称" prop="labelId" class="has-clear">
                <el-select
                  v-model="form.labelName"
                  placeholder="请选择标签"
                  clearable
                  multiple
                  @remove-tag="handleTagRemove"
                  @clear="handleSelectClear"
                  class="form-select"
                  style="width: 100%"
                  key="label-select-unique"
                >
                  <el-option value="" style="height: auto; padding: 0">
                    <el-tree
                      ref="labelTree"
                      :data="labelTreeData"
                      :props="treeProps"
                      :show-checkbox="true"
                      :check-strictly="false"
                      :default-checked-keys="form.labelId"
                      @check-change="handleTreeCheckChange"
                      node-key="id"
                      class="label-tree"
                      :expand-on-click-node="false"
                    ></el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item label="时间范围" prop="labelingTaskTime" class="has-clear">
                <el-date-picker
                  v-model="form.labelingTaskTimeArray"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  class="form-datepicker"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="审核流程" prop="labelingTaskAuditProcess" class="has-clear">
                <el-select
                  v-model="form.labelingTaskAuditProcess"
                  placeholder="请选择"
                  clearable
                  class="form-select"
                  @change="handleAuditProcessChange"
                >
                  <el-option
                    v-for="item in dict.type.review_process"
                    :key="`audit-${item.value}`"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否允许未过审数据" prop="labelingTaskPassState" class="has-clear">
                <el-select
                  v-model="form.labelingTaskPassState"
                  placeholder="请选择"
                  clearable
                  class="form-select"
                >
                  <el-option key="pass-0" label="否" value="0"></el-option>
                  <el-option key="pass-1" label="是" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 占位列 -->
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="labelingTaskAuditRemark">
                <el-input
                  type="textarea"
                  v-model="form.labelingTaskAuditRemark"
                  placeholder="请输入"
                  maxlength="256"
                  show-word-limit
                  :autosize="{ minRows: 3, maxRows: 5 }"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 第二步：团队人员信息 -->
      <div v-if="activeStep === 2" class="form-step">
        <div class="form-title">团队人员信息</div>
        <el-form
          :model="teamForm"
          :rules="teamRules"
          ref="teamFormRef"
          label-position="top"
          label-width="100%"
          class="team-form"
          :validate-on-rule-change="false"
        >
          <!-- 标注人员模块 -->
          <div class="audit-section">
            <div class="section-title">标注</div>
            <el-row :gutter="30" class="section-form-row">
              <el-col :span="6">
                <el-form-item label="团队名称" prop="labelTeamName" class="has-clear">
                  <el-select
                    v-model="teamForm.labelTeamName"
                    placeholder="请选择"
                    clearable
                    filterable
                    class="form-select"
                    @change="triggerLabelTeamValidate"
                  >
                    <el-option
                      v-for="item in filteredLabelTeamList"
                      :key="`label-team-${item.teamId}`"
                      :label="item.teamName"
                      :value="item.teamId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="人员名称" prop="labelers" class="has-clear">
                  <el-select
                    v-model="teamForm.labelers"
                    placeholder="请选择"
                    clearable
                    multiple
                    filterable
                    class="form-select"
                    key="labelers-select-unique"
                    @change="triggerLabelersValidate"
                    :disabled="!teamForm.labelTeamName"
                  >
                    <el-option
                      v-for="item in filteredLabelUserList"
                      :key="`labeler-${item.userId}`"
                      :label="item.userName"
                      :value="item.userId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 标注人员表格 -->
            <el-table :data="labelUserTableData" border class="audit-table" :show-header="true" fit>
              <el-table-column prop="serialNo" label="序号" width="200"></el-table-column>
              <el-table-column prop="userName" label="人员名称" width="400"></el-table-column>
              <el-table-column prop="roleName" label="角色名称" width="400"></el-table-column>
              <el-table-column label="数据量" prop="dataCount">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.dataCount"
                    placeholder="请输入"
                    type="number"
                    min="0"
                    @input="handleDataCountInput('label', scope.row)"
                  >
                    <template slot="append">
                      <span v-if="scope.row.dataCount > sampleCount" class="error-tip">
                        超过总数{{ sampleCount }}
                      </span>
                    </template>
                  </el-input>
                </template>
              </el-table-column>
            </el-table>
            <!-- 标注数据量汇总校验提示 -->
            <div class="data-count-summary" v-if="labelUserTableData.length > 0">
              标注数据量总和：<span :class="{ 'count-error': labelTotalCount !== sampleCount }">{{ labelTotalCount }}</span>
              <span v-if="labelTotalCount !== sampleCount" class="summary-error-tip">
                {{ labelTotalCount > sampleCount ? '超过样本总数' : '未达到样本总数' }}，需等于{{ sampleCount }}
              </span>
            </div>
          </div>

          <!-- 动态渲染审核模块（审核1、审核2、审核3...） -->
          <div
            v-for="auditLevel in Number(form.labelingTaskAuditProcess)"
            :key="`audit-section-${auditLevel}`"
            class="audit-section"
          >
            <div class="section-title">审核{{ auditLevel }}</div>
            <el-row :gutter="30" class="section-form-row">
              <el-col :span="6">
                <el-form-item :label="`团队名称`" :prop="`audit${auditLevel}TeamName`" class="has-clear">
                  <el-select
                    v-model="teamForm[`audit${auditLevel}TeamName`]"
                    placeholder="请选择"
                    clearable
                    filterable
                    class="form-select"
                    @change="() => handleAuditTeamChange(auditLevel)"
                    :disabled="!isLabelInfoCompleted"
                  >
                    <el-option
                      v-for="item in getFilteredAuditTeamList(auditLevel)"
                      :key="`audit${auditLevel}-team-${item.teamId}`"
                      :label="item.teamName"
                      :value="item.teamId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="`人员名称`" :prop="`audit${auditLevel}Users`" class="has-clear">
                  <el-select
                    v-model="teamForm[`audit${auditLevel}Users`]"
                    placeholder="请选择"
                    clearable
                    multiple
                    filterable
                    class="form-select"
                    :key="`audit${auditLevel}-users-select`"
                    @change="() => handleAuditUsersChange(auditLevel)"
                    :disabled="!teamForm[`audit${auditLevel}TeamName`] || !isLabelInfoCompleted"
                  >
                    <el-option
                      v-for="item in getFilteredAuditUserList(auditLevel)"
                      :key="`audit${auditLevel}-user-${item.userId}`"
                      :label="item.userName"
                      :value="item.userId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="`审核方式`" :prop="`audit${auditLevel}Type`" class="has-clear">
                  <el-select
                    v-model="teamForm[`audit${auditLevel}Type`]"
                    placeholder="请选择"
                    clearable
                    class="form-select"
                    @change="() => handleAuditTypeChange(auditLevel)"
                    :disabled="!teamForm[`audit${auditLevel}Users`] || !isLabelInfoCompleted"
                  >
                    <el-option key="audit-type-user" label="人员" value="user"></el-option>
                    <el-option key="audit-type-count" label="数量" value="count"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 被审核人员完整性提示（仅审核方式为人员时显示） -->
            <div v-if="teamForm[`audit${auditLevel}Type`] === 'user'" class="audit-user-check-tip" :class="{ 'tip-error': !checkAuditUserComplete(auditLevel) }">
              <i class="el-icon-warning"></i>
              {{ checkAuditUserComplete(auditLevel) ? '✓ 被审核人员已包含所有标注人员' : '✗ 被审核人员未包含所有标注人员，请补充选择' }}
            </div>

            <!-- 审核人员表格 -->
            <el-table
              :data="teamForm[`audit${auditLevel}TableData`] || []"
              border
              class="audit-table"
              :show-header="true"
              fit
            >
              <el-table-column prop="serialNo" label="序号" width="200"></el-table-column>
              <el-table-column prop="userName" label="人员名称" width="400"></el-table-column>
              <el-table-column prop="roleName" label="角色名称" width="400"></el-table-column>
              <el-table-column
                :label="teamForm[`audit${auditLevel}Type`] === 'user' ? '被审核人员名称' : '数据量'"
                prop="dataCount"
              >
                <template slot-scope="scope">
                  <el-select
                    v-if="teamForm[`audit${auditLevel}Type`] === 'user'"
                    v-model="scope.row.auditedUserId"
                    placeholder="请选择"
                    clearable
                    filterable
                    class="form-select"
                    style="width: 100%"
                    @change="() => handleAuditedUserChange(auditLevel, scope.row)"
                  >
                    <!-- 过滤掉当前审核层级已选的其他被审核人员 -->
                    <el-option
                      v-for="item in getFilteredAuditedUserList(auditLevel, scope.row.userId)"
                      :key="`audited-${auditLevel}-${scope.row.userId}-${item.userId}`"
                      :label="item.userName"
                      :value="item.userId"
                    ></el-option>
                  </el-select>
                  <el-input
                    v-else
                    v-model="scope.row.dataCount"
                    placeholder="请输入"
                    type="number"
                    min="0"
                    style="width: 100%"
                    @input="handleDataCountInput(`audit${auditLevel}`, scope.row)"
                  >
                    <template slot="append">
                      <span v-if="scope.row.dataCount > sampleCount" class="error-tip">
                        超过总数{{ sampleCount }}
                      </span>
                    </template>
                  </el-input>
                </template>
              </el-table-column>
            </el-table>
            <!-- 审核数据量汇总校验提示（仅审核方式为数量时显示） -->
            <div
              class="data-count-summary"
              v-if="teamForm[`audit${auditLevel}TableData`].length > 0 && teamForm[`audit${auditLevel}Type`] === 'count'"
            >
              审核{{ auditLevel }}数据量总和：<span :class="{ 'count-error': getAuditTotalCount(auditLevel) !== sampleCount }">{{ getAuditTotalCount(auditLevel) }}</span>
              <span v-if="getAuditTotalCount(auditLevel) !== sampleCount" class="summary-error-tip">
                {{ getAuditTotalCount(auditLevel) > sampleCount ? '超过样本总数' : '未达到样本总数' }}，需等于{{ sampleCount }}
              </span>
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </el-card>
</template>

<script>
import _ from 'lodash'
import {
  addLabelingTaskAPI,
  editLabelingTaskAPI,
  getLabelingTaskDetailAPI,
  getDatasetListAPI
} from '@/api/data/labeling'
import { listTeamAPI } from '@/api/system/team'
import { getDatasetSelectListAPI, getDatasetVersionSelectListAPI } from '@/api/data/dataset'
import { getLabelTreeListAPI, getLabelListByIdsAPI } from '@/api/data/labeling'
import { listUser } from '@/api/system/user'
import { decryptWithSM4, encryptWithSM4 } from '@/utils/sm'

export default {
  name: 'LabelingTaskAdd',
  dicts: ['review_process'],
  data() {
    return {
      labelingTaskId: this.convertToNumber(decryptWithSM4(this.$route.query.labelingTaskId || '')),
      sampleCount: 0,
      activeStep: 1,
      isEdit: false,
      personLoading: false,
      form: {
        labelingTaskId: '',
        labelingTaskName: '',
        datasetId: '',
        datasetVersionId: '',
        labelId: [],
        labelName: [],
        labelingTaskTimeArray: [],
        labelingTaskTime: '',
        labelingTaskAuditProcess: '',
        labelingTaskPassState: '',
        labelingTaskAuditRemark: '',
        datasetVersion: '',
        datasetName: ''
      },
      // 团队表单：包含标注、各层级审核的所有数据
      teamForm: {
        labelTeamName: '',
        labelers: [],
        labelUserTableData: [],
        leader: ''
      },
      // 新增：存储后端返回的审核人员列表（含团队信息）
      auditPersonList: [],
      // 核心修复3：rules对象提前初始化，避免渲染时找不到
      rules: {
        labelingTaskName: [
          { required: true, message: '标注任务名称不能为空', trigger: 'blur' }
        ],
        datasetId: [
          { required: true, message: '数据集名称不能为空', trigger: 'change' }
        ],
        datasetVersionId: [
          { required: true, message: '数据集版本不能为空', trigger: 'change' }
        ],
        labelId: [
          {
            required: true,
            message: '标签名称不能为空',
            trigger: 'change',
            type: 'array'
          }
        ],
        labelingTaskTime: [
          { required: true, message: '任务时间不能为空', trigger: 'change' }
        ],
        labelingTaskAuditProcess: [
          { required: true, message: '审核流程不能为空', trigger: 'change' }
        ],
        labelingTaskPassState: [
          { required: true, message: '是否允许未过审数据不能为空', trigger: 'change' }
        ]
      },
      // 第二步校验规则：初始为空，进入第二步后初始化
      teamRules: {},
      datasetList: [],
      versionList: [],
      userList: {}, // 修改：改为对象存储不同团队的人员列表 { teamId: [userList] }
      teamList: [], // 团队列表
      labelTreeData: [],
      treeProps: {
        children: 'children',
        label: 'label',
        value: 'id'
      },
      // 已选团队和人员的跟踪状态
      selectedTeams: [],
      selectedUsers: [],
      // 标记是否正在提交
      isSubmitting: false,
      // 跟踪各审核层级已选的被审核人员
      selectedAuditedUsers: {} // { audit1: [userId1, userId2], audit2: [userId3] }
    }
  },
  created() {
    this.getDatasetSelectList()
    this.getLabelTreeList()
    this.initData()
    this.getTeamSelectList()

    this.isEdit = this.$route.query.type === 'edit'
    if (this.isEdit) {
      this.getTaskDetail()
    }
  },
  methods: {
    convertToNumber(value) {
      if (!value || value === '' || value === 'undefined' || value === 'null') {
        return '';
      }
      const num = Number(value);
      return isNaN(num) ? '' : num;
    },

    async initPersonList(teamId, type = 'label', auditLevel = 0) {
      if (!teamId) {
        if (type === 'label') {
          this.userList = {}
          // 注释掉：禁止清空labelers！
          // this.teamForm.labelers = []
          this.teamForm.labelUserTableData = []
        } else {
          this.teamForm[`audit${auditLevel}Users`] = []
          this.teamForm[`audit${auditLevel}TableData`] = []
        }
        return
      }

      try {
        this.personLoading = true;
        const res = await listUser({ teamId });
        if (res.code === 200) {
          const peopleList = res.rows || [];
          this.$set(this.userList, teamId, peopleList.map(item => {
            const team = this.teamList.find(t => t.teamId === teamId)
            return {
              userId: item.userId,
              userName: item.userName,
              userRole: item.roles?.[0]?.roleName || '未知角色',
              teamId: teamId,
              teamName: team?.teamName || ''
            };
          }));

          if (type === 'label') {
            this.teamForm.labelUserTableData = this.teamForm.labelUserTableData.map(row => {
              const user = this.userList[teamId]?.find(item => item.userId === row.userId)
              return {
                ...row,
                userName: user?.userName || row.userName,
                roleName: user?.userRole || row.roleName
              }
            })
            // 注释掉：禁止清空labelers！
            // this.teamForm.labelers = []
          } else {
            this.teamForm[`audit${auditLevel}TableData`] = (this.teamForm[`audit${auditLevel}TableData`] || []).map(row => {
              const user = this.userList[teamId]?.find(item => item.userId === row.userId)
              return {
                ...row,
                userName: user?.userName || row.userName,
                roleName: user?.userRole || row.roleName
              }
            })
            this.teamForm[`audit${auditLevel}Users`] = []
          }
        } else {
          this.$modal.msgError('获取人员列表失败：' + res.msg);
        }
      } catch (error) {
        this.$modal.msgError('获取人员列表异常：' + error.message);
        console.error('获取人员列表失败：', error);
      } finally {
        this.personLoading = false;
        this.updateSelectedTeamsAndUsers()
      }
    },

    async getTeamSelectList() {
      try {
        const res = await listTeamAPI({})
        if (res.code === 200) {
          this.teamList = res.rows
        }
      } catch (error) {
        this.$modal.msgError("获取团队下拉表失败" + error)
      }
    },

    // 初始化第二步校验规则
    initTeamRules() {
      // 基础规则
      this.teamRules = {
        labelTeamName: [
          { required: true, message: '标注团队名称不能为空', trigger: 'manual' }
        ],
        labelers: [
          {
            validator: (rule, value, callback) => {
              if (!Array.isArray(value) || value.length === 0) {
                callback(new Error('至少选择一名标注人员'))
              } else {
                if (!this.isSubmitting) {
                  this.syncLabelUserTableData()
                }
                callback()
              }
            },
            trigger: 'manual'
          }
        ]
      }

      // 审核流程规则
      const auditLevel = Number(this.form.labelingTaskAuditProcess)
      if (auditLevel > 0) {
        for (let i = 1; i <= auditLevel; i++) {
          this.$set(this.teamRules, `audit${i}TeamName`, [
            { required: true, message: `审核${i}团队名称不能为空`, trigger: 'manual' }
          ])
          this.$set(this.teamRules, `audit${i}Users`, [
            {
              validator: (rule, value, callback) => {
                if (!Array.isArray(value) || value.length === 0) {
                  callback(new Error(`至少选择一名审核${i}人员`))
                } else {
                  if (!this.isSubmitting) {
                    this.syncAuditUserTableData(i)
                  }
                  callback()
                }
              },
              trigger: 'manual'
            }
          ])
          this.$set(this.teamRules, `audit${i}Type`, [
            { required: true, message: `审核${i}方式不能为空`, trigger: 'manual' }
          ])
        }
      }
    },

    // 实时校验单个人员数据量输入
    handleDataCountInput(type, row) {
      row.dataCount = Number(row.dataCount) || 0

      if (row.dataCount > this.sampleCount && this.sampleCount > 0) {
        this.$message.warning(`单个人员数据量不能超过样本总数${this.sampleCount}`)
        row.dataCount = this.sampleCount
      }

      if (type === 'label') {
        this.teamForm.labelUserTableData = [...this.teamForm.labelUserTableData]
      } else {
        this.$set(this.teamForm, `${type}TableData`, [...this.teamForm[`${type}TableData`]])
      }
    },

    // 获取标注数据量总和
    getLabelTotalCount() {
      return this.teamForm.labelUserTableData.reduce((sum, item) => {
        return sum + (Number(item.dataCount) || 0)
      }, 0)
    },

    // 获取指定层级审核数据量总和
    getAuditTotalCount(auditLevel) {
      const tableData = this.teamForm[`audit${auditLevel}TableData`] || []
      return tableData.reduce((sum, item) => {
        return sum + (Number(item.dataCount) || 0)
      }, 0)
    },

    // 提交前校验所有数据量总和
    validateDataCountTotal() {
      // 1. 校验标注数据量总和
      const labelTotal = this.getLabelTotalCount()
      if (labelTotal !== this.sampleCount && this.sampleCount > 0) {
        this.$message.error(`标注数据量总和(${labelTotal})与样本总数(${this.sampleCount})不相等，请调整`)
        return false
      }

      // 2. 校验各层级审核数据量总和（仅审核方式为数量时）
      const auditLevel = Number(this.form.labelingTaskAuditProcess)
      for (let i = 1; i <= auditLevel; i++) {
        const auditType = this.teamForm[`audit${i}Type`]
        if (auditType === 'count') {
          const auditTotal = this.getAuditTotalCount(i)
          if (auditTotal !== this.sampleCount && this.sampleCount > 0) {
            this.$message.error(`审核${i}数据量总和(${auditTotal})与样本总数(${this.sampleCount})不相等，请调整`)
            return false
          }
        }
      }

      return true
    },

    // 校验被审核人员完整性（是否包含所有标注人员）
    checkAuditUserComplete(auditLevel) {
      if (!this.teamForm.labelers || this.teamForm.labelers.length === 0) {
        return false
      }

      const tableData = this.teamForm[`audit${auditLevel}TableData`] || []
      // 获取当前审核层级已选的所有被审核人员ID
      const selectedAuditedUserIds = tableData
        .map(row => row.auditedUserId)
        .filter(id => id) // 过滤空值

      // 检查所有标注人员是否都被包含
      return this.teamForm.labelers.every(labelerId =>
        selectedAuditedUserIds.includes(labelerId)
      )
    },

    // 被审核人员选择变更处理
    handleAuditedUserChange(auditLevel, currentRow) {
      const auditKey = `audit${auditLevel}`

      // 初始化当前审核层级的已选被审核人员数组
      if (!Array.isArray(this.selectedAuditedUsers[auditKey])) {
        this.$set(this.selectedAuditedUsers, auditKey, [])
      }

      const selectedAuditedUserIds = this.selectedAuditedUsers[auditKey]

      // 移除当前行之前选择的被审核人员（如果有）
      const prevIndex = selectedAuditedUserIds.indexOf(currentRow.prevAuditedUserId)
      if (prevIndex > -1) {
        selectedAuditedUserIds.splice(prevIndex, 1)
      }

      // 记录当前行之前的被审核人员ID（用于后续移除）
      currentRow.prevAuditedUserId = currentRow.auditedUserId

      // 添加新选择的被审核人员
      if (currentRow.auditedUserId && !selectedAuditedUserIds.includes(currentRow.auditedUserId)) {
        selectedAuditedUserIds.push(currentRow.auditedUserId)
      }

      // 更新表格数据
      this.$set(this.teamForm, `${auditKey}TableData`, [...this.teamForm[`${auditKey}TableData`]])

      // 强制更新视图
      this.$forceUpdate()
    },

    // 获取过滤后的被审核人员列表（排除当前审核层级已选的其他被审核人员）
    getFilteredAuditedUserList(auditLevel, currentRowUserId) {
      if (!this.labeledUserList || this.labeledUserList.length === 0) {
        return []
      }

      const auditKey = `audit${auditLevel}`
      // 获取当前审核层级所有已选的被审核人员ID（排除当前行的）
      const selectedAuditedUserIds = Array.isArray(this.selectedAuditedUsers[auditKey])
        ? this.selectedAuditedUsers[auditKey]
        : []

      // 获取当前行已选的被审核人员ID
      const currentRow = this.teamForm[`audit${auditLevel}TableData`]?.find(row => row.userId === currentRowUserId)
      const currentAuditedUserId = currentRow?.auditedUserId

      // 过滤逻辑：
      // 1. 保留当前行已选的被审核人员（允许取消选择）
      // 2. 排除其他行已选的被审核人员
      return this.labeledUserList.filter(user => {
        return user.userId === currentAuditedUserId || !selectedAuditedUserIds.includes(user.userId)
      })
    },

    handleAuditProcessChange(val) {
      this.form.labelingTaskAuditProcess = val
      // 清空原有审核数据
      Object.keys(this.teamForm).forEach(key => {
        if (key.startsWith('audit')) {
          this.$set(this.teamForm, key, [])
        }
      })
      // 清空已选被审核人员跟踪
      this.selectedAuditedUsers = {}
      // 初始化各层级审核数据（关键修复：确保每个属性都初始化为空数组/空字符串）
      const auditLevel = Number(val)
      for (let i = 1; i <= auditLevel; i++) {
        this.$set(this.teamForm, `audit${i}TeamName`, '')
        this.$set(this.teamForm, `audit${i}Users`, [])
        this.$set(this.teamForm, `audit${i}Type`, '')
        // 关键：初始化TableData为空数组，避免模板访问length时报错
        this.$set(this.teamForm, `audit${i}TableData`, [])
        // 初始化已选被审核人员跟踪（改为数组存储已选ID）
        this.$set(this.selectedAuditedUsers, `audit${i}`, [])
      }
      this.updateSelectedTeamsAndUsers()
    },

    // 审核方式变更
    handleAuditTypeChange(auditLevel) {
      const existingTableData = this.teamForm[`audit${auditLevel}TableData`] || []
      this.syncAuditUserTableData(auditLevel)

      // 恢复已填写的数据
      if (existingTableData.length > 0) {
        const newTableData = this.teamForm[`audit${auditLevel}TableData`]
        existingTableData.forEach(oldRow => {
          const newRow = newTableData.find(row => row.userId === oldRow.userId)
          if (newRow) {
            newRow.dataCount = oldRow.dataCount
            newRow.auditedUserId = oldRow.auditedUserId
            // 记录之前选择的被审核人员ID
            newRow.prevAuditedUserId = oldRow.auditedUserId
            // 更新已选被审核人员跟踪数组
            if (newRow.auditedUserId) {
              const auditKey = `audit${auditLevel}`
              if (!Array.isArray(this.selectedAuditedUsers[auditKey])) {
                this.$set(this.selectedAuditedUsers, auditKey, [])
              }
              if (!this.selectedAuditedUsers[auditKey].includes(newRow.auditedUserId)) {
                this.selectedAuditedUsers[auditKey].push(newRow.auditedUserId)
              }
            }
          }
        })
        this.$set(this.teamForm, `audit${auditLevel}TableData`, newTableData)
      }

      this.triggerAuditValidate(auditLevel, 'Type')
      this.$forceUpdate()
    },

    // 审核团队变更处理
    handleAuditTeamChange(auditLevel) {
      const teamId = this.teamForm[`audit${auditLevel}TeamName`]
      // 调用人员接口获取对应审核团队的人员列表
      this.initPersonList(teamId, 'audit', auditLevel)
      this.triggerAuditValidate(auditLevel, 'TeamName')
      this.$forceUpdate()
    },

    // 审核人员变更处理
    handleAuditUsersChange(auditLevel) {
      this.triggerAuditValidate(auditLevel, 'Users')
      this.$forceUpdate()
    },

    // 同步标注人员表格数据
    syncLabelUserTableData() {
      const labelers = this.teamForm.labelers
      if (!Array.isArray(labelers) || labelers.length === 0) {
        this.teamForm.labelUserTableData = []
        return
      }

      const existingData = [...this.teamForm.labelUserTableData]
      const labelTeamUsers = this.userList[this.teamForm.labelTeamName] || []
      const currentLabelTeamId = this.teamForm.labelTeamName

      const newTableData = labelers.map((userId, index) => {
        const user = labelTeamUsers.find(item => item.userId === userId)
        const existingRow = existingData.find(row => row.userId === userId)

        // 关键：优先保留接口返回的dataCount，其次保留已输入的，最后兜底0
        const originDataCount = this.auditPersonList.find(p => p.userId === userId)?.labelingNum || 0
        return {
          serialNo: index + 1,
          userId,
          userName: user?.userName || '',
          roleName: user?.userRole || '',
          teamName: user?.teamName || '',
          teamId: currentLabelTeamId,
          // 修复：优先用接口原始值，再用现有值，最后兜底
          dataCount: existingRow?.dataCount || Number(originDataCount) || 0
        }
      })

      this.teamForm.labelUserTableData = newTableData
    },

    syncAuditUserTableData(auditLevel) {
      const auditUsers = this.teamForm[`audit${auditLevel}Users`]
      if (!Array.isArray(auditUsers) || auditUsers.length === 0) {
        this.$set(this.teamForm, `audit${auditLevel}TableData`, [])
        return
      }

      const existingData = [...(this.teamForm[`audit${auditLevel}TableData`] || [])]
      const auditTeamUsers = this.userList[this.teamForm[`audit${auditLevel}TeamName`]] || []
      // 当前选中的该层级审核团队ID
      const currentAuditTeamId = this.teamForm[`audit${auditLevel}TeamName`]

      const newTableData = auditUsers.map((userId, index) => {
        const user = auditTeamUsers.find(item => item.userId === userId)
        const existingRow = existingData.find(row => row.userId === userId)

        const auditPerson = this.auditPersonList.find(p => p.userId === userId)

        return {
          serialNo: index + 1,
          userId,
          userName: user?.userName || '',
          roleName: '管理员',
          teamName: auditPerson?.teamName || user?.teamName || '',
          teamId: currentAuditTeamId, // 新增：存入当前选中的审核团队ID
          auditedUserId: existingRow?.auditedUserId || '',
          prevAuditedUserId: existingRow?.auditedUserId || '',
          dataCount: existingRow?.dataCount || 0
        }
      })

      this.$set(this.teamForm, `audit${auditLevel}TableData`, newTableData)

      // 同步已选被审核人员跟踪数组
      const auditKey = `audit${auditLevel}`
      this.selectedAuditedUsers[auditKey] = newTableData
        .map(row => row.auditedUserId)
        .filter(id => id)
    },

    // 手动触发校验
    triggerLabelTeamValidate() {
      if (this.$refs.teamFormRef) {
        this.$refs.teamFormRef.validateField('labelTeamName')
      }
      // 调用标注团队的人员接口
      this.initPersonList(this.teamForm.labelTeamName, 'label')
      this.updateSelectedTeamsAndUsers()
      this.$forceUpdate()
    },

    triggerLabelersValidate() {
      if (this.$refs.teamFormRef) {
        this.$refs.teamFormRef.validateField('labelers')
      }
      this.updateSelectedTeamsAndUsers()
      this.$forceUpdate()
    },

    triggerLeaderValidate() {
      if (this.$refs.teamFormRef) {
        this.$refs.teamFormRef.validateField('leader')
      }
      this.updateSelectedTeamsAndUsers()
      this.$forceUpdate()
    },

    triggerAuditValidate(auditLevel, type) {
      if (this.$refs.teamFormRef) {
        this.$refs.teamFormRef.validateField(`audit${auditLevel}${type}`)
      }
      this.updateSelectedTeamsAndUsers()
    },

    async getDatasetSelectList() {
      try {
        const res = await getDatasetSelectListAPI({ datasetName: this.datasetName })
        if (res.code === 200 && res.data) {
          this.datasetList = res.data
        }
      } catch (error) {
        this.$modal.msgError('获取数据集下拉选列表失败：' + error.message)
      }
    },

    async getDatasetVersionSelectList() {
      try {
        const res = await getDatasetVersionSelectListAPI({ datasetId: this.form.datasetId })
        if (res.code === 200 && res.data) {
          this.versionList = res.data
        }
      } catch (error) {
        this.$modal.msgError('获取数据集版本下拉选列表失败：' + error.message)
      }
    },

    async getLabelTreeList() {
      try {
        const res = await getLabelTreeListAPI()
        if (res.code === 200 && res.data) {
          console.log('res.data')
          this.labelTreeData = this.formatTreeData(res.data)
        }
      } catch (error) {
        this.$modal.msgError('获取标签树形数据失败：' + error.message)
      }
    },

    // 格式化树形数据
    formatTreeData(data, isRoot = true) {
      return data.map(node => {
        const formatNode = { ...node }
        // 为根节点的id添加father_前缀
        if (isRoot) {
          formatNode.id = `father_${formatNode.id}`
        }
        if (formatNode.children && formatNode.children.length > 0) {
          // 递归处理子节点，标记为非根节点
          formatNode.children = this.formatTreeData(formatNode.children, false)
        }
        return formatNode
      })
    },

    handleTreeCheckChange(node, checked, indeterminate) {
      console.log('node',node)
      if (indeterminate === false) {
        const getAllChildIds = (treeNode) => {
          let ids = []
          if (treeNode.children && treeNode.children.length > 0) {
            treeNode.children.forEach(child => {
              ids = [...ids, child.id, ...getAllChildIds(child)]
            })
          }
          return ids
        }
        const getAllChildNames = (treeNode) => {
          let names = []
          if (treeNode.children && treeNode.children.length > 0) {
            treeNode.children.forEach(child => {
              names = [...names, child.label, ...getAllChildNames(child)]
            })
          }
          return names
        }

        let currentNodeIds = []
        let currentNodeNames = []

        if (node.children && node.children.length > 0) {
          currentNodeIds = getAllChildIds(node)
          currentNodeNames = getAllChildNames(node)
        } else {
          currentNodeIds = [node.id]
          currentNodeNames = [node.label]
        }

        console.log('currentNodeIds',currentNodeIds)
        console.log('currentNodeNames',currentNodeNames)


        if (checked) {
          currentNodeIds.forEach(id => {
            if (!this.form.labelId.includes(id)) {
              this.form.labelId.push(id)
            }
          })
          currentNodeNames.forEach(name => {
            if (!this.form.labelName.includes(name)) {
              this.form.labelName.push(name)
            }
          })
        } else {
          this.form.labelId = this.form.labelId.filter(id => !currentNodeIds.includes(id))
          this.form.labelName = this.form.labelName.filter(name => !currentNodeNames.includes(name))
        }

        this.form.labelId = [...this.form.labelId]
        this.form.labelName = [...this.form.labelName]
      }
    },

    // 删除单个标签
    handleTagRemove(removedName) {
      const findIdByName = (treeData, name) => {
        for (const node of treeData) {
          if (node.label === name) return node.id
          if (node.children) {
            const childId = findIdByName(node.children, name)
            if (childId) return childId
          }
        }
        return null
      }
      const removedId = findIdByName(this.labelTreeData, removedName)
      if (removedId) {
        this.$refs.labelTree.setChecked(removedId, false)
        this.form.labelId = this.form.labelId.filter(id => id !== removedId)
        this.form.labelName = this.form.labelName.filter(name => name !== removedName)
        this.form.labelId = [...this.form.labelId]
        this.form.labelName = [...this.form.labelName]
      }
    },

    // select清空
    handleSelectClear() {
      this.$refs.labelTree.setCheckedKeys([])
      this.form.labelId = []
      this.form.labelName = []
    },

    async initData() {
      try {
        const res = await getDatasetSelectListAPI({})
        if (res.code === 200 && res.data) {
          this.datasetList = res.data
        }
      } catch (error) {
        this.$modal.msgError('获取数据集列表失败：' + error.message)
      }

      // 初始化时不再默认获取所有用户，改为按需加载
      this.userList = {}
    },

    async getTaskDetail() {
      try {
        const res = await getLabelingTaskDetailAPI({
          labelingTaskId: this.labelingTaskId
        })
        if (res.code === 200 && res.data) {
          const data = res.data
          console.log('data',data)
          // 处理时间范围
          let timeArray = []
          if (data.labelingTaskTime) {
            timeArray = data.labelingTaskTime.split('至')
          }

          // 第一步：先暂存版本ID，避免被watch清空
          const tempVersionId = data.datasetVersionId || ''

          // 第二步：先赋值datasetId，触发版本列表加载
          this.form = {
            labelingTaskId: data.labelingTaskId || '',
            labelingTaskName: data.labelingTaskName || '',
            datasetId: data.datasetId || '', // 先赋值datasetId
            datasetVersionId: '', // 先置空，避免提前赋值
            datasetVersion: data.datasetVersion || '',
            datasetName: data.datasetName || '',
            labelId: data.labelId ? data.labelId.split(',').map(Number) : [],
            labelName: data.labelName ? data.labelName.split(',') : [],
            labelingTaskTimeArray: timeArray,
            labelingTaskTime: data.labelingTaskTime || '',
            labelingTaskAuditProcess: data.labelingTaskAuditProcess || '',
            labelingTaskPassState: data.labelingTaskPassState || '',
            labelingTaskAuditRemark: data.labelingTaskAuditRemark || ''
          }

          // 第三步：手动加载版本列表并赋值版本ID
          if (this.form.datasetId) {
            await this.getDatasetVersionSelectList() // 手动加载版本列表
            // 版本列表加载完成后，赋值版本ID
            this.form.datasetVersionId = tempVersionId
            // 设置样本数量
            const selectedVersion = this.versionList.find(item => item.datasetVersionId === tempVersionId)
            this.sampleCount = selectedVersion?.sampleCount || 0
          }

          this.$nextTick(() => {
            this.$refs.labelTree.setCheckedKeys(this.form.labelId)
          })

          this.$nextTick(() => {
            this.updateSelectedTeamsAndUsers()
          })
        }
      } catch (error) {
        this.$modal.msgError('获取任务详情失败：' + error.message)
      }
    },

    async getAuditDetail() {
      try {
        const res = await getLabelingTaskDetailAPI({
          labelingTaskId: this.labelingTaskId
        })
        if (res.code === 200 && res.data) {
          const data = res.data
          this.auditPersonList = data.auditPersonList || []

          // 1. 拆分标注/审核人员
          const labelPersonList = this.auditPersonList.filter(item => item.auditNode === '0')
          const auditPersonGroup = _.groupBy(this.auditPersonList.filter(item => item.auditNode !== '0'), 'auditNode')
          console.log('auditPersonList',labelPersonList)


          this.$set(this.teamForm, 'labelTeamName', labelPersonList.length > 0 ? labelPersonList[0].teamId : '')
          this.$set(this.teamForm, 'labelUserTableData', labelPersonList.map((item, index) => ({
            serialNo: index + 1,
            userId: item.userId,
            userName: item.userName || '',
            roleName: item.roleName,
            teamId: item.teamId,
            teamName: item.teamName || '',
            dataCount: Number(item.labelingNum ?? 0),
            auditedUserId: '',
          })))

          console.log('teamForm',this.teamForm)


          // 3. 初始化审核层级数据（保留名称）
          const auditLevel = Number(this.form.labelingTaskAuditProcess)
          for (let i = 1; i <= auditLevel; i++) {
            const currentAuditPersons = auditPersonGroup[i] || []
            this.$set(this.teamForm, `audit${i}TeamName`, currentAuditPersons.length > 0 ? currentAuditPersons[0].teamId : '')
            this.$set(this.teamForm, `audit${i}Users`, currentAuditPersons.map(item => item.userId))
            this.$set(this.teamForm, `audit${i}Type`, currentAuditPersons.length > 0 ? (currentAuditPersons[0].auditType === '2' ? 'count' : 'user') : '')
            // 保留审核人员名称，避免显示ID
            this.$set(this.teamForm, `audit${i}TableData`, currentAuditPersons.map((item, index) => ({
              serialNo: index + 1,
              userId: item.userId,
              userName: item.userName || '', // 关键：保留名称
              roleName: item.roleName,
              teamId: item.teamId,
              teamName: item.teamName || '',
              dataCount: item.auditNum || 0,
              auditedUserId: item.auditee || '',
              prevAuditedUserId: item.auditee || ''
            })))
            // 同步已选被审核人员
            const selectedAuditedIds = currentAuditPersons.map(row => row.auditee).filter(id => id)
            this.$set(this.selectedAuditedUsers, `audit${i}`, selectedAuditedIds)
          }

          // 4. 提前加载团队人员列表（避免下拉框显示ID）
          const allTeamIds = [
            this.teamForm.labelTeamName,
            ...Array.from({ length: auditLevel }, (_, i) => this.teamForm[`audit${i + 1}TeamName`])
          ].filter(Boolean)
          // 批量加载所有团队的人员列表
          for (const teamId of allTeamIds) {
            await this.initPersonList(teamId, teamId === this.teamForm.labelTeamName ? 'label' : 'audit', allTeamIds.indexOf(teamId))
          }

          this.$nextTick(() => {
            this.updateSelectedTeamsAndUsers()
          })
        }
      } catch (error) {
        this.$modal.msgError('获取任务详情失败：' + error.message)
      }
    },

    async goToNextStep() {
      this.$refs.basicForm.validate(async (valid) => {
        if (valid) {
          if (Array.isArray(this.form.labelingTaskTimeArray) && this.form.labelingTaskTimeArray.length === 2) {
            this.form.labelingTaskTime = this.form.labelingTaskTimeArray.join('至')
          }

          if (this.isEdit) {
            await this.getAuditDetail() // 加载历史数据
            // 关键：先恢复labelers，再加载人员列表
            this.teamForm.labelers = this.auditPersonList
              .filter(item => item.auditNode === '0')
              .map(item => item.userId)
          }

          this.activeStep = 2
          await this.$nextTick()

          this.initTeamRules()
          if (this.form.labelingTaskAuditProcess && !this.isEdit) {
            this.handleAuditProcessChange(this.form.labelingTaskAuditProcess)
          }

          if (this.isEdit) {
            // 加载人员列表（此时labelers已恢复，不会清空）
            if (this.teamForm.labelTeamName) {
              await this.initPersonList(this.teamForm.labelTeamName, 'label')
              // 注释掉：已提前恢复labelers，无需重复执行
              // this.teamForm.labelers = this.auditPersonList.filter(...).map(...)
              this.syncLabelUserTableData()
            }
            const auditLevel = Number(this.form.labelingTaskAuditProcess)
            for (let i = 1; i <= auditLevel; i++) {
              const teamId = this.teamForm[`audit${i}TeamName`]
              if (teamId) {
                await this.initPersonList(teamId, 'audit', i)
                this.teamForm[`audit${i}Users`] = this.auditPersonList
                  .filter(item => item.auditNode === `${i}`)
                  .map(item => item.userId)
                this.syncAuditUserTableData(i)
              }
            }
          }
        }
      })
    },

    handleBack() {
      if (this.activeStep === 2) {
        this.activeStep = 1
        this.teamRules = {}
        this.teamForm = {
          leader: '',
          labelTeamName: '',
          labelers: [],
          labelUserTableData: []
        }
        this.selectedTeams = []
        this.selectedUsers = []
        this.selectedAuditedUsers = {}
        this.userList = {} // 清空人员列表
        this.auditPersonList = [] // 清空审核人员列表
      } else {
        const obj = { path: "/data/labeling" }
        this.$tab.closeOpenPage(obj)
      }
    },

    submitBack() {
      const obj = { path: "/data/labeling" }
      this.$tab.closeOpenPage(obj)
    },

    async submitForm() {
      this.isSubmitting = true

      try {
        if (!this.$refs.teamFormRef) return

        // 先校验被审核人员完整性
        const auditLevel = Number(this.form.labelingTaskAuditProcess)
        let isAuditUserValid = true

        for (let i = 1; i <= auditLevel; i++) {
          if (this.teamForm[`audit${i}Type`] === 'user' && !this.checkAuditUserComplete(i)) {
            this.$message.error(`审核${i}的被审核人员未包含所有标注人员，请补充选择`)
            isAuditUserValid = false
            break
          }
        }

        if (!isAuditUserValid) {
          this.isSubmitting = false
          return
        }

        this.$refs.teamFormRef.validate(async (valid) => {
          if (!valid) {
            this.isSubmitting = false
            return
          }

          // 校验数据量总和规则
          const isDataCountValid = this.validateDataCountTotal()
          if (!isDataCountValid) {
            this.isSubmitting = false
            return
          }

          this.$loading({
            lock: true,
            text: '提交中，请稍候...',
            background: 'rgba(0,0,0,0.5)'
          })

          try {
            // 转换时间格式
            if (Array.isArray(this.form.labelingTaskTimeArray) && this.form.labelingTaskTimeArray.length === 2) {
              this.form.labelingTaskTime = this.form.labelingTaskTimeArray.join('至')
            }

            // 整理审核表单数据
            const auditFormData = {}
            const auditLevel = Number(this.form.labelingTaskAuditProcess)
            for (let i = 1; i <= auditLevel; i++) {
              auditFormData[`audit${i}TeamName`] = this.teamForm[`audit${i}TeamName`]
              auditFormData[`audit${i}Users`] = this.teamForm[`audit${i}Users`].join(',')
              auditFormData[`audit${i}Type`] = this.teamForm[`audit${i}Type`]
              auditFormData[`audit${i}TableData`] = JSON.stringify(this.teamForm[`audit${i}TableData`])
            }

            // 整理审核人员列表（含团队信息）
            const auditPersonList = []
            for (let i = 1; i <= auditLevel; i++) {
              const tableData = this.teamForm[`audit${i}TableData`] || []
              tableData.forEach(row => {
                // 查找团队信息
                const team = this.teamList.find(t => t.teamId === this.teamForm[`audit${i}TeamName`])
                auditPersonList.push({
                  userId: row.userId,
                  userName: row.userName,
                  teamId: this.teamForm[`audit${i}TeamName`],
                  teamName: team?.teamName || row.teamName || '',
                  auditLevel: i,
                  auditedUserId: row.auditedUserId,
                  dataCount: row.dataCount
                })
              })
            }

            const submitData = {
              labelingTaskId: this.form.labelingTaskId,
              labelingTaskName: this.form.labelingTaskName,
              datasetVersionId: this.form.datasetVersionId,
              datasetVersion: this.form.datasetVersion,
              labelId: this.form.labelId.join(','),
              labelName: this.form.labelName.join(','),
              labelingTaskTime: this.form.labelingTaskTime, // 传递字符串格式
              labelingTaskAuditProcess: this.form.labelingTaskAuditProcess,
              labelingTaskPassState: this.form.labelingTaskPassState,
              labelingTaskAuditRemark: this.form.labelingTaskAuditRemark,
              leaderId: this.teamForm.leader,
              labelTeamName: this.teamForm.labelTeamName,
              labelerIds: this.teamForm.labelers.join(','),
              labelUserTableData: JSON.stringify(this.teamForm.labelUserTableData),
              auditFormData: JSON.stringify(auditFormData),
              auditorIds: this.teamForm.auditors ? this.teamForm.auditors.join(',') : '',
            }

            let res
            if (this.isEdit) {
              console.log('res',submitData)
              res = await editLabelingTaskAPI(submitData)
            } else {
              res = await addLabelingTaskAPI(submitData)
            }

            if (res.code === 200) {
              this.$message.success(this.isEdit ? '编辑成功' : '新增成功')
              this.submitBack()
            } else {
              this.$message.error(res.msg || '操作失败')
            }
          } catch (error) {
            this.$message.error('提交失败：' + error.message)
          } finally {
            this.$loading().close()
            this.isSubmitting = false
          }
        })
      } catch (error) {
        this.isSubmitting = false
        this.$message.error('提交过程出错：' + error.message)
      }
    },

    // 更新已选团队和人员列表
    updateSelectedTeamsAndUsers() {
      const teams = []
      if (this.teamForm.labelTeamName) {
        teams.push(this.teamForm.labelTeamName)
      }
      const auditLevel = Number(this.form.labelingTaskAuditProcess)
      for (let i = 1; i <= auditLevel; i++) {
        const teamId = this.teamForm[`audit${i}TeamName`]
        if (teamId) {
          teams.push(teamId)
        }
      }
      this.selectedTeams = [...new Set(teams)]
      const users = []
      if (Array.isArray(this.teamForm.labelers) && this.teamForm.labelers.length) {
        users.push(...this.teamForm.labelers)
      }
      for (let i = 1; i <= auditLevel; i++) {
        const auditUsers = this.teamForm[`audit${i}Users`]
        if (Array.isArray(auditUsers) && auditUsers.length) {
          users.push(...auditUsers)
        }
      }
      this.selectedUsers = [...new Set(users)]
      this.$forceUpdate()
    },

    // 获取指定审核层级的过滤后团队列表
    getFilteredAuditTeamList(auditLevel) {
      const currentTeam = this.teamForm[`audit${auditLevel}TeamName`]
      const filtered = this.teamList.filter(team => {
        return team.teamId === currentTeam || !this.selectedTeams.includes(team.teamId)
      })
      return filtered
    },

    // 获取指定审核层级的过滤后人员列表
    getFilteredAuditUserList(auditLevel) {
      const currentTeamId = this.teamForm[`audit${auditLevel}TeamName`]
      const currentUsers = this.teamForm[`audit${auditLevel}Users`] || []
      // 修改：获取对应审核团队的人员列表
      const auditTeamUsers = this.userList[currentTeamId] || []

      const filtered = auditTeamUsers.filter(user => {
        return currentUsers.includes(user.userId) || !this.selectedUsers.includes(user.userId)
      })
      return filtered
    }
  },
  watch: {
    'form.datasetVersionId'(newVal) {
      if (newVal) {
        const selectedVersion = this.versionList.find(item => item.datasetVersionId === newVal)
        this.sampleCount = selectedVersion?.sampleCount || 0
      } else {
        this.sampleCount = 0
      }
    },
    'form.datasetId'(newVal) {
      this.versionList = []
      this.form.datasetVersionId = ''
      if (newVal) {
        this.getDatasetVersionSelectList()
      }
    },
    'teamForm.labelTeamName'(newVal) {
      if (newVal) {
        this.teamForm.labelUserTableData = []
        this.teamForm.labelers = []
        this.initPersonList(newVal, 'label')
      } else {
        this.userList = {} // 清空所有团队人员列表
        this.teamForm.labelers = []
        this.teamForm.labelUserTableData = []
      }
      this.updateSelectedTeamsAndUsers()
    },
    // 监听团队表单变化
    'teamForm': {
      handler() {
        this.updateSelectedTeamsAndUsers()
      },
      deep: true,
      immediate: true
    },
    // 监听时间数组变化，同步更新字符串格式
    'form.labelingTaskTimeArray': {
      handler(newVal) {
        if (Array.isArray(newVal) && newVal.length === 2) {
          this.form.labelingTaskTime = newVal.join('至')
        } else {
          this.form.labelingTaskTime = ''
        }
      },
      immediate: true
    }
  },
  computed: {
    // 判断标注信息是否填写完成（用于禁用审核模块下拉框）
    isLabelInfoCompleted() {
      return !!this.teamForm.labelTeamName && Array.isArray(this.teamForm.labelers) && this.teamForm.labelers.length > 0
    },
    labelUserTableData() {
      return this.teamForm.labelUserTableData
    },
    labelTotalCount() {
      return this.getLabelTotalCount()
    },
    filteredLabelTeamList() {
      const currentTeam = this.teamForm.labelTeamName
      const filtered = this.teamList.filter(team => {
        return team.teamId === currentTeam || !this.selectedTeams.includes(team.teamId)
      })
      return filtered
    },
    filteredLabelUserList() {
      const currentTeamId = this.teamForm.labelTeamName
      const currentUsers = this.teamForm.labelers || []
      // 修改：从对应标注团队的人员列表中过滤
      const labelTeamUsers = this.userList[currentTeamId] || []

      const filtered = labelTeamUsers.filter(user => {
        return currentUsers.includes(user.userId) || !this.selectedUsers.includes(user.userId)
      })
      return filtered
    },
    filteredLeaderUserList() {
      const currentLeader = this.teamForm.leader
      const filtered = this.userList.filter(user => {
        return user.userId === currentLeader || !this.selectedUsers.includes(user.userId)
      })
      return filtered
    },
    labeledUserList() {
      if (!Array.isArray(this.teamForm.labelers) || this.teamForm.labelers.length === 0) {
        return []
      }
      const labelTeamUsers = this.userList[this.teamForm.labelTeamName] || []
      return labelTeamUsers.filter(user => {
        return this.teamForm.labelers.includes(user.userId)
      })
    }
  }
}
</script>

<style scoped lang="scss">
.labeling-task-form-container {
  background: #fff;
  padding: 0;
  min-height: calc(100vh - 84px);
  border: none;
  width: 100%;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 16px 24px;
  border-bottom: 1px solid #ebeef5;
  gap: 12px;
  width: 100%;

  .back-btn {
    background: #fff;
    border: 1px solid #dcdfe6;
    color: #666;
    padding: 6px 12px;
    width: 80px;
    height: 32px;
    border-radius: 4px;
  }

  .next-btn {
    width: 80px;
    height: 32px;
    background: #1f72ea;
    border: none;
    border-radius: 4px;
  }
}

.progress-steps {
  display: flex;
  align-items: center;
  padding: 24px;
  margin-left: 20px;
  width: 100%;
  box-sizing: border-box;

  .step-item {
    display: flex;
    flex-direction: column;
    align-items: center;

    .step-dot {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: #e5e6eb;
      color: #999;
      text-align: center;
      line-height: 32px;
      font-size: 14px;
      margin-bottom: 8px;

      &.active {
        background: #1f72ea;
        color: #fff;
      }
    }

    .step-text {
      font-size: 14px;
      color: #666;
    }
  }

  .step-line {
    flex: 1;
    height: 2px;
    background: #1f72ea;
    margin: 0 16px;
    max-width: calc(100% - 200px);
  }
}

.form-container {
  padding: 0 24px 24px;
  width: 100%;
  box-sizing: border-box;

  .form-step {
    background: #f9f9f9;
    padding: 24px;
    border-radius: 4px;
    width: 100%;
    box-sizing: border-box;

    .form-title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 24px;
      display: flex;
      align-items: center;

      &::before {
        content: '';
        display: inline-block;
        width: 4px;
        height: 16px;
        background: #1f72ea;
        margin-right: 8px;
      }
    }
  }

  .basic-form, .team-form {
    width: 100%;
    box-sizing: border-box;

    .el-form-item {
      margin-bottom: 24px;
      width: 100%;
      box-sizing: border-box;

      ::v-deep .el-form-item__label {
        color: #333;
        font-weight: 400;
        text-align: left;
        padding: 0 0 8px 0;
        line-height: 1.4;
        width: 100%;
        display: block;
      }

      &.has-clear {
        position: relative;
        width: 100%;

        ::v-deep .el-input,
        ::v-deep .el-select,
        ::v-deep .el-date-picker {
          width: 100%;
          box-sizing: border-box;

          .el-select__wrapper, .el-input__inner {
            padding-right: 35px !important;
            height: 36px !important;
            border-radius: 4px;
            border: 1px solid #dcdfe6;
            width: 100%;
            box-sizing: border-box;
          }
        }

        .clear-icon {
          position: absolute;
          right: 20px;
          top: 50px;
          transform: translateY(-50%);
          color: #c0c4cc;
          cursor: pointer;
          font-size: 14px;
          z-index: 1;

          &:hover {
            color: #909399;
          }
        }
      }

      ::v-deep .label-tree {
        padding: 10px;
        max-height: 300px;
        overflow-y: auto;
        width: 100%;
        box-sizing: border-box;
      }

      .form-input, .form-select, .form-datepicker {
        width: 100%;
        box-sizing: border-box;
        border-radius: 4px;
      }
    }
  }

  // 审核模块样式
  .audit-section {
    margin-bottom: 30px;
    width: 100%;
    box-sizing: border-box;

    .section-title {
      font-size: 15px;
      font-weight: 500;
      color: #333;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 1px solid #ebeef5;
      width: 100%;
      display: block;
    }

    .section-form-row {
      margin-bottom: 16px;
      width: 100%;
      box-sizing: border-box;
    }

    // 被审核人员完整性提示
    .audit-user-check-tip {
      padding: 8px 12px;
      border-radius: 4px;
      margin-bottom: 12px;
      font-size: 14px;
      background-color: #f0f9ff;
      color: #1f72ea;

      &.tip-error {
        background-color: #fef0f0;
        color: #f56c6c;
      }

      .el-icon-warning {
        margin-right: 6px;
      }
    }

    // 样本总数提示
    .sample-count-tip {
      color: #666;
      margin-bottom: 12px;
      font-size: 14px;
      .count-num {
        color: #1f72ea;
        font-weight: 500;
        margin: 0 4px;
      }
    }

    // 数据量汇总提示
    .data-count-summary {
      margin-top: 12px;
      font-size: 14px;
      color: #666;
      .count-error {
        color: #f56c6c;
        font-weight: 500;
      }
      .summary-error-tip {
        color: #f56c6c;
        margin-left: 8px;
        font-size: 13px;
      }
    }

    // 表格样式
    .audit-table {
      width: 100% !important;
      margin-bottom: 10px;
      box-sizing: border-box;

      ::v-deep {
        .el-table__header {
          width: 100% !important;

          th {
            background-color: #f8f9fa;
            color: #333;
            font-weight: 500;
            width: auto !important;
            padding: 12px 0;
            text-align: center;
          }
        }

        .el-table__body {
          width: 100% !important;

          td {
            padding: 8px 0;
            text-align: center;
            width: auto !important;
          }
        }

        .el-table__empty-block {
          min-height: 80px;
          width: 100% !important;
        }

        .el-table__cell {
          padding: 0;
          text-align: center;
          box-sizing: border-box;
        }

        .el-table__header-wrapper,
        .el-table__body-wrapper {
          width: 100% !important;
          overflow: hidden !important;
        }

        .el-table--border {
          border-right: 1px solid #ebeef5;
          border-bottom: 1px solid #ebeef5;
        }

        .el-table--border th.gutter:last-of-type {
          display: none !important;
          width: 0 !important;
        }

        .error-tip {
          color: #f56c6c;
          font-size: 12px;
          margin-left: 4px;
        }
      }
    }
  }
}

::v-deep .el-table-column {
  width: auto !important;
  flex: 1;
  min-width: 80px;
}

@media (max-width: 1200px) {
  .progress-steps .step-line {
    max-width: calc(100% - 150px);
  }
}
</style>
