<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 < 3"
        type="primary"
        @click="goToNextStep"
        class="next-btn"
      >下一步</el-button>
    </div>

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

    <!-- 表单容器：确保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"
          label-position="top"
          label-width="100%"
          class="basic-form"
          disabled
        >
          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item label="标注任务名称" prop="labelingTaskName">
                <el-input
                  v-model="form.labelingTaskName"
                  placeholder="无"
                  class="form-input"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="数据集名称" prop="datasetId">
                <el-select
                  v-model="form.datasetName"
                  placeholder="无"
                  class="form-select"
                  disabled
                >
                  <el-option :label="form.datasetName" :value="form.datasetId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="数据集版本" prop="datasetVersionId">
                <el-select
                  v-model="form.datasetVersion"
                  placeholder="无"
                  class="form-select"
                  disabled
                >
                  <el-option :label="form.datasetVersion" :value="form.datasetVersionId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="标签名称" prop="labelId">
                <el-select
                  v-model="form.labelName"
                  placeholder="无"
                  multiple
                  class="form-select"
                  style="width: 100%"
                  disabled
                >
                  <el-option
                    v-for="(name, index) in (form.labelName || [])"
                    :key="index"
                    :label="name"
                    :value="name"
                  ></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">
                <el-input
                  v-model="form.labelingTaskTime"
                  placeholder="无"
                  class="form-datepicker"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="审核流程" prop="labelingTaskAuditProcess">
                <el-select
                  v-model="form.labelingTaskAuditProcessText"
                  placeholder="无"
                  class="form-select"
                  disabled
                >
                  <el-option
                    :label="form.labelingTaskAuditProcessText"
                    :value="form.labelingTaskAuditProcess"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否允许未过审数据" prop="labelingTaskPassState">
                <el-select
                  v-model="form.labelingTaskPassStateText"
                  placeholder="无"
                  class="form-select"
                  disabled
                >
                  <el-option
                    :label="form.labelingTaskPassStateText"
                    :value="form.labelingTaskPassState"
                  ></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="无"
                  :autosize="{ minRows: 3, maxRows: 5 }"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 第二步：团队人员信息（仅回显） -->
      <div v-show="activeStep === 2" class="form-step">
        <div class="form-title">团队人员信息</div>
        <el-form
          :model="teamForm"
          label-position="top"
          label-width="100%"
          class="team-form"
          disabled
        >
          <!-- 标注人员模块 -->
          <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">
                  <el-select
                    v-model="teamForm.labelTeamNameText"
                    placeholder="无"
                    class="form-select"
                    disabled
                  >
                    <el-option :label="teamForm.labelTeamNameText" :value="teamForm.labelTeamName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="人员名称" prop="labelers">
                  <el-select
                    v-model="teamForm.labelersText"
                    placeholder="无"
                    multiple
                    class="form-select"
                    disabled
                  >
                    <el-option
                      v-for="(name, index) in (teamForm.labelersText || [])"
                      :key="index"
                      :label="name"
                      :value="name"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 标注人员表格 -->
            <el-table :data="teamForm.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="0"
                    type="number"
                    disabled
                  ></el-input>
                </template>
              </el-table-column>
            </el-table>
            <!-- 标注数据量汇总 -->
            <div class="data-count-summary" v-if="(teamForm.labelUserTableData || []).length > 0">
              标注数据量总和：<span>{{ labelTotalCount }}</span>
            </div>
          </div>

          <!-- 动态渲染审核模块（审核1、审核2、审核3...） -->
          <div
            v-for="(auditLevel, index) in Array.from({ length: form.labelingTaskAuditProcess ? Number(form.labelingTaskAuditProcess) : 0 }, (_, i) => i + 1)"
            :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`">
                  <el-select
                    v-model="teamForm[`audit${auditLevel}TeamNameText`]"
                    placeholder="无"
                    class="form-select"
                    disabled
                  >
                    <el-option
                      :label="teamForm[`audit${auditLevel}TeamNameText`] || ''"
                      :value="teamForm[`audit${auditLevel}TeamName`] || ''"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="`人员名称`" :prop="`audit${auditLevel}Users`">
                  <el-select
                    v-model="teamForm[`audit${auditLevel}UsersText`]"
                    placeholder="无"
                    multiple
                    class="form-select"
                    disabled
                  >
                    <el-option
                      v-for="(name, index) in (teamForm[`audit${auditLevel}UsersText`] || [])"
                      :key="index"
                      :label="name"
                      :value="name"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="`审核方式`" :prop="`audit${auditLevel}Type`">
                  <el-select
                    v-model="teamForm[`audit${auditLevel}TypeText`]"
                    placeholder="无"
                    class="form-select"
                    disabled
                  >
                    <el-option
                      :label="teamForm[`audit${auditLevel}TypeText`] || ''"
                      :value="teamForm[`audit${auditLevel}Type`] || ''"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 审核人员表格 -->
            <el-table
              :data="teamForm[`audit${auditLevel}TableData`] && Array.isArray(teamForm[`audit${auditLevel}TableData`]) ? 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.auditedUserName"
                    placeholder="无"
                    class="form-select"
                    style="width: 100%"
                    disabled
                  >
                    <el-option :label="scope.row.auditedUserName || ''" :value="scope.row.auditedUserId || ''"></el-option>
                  </el-select>
                  <el-input
                    v-else
                    v-model="scope.row.dataCount"
                    placeholder="0"
                    type="number"
                    style="width: 100%"
                    disabled
                  ></el-input>
                </template>
              </el-table-column>
            </el-table>
            <!-- 审核数据量汇总（仅审核方式为数量时显示） -->
            <div
              class="data-count-summary"
              v-if="(teamForm[`audit${auditLevel}TableData`] && teamForm[`audit${auditLevel}TableData`].length > 0) && teamForm[`audit${auditLevel}Type`] === 'count'"
            >
              审核{{ auditLevel }}数据量总和：<span>{{ getAuditTotalCount(auditLevel) }}</span>
            </div>
          </div>
        </el-form>
      </div>

      <!-- 第三步：标注信息 -->
      <div v-show="activeStep === 3" class="form-step">
        <div class="form-title">标注信息</div>
        <!-- 标注样本表格（仅展示，无查询/操作按钮） -->
        <div class="table-container">
          <TableModel
            :showSearch="false"
            :showBtnCrews="false"
            :showshowQueryButtons="false"
            :formLabel="[]"
            :showOperation="false"
            :showRightTools="false"
            :handleShow="false"
            ref="sampleTableRef"
            :columnsList="columnsList"
            :request-api="labelingListAPI"
            :sendParams="sendParams"
            :handleColWidth="0"
          >
            <!-- 自定义列：标注状态 -->
            <template slot="labelingStatus" slot-scope="{ data }">
              <span>{{ getStatusText('labelingStatus', data.labelingStatus) }}</span>
            </template>

            <!-- 自定义列：审核状态 -->
            <template slot="auditStatus" slot-scope="{ data }">
              <span>{{ getStatusText('auditStatus', data.auditStatus) }}</span>
            </template>
          </TableModel>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script>
import _ from 'lodash'
import TableModel from '@/components/TableModel2'
import {
  getLabelingTaskDetailAPI,
  labelingListAPI
} from '@/api/data/labeling'
import { listTeamAPI } from '@/api/system/team'
import { getDatasetVersionSelectListAPI } from '@/api/data/dataset'
import { getLabelTreeListAPI } from '@/api/data/labeling'
import { listUser } from '@/api/system/user'
import { decryptWithSM4 } from '@/utils/sm'

// 表格列配置（移除无效数据列，仅保留核心列）
const columnsList = [
  { t_props: 'fileName', t_label: '文件名称', t_width: 400 },
  { t_props: 'labelingPerson', t_label: '标注人员', t_width: 270 },
  { t_props: 'labelingStatus', t_label: '标注状态', t_width: 270, t_slot: 'labelingStatus' },
  { t_props: 'auditPerson', t_label: '审核人员', t_width: 340 },
  { t_props: 'auditStatus', t_label: '审核状态', t_width: 200, t_slot: 'auditStatus' }
];

// 状态字典
const statusDict = {
  labelingStatus: {
    '0': '未标注',
    '1': '已标注',
  },
  auditStatus: {
    '0': '未审核',
    '1': '审核中',
    '2': '已通过',
    '3': '未通过'
  }
};

export default {
  name: 'LabelingTaskDetail',
  components: { TableModel },
  data() {
    return {
      labelingTaskId: this.convertToNumber(decryptWithSM4(this.$route.query.labelingTaskId || '')),
      sampleCount: 0,
      activeStep: 1,
      // 基础信息表单
      form: {
        labelingTaskId: '',
        labelingTaskName: '',
        datasetId: '',
        datasetVersionId: '',
        labelId: [],
        labelName: [],
        labelingTaskTime: '',
        labelingTaskAuditProcess: '',
        labelingTaskAuditProcessText: '', // 审核流程文本（回显用）
        labelingTaskPassState: '',
        labelingTaskPassStateText: '', // 是否允许未过审数据文本（回显用）
        labelingTaskAuditRemark: '',
        datasetVersion: '',
        datasetName: ''
      },
      // 团队表单：仅用于回显（提前初始化所有可能的动态属性）
      teamForm: {
        labelTeamName: '',
        labelTeamNameText: '', // 团队名称文本
        labelers: [],
        labelersText: [], // 人员名称文本
        labelUserTableData: []
      },
      // 审核人员列表（回显用）
      auditPersonList: [],
      versionList: [],
      userList: {}, // 存储不同团队的人员列表
      teamList: [], // 团队列表
      labelTreeData: [],
      treeProps: {
        children: 'children',
        label: 'label',
        value: 'id'
      },
      // 第三步：标注信息表格配置
      columnsList,
      labelingListAPI,
      sendParams: {
        labelingTaskId: '' // 标注任务ID
      }
    }
  },
  created() {
    // 初始化任务ID
    this.sendParams.labelingTaskId = this.labelingTaskId
    // 获取基础数据
    this.getLabelTreeList()
    this.getTeamSelectList()
    // 获取任务详情
    this.getTaskDetail()
  },
  methods: {
    convertToNumber(value) {
      if (!value || value === '' || value === 'undefined' || value === 'null') {
        return '';
      }
      const num = Number(value);
      return isNaN(num) ? '' : num;
    },

    // 获取团队列表（回显用）
    async getTeamSelectList() {
      try {
        const res = await listTeamAPI({})
        if (res.code === 200) {
          this.teamList = res.rows
        }
      } catch (error) {
        this.$modal.msgError("获取团队列表失败：" + error)
      }
    },

    // 获取数据集版本列表（回显用）
    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) {
          this.labelTreeData = this.formatTreeData(res.data)
        }
      } catch (error) {
        this.$modal.msgError('获取标签树形数据失败：' + error.message)
      }
    },

    // 格式化树形数据
    formatTreeData(data) {
      return data.map(node => {
        const formatNode = { ...node }
        if (formatNode.children && formatNode.children.length > 0) {
          formatNode.children = this.formatTreeData(formatNode.children)
        }
        return formatNode
      })
    },

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

    // 获取指定层级审核数据量总和
    getAuditTotalCount(auditLevel) {
      // 增强空值保护
      const tableData = this.teamForm[`audit${auditLevel}TableData`] && Array.isArray(this.teamForm[`audit${auditLevel}TableData`])
        ? this.teamForm[`audit${auditLevel}TableData`]
        : []
      return tableData.reduce((sum, item) => {
        return sum + (Number(item?.dataCount) || 0) // 保护item.dataCount
      }, 0)
    },

    // 获取状态文本
    getStatusText(type, value) {
      return statusDict[type][value] || '/'
    },

    // 初始化审核层级数据（关键修复：提前初始化空数组）
    initAuditLevelData(auditLevel) {
      for (let i = 1; i <= auditLevel; i++) {
        // 初始化所有审核层级的属性为空值，避免访问undefined
        this.$set(this.teamForm, `audit${i}TeamName`, '')
        this.$set(this.teamForm, `audit${i}TeamNameText`, '')
        this.$set(this.teamForm, `audit${i}Users`, [])
        this.$set(this.teamForm, `audit${i}UsersText`, [])
        this.$set(this.teamForm, `audit${i}Type`, '')
        this.$set(this.teamForm, `audit${i}TypeText`, '')
        this.$set(this.teamForm, `audit${i}TableData`, [])
      }
    },

    // 加载审核详情（仅回显）
    async getAuditDetail() {
      try {
        const res = await getLabelingTaskDetailAPI({
          labelingTaskId: this.labelingTaskId
        })
        if (res.code === 200 && res.data) {
          const data = res.data
          this.auditPersonList = data.auditPersonList || []

          // 先初始化审核层级数据
          const auditLevel = Number(this.form.labelingTaskAuditProcess)
          this.initAuditLevelData(auditLevel)

          // 1. 处理标注人员回显
          const labelPersonList = this.auditPersonList.filter(item => item.auditNode === '0')
          this.$set(this.teamForm, 'labelTeamName', labelPersonList.length > 0 ? labelPersonList[0].teamId : '')
          // 匹配团队名称
          const labelTeam = this.teamList.find(t => t.teamId === this.teamForm.labelTeamName)
          this.$set(this.teamForm, 'labelTeamNameText', labelTeam?.teamName || '')
          // 处理标注人员名称
          this.$set(this.teamForm, 'labelers', labelPersonList.map(item => item.userId))
          this.$set(this.teamForm, 'labelersText', labelPersonList.map(item => item.userName || ''))
          // 处理标注人员表格
          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)
          })))

          // 2. 处理审核层级数据回显
          const auditPersonGroup = _.groupBy(this.auditPersonList.filter(item => item.auditNode !== '0'), 'auditNode')

          for (let i = 1; i <= auditLevel; i++) {
            const currentAuditPersons = auditPersonGroup[i] || []
            // 审核团队ID和名称
            this.$set(this.teamForm, `audit${i}TeamName`, currentAuditPersons.length > 0 ? currentAuditPersons[0].teamId : '')
            const auditTeam = this.teamList.find(t => t.teamId === this.teamForm[`audit${i}TeamName`])
            this.$set(this.teamForm, `audit${i}TeamNameText`, auditTeam?.teamName || '')
            // 审核人员ID和名称
            this.$set(this.teamForm, `audit${i}Users`, currentAuditPersons.map(item => item.userId))
            this.$set(this.teamForm, `audit${i}UsersText`, currentAuditPersons.map(item => item.userName || ''))
            // 审核方式（转换为文本）
            const auditType = currentAuditPersons.length > 0 ? (currentAuditPersons[0].auditType === '2' ? 'count' : 'user') : ''
            this.$set(this.teamForm, `audit${i}Type`, auditType)
            this.$set(this.teamForm, `audit${i}TypeText`, auditType === 'count' ? '数量' : '人员')
            // 审核人员表格
            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 || '',
              auditedUserName: item.auditeeName || '' // 被审核人员名称
            })))
          }

          // 3. 加载团队人员列表（用于回显）
          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)
          }
        }
      } catch (error) {
        this.$modal.msgError('获取审核详情失败：' + error.message)
      }
    },

    // 初始化人员列表（仅回显用）
    async initPersonList(teamId) {
      if (!teamId) return

      try {
        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 || ''
            };
          }));
        }
      } catch (error) {
        console.error('获取人员列表失败：', error);
      }
    },

    // 获取任务详情（核心回显逻辑）
    async getTaskDetail() {
      try {
        const res = await getLabelingTaskDetailAPI({
          labelingTaskId: this.labelingTaskId
        })
        if (res.code === 200 && res.data) {
          const data = res.data

          // 1. 基础信息回显
          let timeArray = []
          if (data.labelingTaskTime) {
            timeArray = data.labelingTaskTime.split('至')
          }

          this.form = {
            labelingTaskId: data.labelingTaskId || '',
            labelingTaskName: data.labelingTaskName || '',
            datasetId: data.datasetId || '',
            datasetVersionId: data.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 || '',
            // 转换审核流程为文本
            labelingTaskAuditProcessText: `${data.labelingTaskAuditProcess || 0}级审核`,
            labelingTaskPassState: data.labelingTaskPassState || '',
            // 转换是否允许未过审数据为文本
            labelingTaskPassStateText: data.labelingTaskPassState === '1' ? '是' : '否',
            labelingTaskAuditRemark: data.labelingTaskAuditRemark || ''
          }

          // 2. 获取数据集版本信息
          if (this.form.datasetId) {
            await this.getDatasetVersionSelectList()
            const selectedVersion = this.versionList.find(item => item.datasetVersionId === this.form.datasetVersionId)
            this.sampleCount = selectedVersion?.sampleCount || 0
          }

          // 3. 加载审核详情（确保数据初始化完成后再渲染）
          await this.$nextTick()
          await this.getAuditDetail()

          // 4. 刷新第三步表格数据
          this.$nextTick(() => {
            if (this.$refs.sampleTableRef) {
              this.$refs.sampleTableRef.getTableList()
            }
          })
        }
      } catch (error) {
        this.$modal.msgError('获取任务详情失败：' + error.message)
      }
    },

    // 下一步按钮逻辑
    goToNextStep() {
      if (this.activeStep < 3) {
        this.activeStep += 1
        // 第三步时刷新表格
        if (this.activeStep === 3 && this.$refs.sampleTableRef) {
          this.$refs.sampleTableRef.getTableList()
        }
      }
    },

    // 返回按钮逻辑
    handleBack() {
      if (this.activeStep > 1) {
        this.activeStep -= 1
      } else {
        const obj = { path: "/data/labeling" }
        this.$tab.closeOpenPage(obj)
      }
    }
  },
  computed: {
    labelTotalCount() {
      return this.getLabelTotalCount()
    }
  },
  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()
      }
    }
  }
}
</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;
          }
        }
      }

      .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;
    }

    // 数据量汇总提示
    .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;
        }
      }
    }
  }

  // 第三步表格容器样式
  .table-container {
    height: calc(100vh - 200px);

    ::v-deep .table-card {
      height: 100% !important;
      border: 1px solid #ebeef5;
      border-radius: 4px;
    }

    // 表格样式优化
    ::v-deep .el-table {
      --el-table-row-hover-bg-color: #f8f9fa;

      .el-table__header th {
        background-color: #f5f7fa;
        color: #333;
        font-weight: 500;
      }

      .el-table__body td {
        color: #666;
      }

      // 序号列居中
      .el-table-column--index {
        text-align: center;
      }
    }

    // 分页样式
    ::v-deep .el-pagination {
      margin-top: 16px;
      text-align: right;

      .el-pagination__total {
        margin-right: 8px;
      }
    }
  }
}

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