<template>
  <ContentWrap v-loading="formLoading">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同名称" prop="contractName">
            <el-select v-model="formData.contractId" placeholder="请选择" @change="getProjectInfo" disabled>
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.contractName"
                :value="item.id"
                clearable
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractCode">
            <el-input v-model="formData.contractCode" placeholder="请输入合同编号" disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="manufacturerId" >
            <el-select
              clearable
              @clear="zzClear"
              v-model="formData.manufacturerId"
              :placeholder="t('deviceForm.mfgHolder')"
              disabled
            >
              <el-option :label="formData.manufactureName" :value="formData.manufacturerId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('project.payment')" prop="payment">
            <el-select v-model="formData.payment" placeholder="请选择" disabled>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PMS_PROJECT_SETTLEMENT)"
                :key="dict.id"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!--
      <el-row>
        <el-col :span="12">
          <el-form-item label="总数" prop="workloadTotal">
            <el-input v-model="formData.workloadTotal" placeholder="请输入工作量总数" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已完成" prop="workloadFinish">
            <el-input v-model="formData.workloadFinish" placeholder="已完成工作量" disabled/>
          </el-form-item>
        </el-col>
      </el-row> -->

      <el-row>
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              style="width: 150%"
              v-model="formData.startTime"
              type="date"
              value-format="x"
              placeholder="选择开始时间"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="完成时间" prop="endTime">
            <el-date-picker
              style="width: 150%"
              v-model="formData.endTime"
              type="date"
              value-format="x"
              placeholder="选择完成时间"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" disabled/>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap v-if="false">
    <div class="content">
      <div class="toolbar">
        <div class="actions">
          <!-- 操作按钮已移动到表单区域 -->
        </div>
      </div>

      <div class="table-container">
        <el-table
          :data="tableData"
          empty-text="暂无数据"
          highlight-current-row
          @current-change="handleRowClick"
        >
          <el-table-column prop="wellName" label="井号" />
          <el-table-column prop="wellType" label="井型">
            <template #default="{ row }">
              {{ getWellTypeLabel(row.wellType) }}
            </template>
          </el-table-column>
          <el-table-column prop="wellCategory" label="井别">
            <template #default="{ row }">
              {{ getWellCategoryLabel(row.wellCategory) }}
            </template>
          </el-table-column>
          <el-table-column prop="location" label="施工地点" />
          <el-table-column :label="t('project.technology')">
            <template #default="{ row }">
              {{ getTechniqueLabel(row.technique) }}
            </template>
          </el-table-column>
          <el-table-column prop="workloadDesign" label="设计工作量" />
          <el-table-column :label="t('project.unit')">
            <template #default="{ row }">
              {{ getWorkloadUnitLabel(row.workloadUnit) }}
            </template>
          </el-table-column>
          <el-table-column prop="deptIds" label="施工队伍" >
            <template #default="{ row }">
              <el-tooltip
                effect="dark"
                :content="getAllDeptNames(row.deptIds)"
                placement="top"
                :disabled="!row.deptIds || row.deptIds.length <= 1"
              >
                <span class="dept-names">
                  {{ getDeptNames(row.deptIds) }}
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="deviceIds" label="施工设备" >
            <template #default="{ row }">
              <el-tooltip
                :content="getAllDeviceNames(row.deviceIds)"
                placement="top"
                :disabled="row.deviceIds && row.deviceIds.length <= 1"
              >
                <span class="device-names">
                  {{ getDeviceNames(row.deviceIds) }}
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="responsiblePerson" label="责任人">
            <template #default="{ row }">
              <el-tooltip
                :content="getAllResponsiblePersonNames(row.responsiblePerson)"
                placement="top"
                :disabled="!row.responsiblePerson || row.responsiblePerson.length <= 1"
              >
                <span class="responsible-names">
                  {{ getResponsiblePersonNames(row.responsiblePerson) }}
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
        </el-table>
      </div>
    </div>
  </ContentWrap>

  <!-- 新增任务详情编辑表单 -->
  <ContentWrap>
    <h3 style="margin-bottom: 20px;">任务详情</h3>
    <el-form
      ref="taskFormRef"
      :model="currentTask"
      :rules="taskFormRules"
      label-width="120px"
      class="task-edit-form"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="井号" prop="wellName">
            <el-input v-model="currentTask.wellName" placeholder="请输入井号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('project.workArea')" prop="location">
            <el-autocomplete
              ref="workAreaAutocomplete"
              v-model="currentTask.location"
              :fetch-suggestions="querySearch"
              :trigger-on-focus="true"
              placeholder="请输入施工区域"
              @focus="handleWorkAreaFocus"
              @select="handleSelect"
              :disabled="!workAreaOptions.length"
              popper-class="work-area-autocomplete"
            >
              <template #prefix>
                <el-icon v-if="loadingWorkAreaOptions" class="is-loading">
                  <Loading />
                </el-icon>
              </template>
            </el-autocomplete>
            <div v-if="!workAreaOptions.length" class="el-form-item__error">
              暂无可用施工区域选项，请手动输入
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('project.technology')" prop="technique">
            <el-select v-model="currentTask.technique"
                       placeholder="请选择施工工艺"
                       clearable
                       :loading="loadingTechnologyOptions"
            >
              <el-option
                v-for="dict in technologyOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <div v-if="!technologyOptions.length && !loadingTechnologyOptions" class="el-form-item__error">
              暂无可用施工工艺选项
            </div>
          </el-form-item>
        </el-col>
        <!--
        <el-col :span="8">
          <el-form-item label="井型" prop="wellType">
            <el-select v-model="currentTask.wellType" placeholder="请选择井型" clearable>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PMS_PROJECT_WELL_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="井别" prop="wellCategory">
            <el-select v-model="currentTask.wellCategory" placeholder="请选择井别" clearable>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PMS_PROJECT_WELL_CATEGORY)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="设计工作量" prop="workloadDesign">
            <el-input v-model="currentTask.workloadDesign" placeholder="请输入设计工作量" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="t('project.unit')" prop="workloadUnit">
            <el-select v-model="currentTask.workloadUnit" placeholder="请选择工作量单位" clearable>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PMS_PROJECT_WORKLOAD_UNIT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="施工队伍" prop="deptIds">
            <el-tree-select
              multiple
              v-model="currentTask.deptIds"
              :data="deptList"
              :props="defaultProps"
              :default-expanded-keys="defaultExpandedKeys"
              check-strictly
              node-key="id"
              filterable
              placeholder="请选择施工队伍"
              clearable
              @visible-change="handleTreeVisibleChange"
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="1"
              class="department-tree-select"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="施工设备" prop="deviceIds">
            <el-button
              @click="openDeviceDialogForForm"
              type="primary"
              size="small"
            >
              选择设备
            </el-button>
            <!--
            <span v-if="currentTask.deviceIds && currentTask.deviceIds.length > 0" style="margin-left: 10px;">
              已选 {{ currentTask.deviceIds.length }} 台设备
            </span> -->
            <el-tooltip
              v-if="currentTask.deviceIds && currentTask.deviceIds.length > 0"
              :content="getAllDeviceNamesForForm(currentTask.deviceIds)"
              placement="top"
            >
            <span style="margin-left: 10px;">
              {{ formatDevicesForForm(currentTask.deviceIds) }}
            </span>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="责任人" prop="responsiblePerson">
            <el-button
              @click="openResponsiblePersonDialogForForm"
              type="primary"
              size="small"
            >
              选择责任人
            </el-button>
            <!--
            <span v-if="currentTask.responsiblePerson && currentTask.responsiblePerson.length > 0" style="margin-left: 10px;">
              已选 {{ currentTask.responsiblePerson.length }} 人
            </span> -->
            <el-tooltip
              v-if="currentTask.responsiblePerson && currentTask.responsiblePerson.length > 0"
              :content="getAllResponsiblePersonNamesForForm(currentTask.responsiblePerson)"
              placement="top"
            >
            <span style="margin-left: 10px;">
              {{ formatResponsiblePersonsForForm(currentTask.responsiblePerson) }}
            </span>
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 动态属性部分 -->
      <el-row v-if="dynamicAttrs.length > 0">
        <el-col v-for="attr in dynamicAttrs" :key="attr.id" :span="attr.dataType === 'textarea' ? 24 : 8">
          <el-form-item
            :label="attr.name + (attr.unit ? `(${attr.unit})` : '')"
            :prop="attr.identifier"
            :rules="getDynamicAttrRules(attr)"
          >
            <!-- 文本类型 -->
            <el-input
              v-if="attr.dataType === 'text'"
              v-model="currentTask[attr.identifier]"
              :placeholder="`请输入${attr.name}`"
            />

            <!-- 文本域类型 -->
            <el-input
              v-else-if="attr.dataType === 'textarea'"
              v-model="currentTask[attr.identifier]"
              :placeholder="`请输入${attr.name}`"
              type="textarea"
              :rows="3"
            />

            <!-- 数字类型 -->
            <el-input
              v-else-if="attr.dataType === 'double'"
              v-model="currentTask[attr.identifier]"
              :placeholder="`请输入${attr.name}`"
              type="number"
              :min="attr.minValue || undefined"
              :max="attr.maxValue || undefined"
            />

            <!-- 日期类型 -->
            <el-date-picker
              v-else-if="attr.dataType === 'date'"
              v-model="currentTask[attr.identifier]"
              type="date"
              value-format="x"
              :placeholder="`选择${attr.name}`"
              style="width: 100%"
            />

            <!-- 默认文本输入 -->
            <el-input
              v-else
              v-model="currentTask[attr.identifier]"
              :placeholder="`请输入${attr.name}`"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="currentTask.remark" placeholder="请输入备注" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <!-- <el-button type="primary" @click="saveTask" :disabled="!currentTask.id && !isNewTask">保存任务</el-button> -->
        <el-button @click="resetTaskForm" v-if="isNewTask">重置</el-button>
        <!--
        <el-button type="danger" @click="deleteCurrentTask" v-if="currentTask.id">删除任务</el-button>
        <el-button @click="addNewTask" v-if="!isNewTask">新增任务</el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-form style="float: right">
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </el-form>
  </ContentWrap>

  <!-- 设备选择对话框 -->
  <el-dialog
    v-model="deviceDialogVisible"
    title="选择施工设备"
    width="1000px"
    :before-close="handleDeviceDialogClose"
    class="device-select-dialog"
  >
    <div class="transfer-container">
      <el-transfer
        v-model="selectedDeviceIds"
        :data="filteredDeviceList"
        :titles="['可选设备', '已选设备']"
        :props="{ key: 'id', label: 'deviceCode' }"
        filterable
        class="transfer-component"
        @change="handleTransferChange"
      >
        <template #default="{ option }">
          <el-tooltip
            effect="dark"
            placement="top"
            :content="`${option.deviceCode || ''} - ${option.deviceName || ''}`"
            :disabled="!option.deviceCode && !option.deviceName"
            transition="fade-in-linear"
          >
        <span class="transfer-option-text">
              {{ option.deviceCode }} - {{ option.deviceName }}
        </span>
          </el-tooltip>
        </template>
      </el-transfer>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleDeviceDialogClose">取消</el-button>
        <el-button type="primary" @click="confirmDeviceSelection">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 责任人选择对话框 -->
  <el-dialog
    v-model="responsiblePersonDialogVisible"
    title="选择责任人"
    width="1000px"
    :before-close="handleResponsiblePersonDialogClose"
    class="responsible-person-select-dialog"
  >
    <div class="transfer-container">
      <el-transfer
        v-model="selectedResponsiblePersonIds"
        :data="responsiblePersonList"
        :titles="['可选人员', '已选人员']"
        :props="{ key: 'id', label: 'nickname' }"
        filterable
        class="transfer-component"
      >
        <template #default="{ option }">
          <el-tooltip
            effect="dark"
            placement="top"
            :content="`${option.nickname} - ${option.deptName || '未分配部门'}`"
          >
            <span class="transfer-option-text">
              {{ option.nickname }} - {{ option.deptName || '未分配部门' }}
            </span>
          </el-tooltip>
        </template>
      </el-transfer>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleResponsiblePersonDialogClose">取消</el-button>
        <el-button type="primary" @click="confirmResponsiblePersonSelection">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
// 导入部分保持不变，与原始代码相同
import { IotProjectInfoApi, IotProjectInfoVO } from '@/api/pms/iotprojectinfo'
import {defaultProps,handleTree} from "@/utils/tree";
import * as DeptApi from "@/api/system/dept";
import {ref, reactive, computed, onMounted, watch} from "vue";
import {useUserStore} from "@/store/modules/user";
import {IotProjectTaskApi, IotProjectTaskVO} from "@/api/pms/iotprojecttask";
import {ElMessageBox, ElMessage} from "element-plus";
import {useTagsViewStore} from "@/store/modules/tagsView";
import { IotDeviceApi, IotDeviceVO } from '@/api/pms/device'
import * as UserApi from "@/api/system/user";
import {IotProjectTaskAttrsApi, IotProjectTaskAttrsVO} from "@/api/pms/iotprojecttaskattrs";
import {DICT_TYPE, getIntDictOptions, getStrDictOptions, getDictLabel} from "@/utils/dict";

const { query, params, name } = useRoute() // 查询参数
const id = params.id

// 修改projectId获取逻辑：优先使用params.projectId，其次使用query.projectId
const projectId = ref<string>('')
// 获取projectId的逻辑
if (params.projectId) {
  projectId.value = Array.isArray(params.projectId) ? params.projectId[0] : params.projectId
} else if (query.projectId) {
  projectId.value = Array.isArray(query.projectId) ? query.projectId[0] : query.projectId as string
}

// 施工队伍 选择树 响应式变量
const defaultExpandedKeys = ref<number[]>([]); // 默认展开的部门节点keys
const treeSelectRef = ref(); // 树选择组件的引用

const { delView } = useTagsViewStore() // 视图操作
const { currentRoute, push } = useRouter()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const deptList = ref<Tree[]>([]) // 树形结构
const deviceList = ref<IotDeviceVO[]>([]) // 设备列表
// 设备映射表（ID->设备对象）
const deviceMap = ref<Record<number, IotDeviceVO>>({});

const dialogVisible = ref(true) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const taskList = ref<IotProjectTaskVO[]>([]) // 列表的数据
const projectList = ref<IotProjectInfoVO[]>([])
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const loading = ref(true) // 列表的加载中

// 设备选择相关变量
const deviceDialogVisible = ref(false);
const filteredDeviceList = ref<IotDeviceVO[]>([]); // 过滤后的设备列表
const selectedDeviceIds = ref<number[]>([]); // 选中的设备ID

// 责任人相关变量
const responsiblePersonDialogVisible = ref(false);
const responsiblePersonList = ref([]); // 所有责任人列表
const selectedResponsiblePersonIds = ref([]); // 选中的责任人ID
const currentEditingRowForResponsible = ref(null); // 当前正在编辑责任人的行

// 动态属性相关变量
const dynamicAttrs = ref([]); // 存储动态属性列表

// 跟踪是否已从任务数据中获取动态属性
const hasDynamicAttrsFromTask = ref(false);

// 添加 workAreaOptions 引用和加载状态
const workAreaOptions = ref<any[]>([])
const loadingWorkAreaOptions = ref(false)
const workAreaAutocomplete = ref() // 添加对el-autocomplete的引用
// currentDictLabel 响应式变量
const currentDictLabel = ref(''); // 存储当前项目对应的施工区域字典类型

// 施工工艺相关变量
const technologyOptions = ref<any[]>([])
const loadingTechnologyOptions = ref(false)
const currentTechnologyDictLabel = ref(''); // 存储当前项目对应的施工工艺字典类型

/** 项目信息 表单 */
defineOptions({ name: 'IotProjectTaskInfo' })

const formData = ref({
  id: undefined,
  contractId: undefined,
  contractName: undefined,
  contractCode: undefined,
  workloadTotal: undefined,
  workloadFinish: undefined,
  workloadUnit: undefined,
  startTime: undefined,
  endTime: undefined,
  location: undefined,
  technique: undefined,
  payment: undefined,
  remark:undefined,
  manufactureName: undefined,
  manufacturerId: undefined,
  userName: undefined,
  userId: undefined,
  deptId: undefined, // 新增项目部门ID字段
})

const close = () => {
  delView(unref(currentRoute))
  push({ name: 'IotProjectTask', params:{}})
}

const getProjectInfo = async (contractId: number) => {
  const project = projectList.value.find(item => item.id === contractId);
  if (project) {
    formData.value.contractName = project.contractName;
    formData.value.contractCode = project.contractCode;
    formData.value.payment = project.payment;
    formData.value.workloadTotal = project.workloadTotal;
    formData.value.startTime = project.startTime;
    formData.value.endTime = project.endTime;
    formData.value.remark = project.remark;
    formData.value.manufactureName = project.manufactureName;
    formData.value.manufacturerId = project.manufacturerId;
    formData.value.id = project.id;
    formData.value.deptId = project.deptId; // 保存项目部门ID
    // 获取施工区域数据字典集合
    await loadWorkAreaOptions(formData.value.deptId);
    // 获取施工工艺数据字典集合
    await loadTechnologyOptions(formData.value.deptId);
    // 获取动态属性
    await fetchDynamicAttrs();
  }
}

const queryParams = reactive({
  projectId:undefined,
  id:undefined
})
const formRules = reactive({
  contractId: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  manufacturerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  payment: [{ required: true, message: '结算方式不能为空', trigger: 'blur' }],
  // workloadTotal: [{ required: true, message: '工作量总数不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const zzClear = () =>{
  formData.value.manufacturerId = undefined
  formData.value.manufactureName = undefined
}

// 根据部门ID获取部门名称
const getDeptNames = (deptIds) => {
  if (!deptIds || deptIds.length === 0) return '';

  const names = [];
  const findDept = (list, id) => {
    for (const item of list) {
      if (item.id === id) {
        names.push(item.name);
        return true;
      }
      if (item.children && findDept(item.children, id)) {
        return true;
      }
    }
    return false;
  };

  deptIds.forEach(id => findDept(deptList.value, id));
  if (names.length > 1) {
    return `${names[0]}...`;
  }
  return names.join(', ');
};

const getAllDeptNames = (deptIds) => {
  if (!deptIds || deptIds.length === 0) return '无施工队伍';

  const names = [];
  const findDept = (list, id) => {
    for (const item of list) {
      if (item.id === id) {
        names.push(item.name);
        return true;
      }
      if (item.children && findDept(item.children, id)) {
        return true;
      }
    }
    return false;
  };

  deptIds.forEach(id => findDept(deptList.value, id));

  return names.join(', ') || '无有效施工队伍';
};

const getDeviceNames = (deviceIds: number[]) => {
  if (!deviceIds || deviceIds.length === 0) return '';

  // 获取所有有效设备名称
  const deviceNames = deviceIds
    .map(id => deviceMap.value[id]?.deviceCode)
    .filter(name => name !== undefined && name !== '');

  if (deviceNames.length === 0) return '';

  // 如果设备数量超过2个，显示前两个加省略号
  if (deviceNames.length > 2) {
    return `${deviceNames[0]}, ${deviceNames[1]}...`;
  }

  // 设备数量不超过2个，正常显示所有
  return deviceNames.join(', ');
};

// 初始化动态属性到当前任务
/* const initDynamicAttrsToCurrentTask = () => {
  dynamicAttrs.value.forEach(attr => {
    // 如果当前任务中还没有这个属性，则初始化
    if (!currentTask.value.hasOwnProperty(attr.identifier)) {
      // 如果是编辑模式且有已有值，使用已有值，否则使用默认值
      if (formType.value === 'update' && tableData.value[0] && tableData.value[0][attr.identifier] !== undefined) {
        currentTask.value[attr.identifier] = tableData.value[0][attr.identifier];
      } else {
        currentTask.value[attr.identifier] = attr.defaultValue || '';
      }
    }
  });
}; */

const initDynamicAttrsToCurrentTask = () => {
  dynamicAttrs.value.forEach(attr => {
    if (!currentTask.value.hasOwnProperty(attr.identifier)) {
      // 如果是从任务数据中获取的属性，并且有实际值，使用实际值
      if (hasDynamicAttrsFromTask.value && attr.actualValue !== undefined && attr.actualValue !== null && attr.actualValue !== '') {
        currentTask.value[attr.identifier] = attr.actualValue;
      } else {
        // 否则使用默认值
        currentTask.value[attr.identifier] = attr.defaultValue || '';
      }
    }
  });
};

// 当前编辑的任务
const currentTask = ref({
  id: undefined,
  wellName: '',
  wellType: '',
  wellCategory: '',
  location: '',
  dictType: '',
  technique: '',
  workloadDesign: '',
  workloadUnit: '',
  deptIds: [],
  deviceIds: [],
  responsiblePerson: [],
  remark: '',
  projectId: ''
});

const isNewTask = ref(false); // 是否是新任务
const taskFormRef = ref(); // 任务表单ref
const currentEditingIndex = ref(-1); // 当前编辑的行索引

// 任务表单验证规则
const taskFormRules = reactive({
  wellName: [{ required: true, message: '井号不能为空', trigger: 'blur' }],
  wellType: [{ required: true, message: '井型不能为空', trigger: 'change' }],
  location: [{ required: true, message: '施工地点不能为空', trigger: 'blur' }],
  technique: [{ required: true, message: '施工工艺不能为空', trigger: 'change' }],
  workloadDesign: [{ required: true, message: '设计工作量不能为空', trigger: 'blur' }],
  workloadUnit: [{ required: true, message: '工作量单位不能为空', trigger: 'change' }],
  deptIds: [{ required: true, message: '施工队伍不能为空', trigger: 'change' }],
  deviceIds: [{ required: true, message: '施工设备不能为空', trigger: 'change' }],
  responsiblePerson: [{ required: true, message: '责任人不能为空', trigger: 'change' }],
});

// 动态属性验证规则
const getDynamicAttrRules = (attr) => {
  const rules = [];
  if (attr.required === 1) {
    rules.push({ required: true, message: `${attr.name}不能为空`, trigger: 'blur' });
  }

  // 数字类型验证
  if (attr.dataType === 'double') {
    rules.push({
      validator: (rule, value, callback) => {
        if (value === '' || value === null || value === undefined) {
          callback();
          return;
        }

        const numValue = Number(value);
        if (isNaN(numValue)) {
          callback(new Error(`${attr.name}必须是数字`));
        } else if (attr.minValue !== null && numValue < Number(attr.minValue)) {
          // callback(new Error(`${attr.name}不能小于${attr.minValue}`));
        } else if (attr.maxValue !== null && numValue > Number(attr.maxValue)) {
          // callback(new Error(`${attr.name}不能大于${attr.maxValue}`));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    });
  }

  return rules;
};

const tableData = ref([]);

// 打开责任人选择对话框（用于表单）
const openResponsiblePersonDialogForForm = async () => {
  if (!currentTask.value.deptIds || currentTask.value.deptIds.length === 0) {
    ElMessage.warning('请先选择施工队伍');
    return;
  }

  selectedResponsiblePersonIds.value = [...(currentTask.value.responsiblePerson || [])];

  try {
    const params = {
      deptIds: currentTask.value.deptIds // 使用当前项目所属部门的deptId
    };
    const response = await UserApi.selectedDeptsEmployee(params);
    responsiblePersonList.value = response;
    responsiblePersonDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取责任人列表失败');
    console.error('获取责任人列表失败:', error);
  }
};

// 获取动态属性
const fetchDynamicAttrs = async () => {
  // 如果已经通过任务数据获取了动态属性，则不再调用接口
  if (hasDynamicAttrsFromTask.value) {
    return;
  }

  if (!formData.value.deptId) {
    console.warn('部门ID为空，无法获取动态属性');
    return;
  }

  try {
    const queryParams = {
      deptId: formData.value.deptId
    };

    const response = await IotProjectTaskAttrsApi.getIotProjectTaskAttrsList(queryParams);
    dynamicAttrs.value = response || [];

    // 初始化动态属性到当前任务
    initDynamicAttrsToCurrentTask();
  } catch (error) {
    console.error('获取动态属性失败:', error);
    ElMessage.error('获取动态属性失败');
  }
};

// 打开设备选择对话框（用于表单）
const openDeviceDialogForForm = async () => {
  if (!currentTask.value.deptIds || currentTask.value.deptIds.length === 0) {
    ElMessage.warning('请先选择施工队伍');
    return;
  }

  selectedDeviceIds.value = [...(currentTask.value.deviceIds || [])];

  try {
    const params = {
      deptIds: currentTask.value.deptIds
    };
    const data = await IotDeviceApi.getDevicesByDepts(params);

    // 更新设备映射表
    const newDeviceMap = {...deviceMap.value};
    data.forEach(device => {
      newDeviceMap[device.id] = device;
    });
    deviceMap.value = newDeviceMap;

    filteredDeviceList.value = data;
    deviceDialogVisible.value = true;

  } catch (error) {
    ElMessage.error('获取设备列表失败');
    console.error('获取设备列表失败:', error);
  }
};

// 处理穿梭框变化
const handleTransferChange = (value, direction, movedKeys) => {
  // 可以添加额外的处理逻辑
};

// 确认设备选择（用于表单）
const confirmDeviceSelection = () => {
  currentTask.value.deviceIds = [...selectedDeviceIds.value];
  // 强制更新视图
  currentTask.value = {...currentTask.value};
  deviceDialogVisible.value = false;
};

// 确认责任人选择（用于表单）
const confirmResponsiblePersonSelection = () => {
  currentTask.value.responsiblePerson = [...selectedResponsiblePersonIds.value];
  responsiblePersonDialogVisible.value = false;
};

// 关闭设备选择对话框
const handleDeviceDialogClose = () => {
  deviceDialogVisible.value = false;
};

// 关闭责任人选择对话框
const handleResponsiblePersonDialogClose = () => {
  responsiblePersonDialogVisible.value = false;
};

// 获取井型标签的方法
const getWellTypeLabel = (value) => {
  const options = getStrDictOptions(DICT_TYPE.PMS_PROJECT_WELL_TYPE)
  const option = options.find(opt => opt.value === value)
  return option ? option.label : value
}

// 获取井别标签的方法
const getWellCategoryLabel = (value) => {
  const options = getStrDictOptions(DICT_TYPE.PMS_PROJECT_WELL_CATEGORY)
  const option = options.find(opt => opt.value === value)
  return option ? option.label : value
}

// 获取施工工艺标签的方法
const getTechniqueLabel = (value) => {
  const options = getStrDictOptions(DICT_TYPE.PMS_PROJECT_TECHNOLOGY)
  const option = options.find(opt => opt.value === value)
  return option ? option.label : value
}

// 获取 工作量单位 标签的方法
const getWorkloadUnitLabel = (value) => {
  const options = getStrDictOptions(DICT_TYPE.PMS_PROJECT_WORKLOAD_UNIT)
  const option = options.find(opt => opt.value === value)
  return option ? option.label : value
}

/** 同步当前任务表单数据到表格数据 */
const syncCurrentTaskToTable = () => {
  if (!currentTask.value.wellName) {
    ElMessage.warning('请先填写任务详情');
    return false;
  }

  // 设置项目ID
  currentTask.value.projectId = formData.value.id;

  if (isNewTask.value) {
    // 新增任务 - 生成唯一ID并添加到表格
    const newId = tableData.value.length > 0
      ? Math.max(...tableData.value.map(item => item.id)) + 1
      : 1;
    currentTask.value.id = newId;
    tableData.value.unshift({...currentTask.value});
    isNewTask.value = false;
    // ElMessage.success('任务已添加到列表');
  } else {
    // 更新现有任务
    const index = tableData.value.findIndex(item => item.id === currentTask.value.id);
    if (index !== -1) {
      tableData.value.splice(index, 1, {...currentTask.value});
      // ElMessage.success('任务已更新');
    } else {
      // 如果没有找到，添加到表格（可能是意外情况）
      tableData.value.unshift({...currentTask.value});
    }
  }

  return true;
};

// 重置任务表单
const resetTaskForm = () => {
  currentTask.value = {
    id: undefined,
    wellName: '',
    wellType: '',
    wellCategory: '',
    location: '',
    technique: '',
    workloadDesign: '',
    workloadUnit: '',
    deptIds: [],
    deviceIds: [],
    responsiblePerson: [],
    remark: '',
    projectId: formData.value.id
  };

  // 重新初始化动态属性
  initDynamicAttrsToCurrentTask();

  isNewTask.value = false;
  taskFormRef.value?.resetFields();
};

// 添加新任务
const addNewTask = () => {
  resetTaskForm();
  isNewTask.value = true;
};

// 保存任务
const saveTask = async () => {
  // 验证表单
  try {
    await taskFormRef.value.validate();
  } catch (error) {
    ElMessage.error('请完善任务信息');
    return;
  }

  // 设置项目ID
  currentTask.value.projectId = formData.value.id;

  if (isNewTask.value) {
    // 新增任务
    const newId = tableData.value.length > 0
      ? Math.max(...tableData.value.map(item => item.id)) + 1
      : 1;

    currentTask.value.id = newId;
    tableData.value.unshift({...currentTask.value});
    ElMessage.success('任务添加成功');
    resetTaskForm();
  } else {
    // 更新任务
    const index = tableData.value.findIndex(item => item.id === currentTask.value.id);
    if (index !== -1) {
      tableData.value.splice(index, 1, {...currentTask.value});
      ElMessage.success('任务更新成功');
    }
  }
};

// 删除当前任务
const deleteCurrentTask = () => {
  if (!currentTask.value.id) return;

  ElMessageBox.confirm('确定要删除这个任务吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = tableData.value.findIndex(item => item.id === currentTask.value.id);
    if (index !== -1) {
      tableData.value.splice(index, 1);
      resetTaskForm();
      ElMessage.success('任务删除成功');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 处理行点击事件
const handleRowClick = (row, index) => {
  if (row) {
    currentTask.value = {...row};
    currentEditingIndex.value = index; // 保存当前编辑的行索引
    isNewTask.value = false;
  }
};

// 根据责任人ID获取责任人名称
const getResponsiblePersonNames = (responsiblePersonIds: number[]) => {
  if (!responsiblePersonIds || responsiblePersonIds.length === 0) return '';

  // 获取所有有效责任人名称
  const personNames = responsiblePersonIds
    .map(id => {
      const person = responsiblePersonList.value.find(p => p.id === id);
      return person ? person.nickname : '';
    })
    .filter(name => name !== undefined && name !== '');

  if (personNames.length === 0) return '';

  // 如果责任人数量超过2个，显示前两个加省略号
  if (personNames.length > 2) {
    return `${personNames[0]}, ${personNames[1]}...`;
  }

  // 责任人数量不超过2个，正常显示所有
  return personNames.join(', ');
};

// 获取所有责任人名称（用于tooltip提示）
const getAllResponsiblePersonNames = (responsiblePersonIds: number[]) => {
  if (!responsiblePersonIds || responsiblePersonIds.length === 0) return '无责任人';

  const personNames = responsiblePersonIds
    .map(id => {
      const person = responsiblePersonList.value.find(p => p.id === id);
      return person ? person.nickname : '未知人员';
    })
    .filter(name => name !== '未知人员');

  return personNames.join(', ') || '无有效责任人';
};

// 获取所有设备名称（用于tooltip提示）
const getAllDeviceNames = (deviceIds: number[]) => {
  if (!deviceIds || deviceIds.length === 0) return '无设备';

  const deviceNames = deviceIds
    .map(id => deviceMap.value[id]?.deviceCode || '未知设备')
    .filter(name => name !== '未知设备');

  return deviceNames.join(', ') || '无有效设备';
};

/** 打开弹窗 */
const open = async () => {
  resetForm()
  resetTaskForm();
  hasDynamicAttrsFromTask.value = false; // 重置标志

  // 修改时，设置数据
  if (id) {
    formType.value = 'update';
    formLoading.value = true
    try {
      queryParams.id = id;
      const data = await IotProjectTaskApi.getIotProjectTaskPage(queryParams);
      tableData.value = data.list

      // 1. 收集所有设备ID
      const allDeviceIds = new Set<number>();
      // 收集所有责任人ID
      const allResponsiblePersonIds = new Set<number>();

      data.list.forEach(item => {
        if (item.deviceIds?.length) {
          item.deviceIds.forEach(id => allDeviceIds.add(id));
        }
        if (item.responsiblePerson?.length) {
          item.responsiblePerson.forEach(id => allResponsiblePersonIds.add(id));
        }
      });

      // 2. 批量获取设备信息
      if (allDeviceIds.size > 0) {
        const deviceIdsArray = Array.from(allDeviceIds);
        const devices = await IotDeviceApi.getDevicesByDepts({
          deviceIds: deviceIdsArray
        });

        // 3. 更新设备列表和映射表
        deviceList.value = devices;
        deviceMap.value = {};
        devices.forEach(device => {
          deviceMap.value[device.id] = device;
        });
      }

      // 批量获取责任人信息
      if (allResponsiblePersonIds.size > 0) {
        const personIdsArray = Array.from(allResponsiblePersonIds);
        const params = {
          userIds: personIdsArray
        };
        const persons = await UserApi.companyDeptsEmployee(params);

        // 更新责任人列表
        responsiblePersonList.value = persons;
      }

      if (tableData.value && tableData.value.length > 0) {
        // 使用深拷贝，避免修改表单时直接影响表格数据
        currentTask.value = JSON.parse(JSON.stringify(tableData.value[0]));
        isNewTask.value = false;

        // 新增代码：检查任务数据中是否有extProperty
        if (tableData.value[0].extProperty && tableData.value[0].extProperty.length > 0) {
          // 使用任务数据中的extProperty作为动态属性
          dynamicAttrs.value = tableData.value[0].extProperty;
          hasDynamicAttrsFromTask.value = true;

          // 将extProperty中的值设置到当前任务
          tableData.value[0].extProperty.forEach(attr => {
            if (attr.identifier) {
              // 优先使用actualValue，如果没有则使用defaultValue
              currentTask.value[attr.identifier] =
                attr.actualValue !== undefined && attr.actualValue !== null && attr.actualValue !== ''
                  ? attr.actualValue
                  : attr.defaultValue || '';
            }
          });
        }
      }
    } finally {
      formLoading.value = false
    }
  } else {
    formType.value = 'create';
  }
  // 如果有projectId参数，自动选中对应的合同
  if (projectId.value) {
    autoSelectContract(projectId.value);
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 自动选择合同 */
const autoSelectContract = async (projectId: string) => {
  console.log('项目id：' + projectId);
  // 查找匹配的合同
  const project = projectList.value.find(item => item.id === Number(projectId));
  if (project) {
    // 设置选中值
    formData.value.contractId = project.id;
    // 触发合同信息加载
    getProjectInfo(project.id);
  } else {
    ElMessage.warning('未找到指定的合同信息');
  }
}

/** 校验所有行数据 */
const validateAllRows = (): boolean => {
  // 新增检查：判断任务列表是否为空
  if (!tableData.value || tableData.value.length === 0) {
    ElMessage.error('没有任务数据，无法保存');
    return false;
  }

  let allValid = true;

  tableData.value.forEach(row => {
    if (!row.wellName || row.wellName.trim() === '') {
      allValid = false;
    }

    /* if (!row.wellType || row.wellType.trim() === '') {
      allValid = false;
    } */

    if (!row.location || row.location.trim() === '') {
      allValid = false;
    }

    if (!row.technique || row.technique.trim() === '') {
      allValid = false;
    }

    if (!row.deptIds || row.deptIds.length === 0) {
      allValid = false;
    }

    if (!row.deviceIds || row.deviceIds.length === 0) {
      allValid = false;
    }

    if (!row.responsiblePerson || row.responsiblePerson.length === 0) {
      allValid = false;
    }
  });

  if (!allValid) {
    ElMessage.error('请检查表格中的数据，部分必填项未填写或格式不正确');
  }

  return allValid;
};

// 添加表单专用的格式化方法
// 格式化设备显示（用于表单）
const formatDevicesForForm = (deviceIds: number[]) => {
  if (!deviceIds || deviceIds.length === 0) return '';

  const deviceNames = deviceIds
    .map(id => deviceMap.value[id]?.deviceCode)
    .filter(name => name !== undefined && name !== '');

  if (deviceNames.length === 0) return '';

  if (deviceNames.length > 2) {
    return `${deviceNames[0]}, ${deviceNames[1]}...`;
  }

  return deviceNames.join(', ');
};

// 获取所有设备名称（用于表单的tooltip）
const getAllDeviceNamesForForm = (deviceIds: number[]) => {
  if (!deviceIds || deviceIds.length === 0) return '无设备';

  const deviceNames = deviceIds
    .map(id => deviceMap.value[id]?.deviceCode || '未知设备')
    .filter(name => name !== '未知设备');

  return deviceNames.join(', ') || '无有效设备';
};

// 格式化责任人显示（用于表单）
const formatResponsiblePersonsForForm = (responsiblePersonIds: number[]) => {
  if (!responsiblePersonIds || responsiblePersonIds.length === 0) return '';

  const personNames = responsiblePersonIds
    .map(id => {
      const person = responsiblePersonList.value.find(p => p.id === id);
      return person ? person.nickname : '';
    })
    .filter(name => name !== undefined && name !== '');

  if (personNames.length === 0) return '';

  if (personNames.length > 2) {
    return `${personNames[0]}, ${personNames[1]}...`;
  }

  return personNames.join(', ');
};

// 获取所有责任人名称（用于表单的tooltip）
const getAllResponsiblePersonNamesForForm = (responsiblePersonIds: number[]) => {
  if (!responsiblePersonIds || responsiblePersonIds.length === 0) return '无责任人';

  const personNames = responsiblePersonIds
    .map(id => {
      const person = responsiblePersonList.value.find(p => p.id === id);
      return person ? person.nickname : '未知人员';
    })
    .filter(name => name !== '未知人员');

  return personNames.join(', ') || '无有效责任人';
};

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const submitForm = async () => {
  // 施工区域的数据字典类型
  currentTask.value.dictType = currentDictLabel.value;

  // 先同步当前任务表单数据到表格
  if (!syncCurrentTaskToTable()) {
    return;
  }

  // 校验表单
  await formRef.value.validate()

  // 校验所有行数据
  if (!validateAllRows()) {
    return;
  }

  // 处理动态属性数据
  const processedTableData = tableData.value.map(task => {
    // 为每个任务构建extProperty数组
    const extProperties = dynamicAttrs.value.map(attr => {
      return {
        name: attr.name,
        sort: attr.sort,
        unit: attr.unit,
        actualValue: task[attr.identifier] || '', // 从任务中获取用户填写的值
        dataType: attr.dataType,
        maxValue: attr.maxValue,
        minValue: attr.minValue,
        required: attr.required,
        accessMode: attr.accessMode,
        identifier: attr.identifier,
        defaultValue: attr.defaultValue
      };
    });

    // 返回处理后的任务数据，包含extProperty字段
    return {
      ...task,
      dictType: task.dictType || currentDictLabel.value, // 确保每个任务都有dictType
      extProperty: extProperties
    };
  });

  // 提交请求
  formLoading.value = true
  try {
    tableData.value.forEach(item=>{
      item.projectId = formData.value.id;
    })

    const data = {
      taskList: processedTableData
    }
    if (formType.value === 'create') {
      await IotProjectTaskApi.createIotProjectTask(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotProjectTaskApi.updateIotProjectTask(data)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    emit('success')
    close()
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    contractId: undefined,
    contractName: undefined,
    contractCode: undefined,
    workloadTotal: undefined,
    workloadFinish: undefined,
    workloadUnit: undefined,
    startTime: undefined,
    endTime: undefined,
    location: undefined,
    technique: undefined,
    payment: undefined,
    remark: undefined,
    manufactureName: undefined,
    manufacturerId: undefined,
    userName: undefined,
    userId: undefined,
  }
  formRef.value?.resetFields()
}

// 加载工作区域选项的方法
const loadWorkAreaOptions = async (deptId: number) => {
  // 如果正在加载，直接返回
  if (loadingWorkAreaOptions.value) return;

  loadingWorkAreaOptions.value = true;
  try {
    // 先尝试通过 getDictLabel 获取字典标签
    const dictLabel = await getDictLabel(DICT_TYPE.PMS_PROJECT_WORK_AREA, deptId);
    console.log('当前专业公司的施工区域数据字典类型：' + dictLabel)
    // 将 dictLabel 存储到 currentDictLabel
    currentDictLabel.value = dictLabel || ''; // 如果没有获取到，设为空字符串

    if (dictLabel) {
      // 如果获取到标签，再获取完整的字典选项
      const dictOptions = getStrDictOptions(dictLabel);
      console.log('当前专业公司的施工区域数据字典集合长度：' + dictOptions.length)
      workAreaOptions.value = dictOptions.map(option => ({
        value: option.label, // 使用标签作为显示值
        id: option.value     // 保留原始值
      }));
    } else {
      // 如果获取不到标签，清空选项
      workAreaOptions.value = [];
    }
  } catch (error) {
    console.error('获取工作区域选项失败:', error);
    workAreaOptions.value = [];
  } finally {
    loadingWorkAreaOptions.value = false;
  }
}

// 当没有查询字符串时返回所有选项
const querySearch = (queryString: string, cb: any) => {
  // 如果没有查询字符串，返回所有选项
  if (!queryString) {
    cb(workAreaOptions.value);
    return;
  }

  // 有查询字符串时进行筛选
  const results = workAreaOptions.value.filter(option =>
    option.value.toLowerCase().includes(queryString.toLowerCase())
  );

  // 调用 callback 返回建议列表的数据
  cb(results);
}

// 添加处理施工区域获取焦点的方法
const handleWorkAreaFocus = async () => {
  // 如果已经有选项数据，直接显示下拉框
  if (workAreaOptions.value.length > 0) {
    // 使用Element Plus提供的方法触发下拉框
    try {
      // 直接调用el-autocomplete的focus方法
      if (workAreaAutocomplete.value && typeof workAreaAutocomplete.value.focus === 'function') {
        workAreaAutocomplete.value.focus();
      }
    } catch (error) {
      console.error('触发下拉框显示失败:', error)
    }
    return
  }

  // 如果没有选项数据，尝试加载
  if (formData.value.deptId && !loadingWorkAreaOptions.value) {
    await loadWorkAreaOptions(formData.value.deptId)
    // 加载完成后尝试显示下拉框
    if (workAreaOptions.value.length > 0) {
      try {
        if (workAreaAutocomplete.value && typeof workAreaAutocomplete.value.focus === 'function') {
          workAreaAutocomplete.value.focus();
        }
      } catch (error) {
        console.error('触发下拉框显示失败:', error)
      }
    }
  }
}

// 添加选择处理方法
const handleSelect = (item: any) => {
  // 这里可以根据需要处理选择后的逻辑
  console.log('选择了:', item.value);
}

// 加载施工工艺选项的方法
const loadTechnologyOptions = async (deptId: number) => {
  if (loadingTechnologyOptions.value) return;

  loadingTechnologyOptions.value = true;
  try {
    // 先尝试通过 getDictLabel 获取字典标签
    const dictLabel = await getDictLabel(DICT_TYPE.PMS_PROJECT_TECHNOLOGY, deptId);
    console.log('当前专业公司的施工工艺数据字典类型：' + dictLabel)
    // 将 dictLabel 存储到 currentTechnologyDictLabel
    currentTechnologyDictLabel.value = dictLabel || ''; // 如果没有获取到，设为空字符串

    if (dictLabel) {
      // 如果获取到标签，再获取完整的字典选项
      const dictOptions = getStrDictOptions(dictLabel);
      console.log('当前专业公司的施工工艺数据字典集合长度：' + dictOptions.length)
      technologyOptions.value = dictOptions.map(option => ({
        value: option.value,
        label: option.label
      }));
    } else {
      // 如果获取不到标签，清空选项
      technologyOptions.value = [];
    }
  } catch (error) {
    console.error('获取施工工艺选项失败:', error);
    technologyOptions.value = [];
  } finally {
    loadingTechnologyOptions.value = false;
  }
}

// 监听当前任务的变化，设置默认展开的keys
watch(() => currentTask.value.deptIds, (newVal) => {
  if (newVal && newVal.length > 0) {
    defaultExpandedKeys.value = [...newVal];
  }
}, { immediate: true, deep: true });

// 监听部门列表加载完成
watch(() => deptList.value, (newVal) => {
  if (newVal && newVal.length > 0 && currentTask.value.deptIds && currentTask.value.deptIds.length > 0) {
    defaultExpandedKeys.value = [...currentTask.value.deptIds];
  }
}, { immediate: true, deep: true });

// 监听项目列表变化，确保列表加载完成后才执行自动选择
watch(projectList, (newVal) => {
  if (newVal && newVal.length > 0) {
    // 如果是编辑模式，使用任务数据中的合同ID
    if (id && tableData.value.length > 0 && tableData.value[0].projectId) {
      autoSelectContract(tableData.value[0].projectId.toString());
    }
    // 如果是新增模式且有传递的projectId，使用传递的projectId
    else if (!id && projectId.value) {
      console.log('watch-新增模式且有传递的projectId' + projectId.value + ' projectId not found');
      autoSelectContract(projectId.value);
    }
  }
});

// 处理树形下拉框可见性变化
const handleTreeVisibleChange = (visible: boolean) => {
  if (visible && currentTask.value.deptIds && currentTask.value.deptIds.length > 0) {
    // 当下拉框显示且当前任务有已选部门时，设置默认展开的keys
    defaultExpandedKeys.value = [...currentTask.value.deptIds];

    // 使用nextTick确保DOM更新后再执行展开操作
    nextTick(() => {
      if (treeSelectRef.value) {
        // 尝试访问内部树实例并展开节点
        const treeInstance = treeSelectRef.value.treeRef;
        if (treeInstance && treeInstance.setExpandedKeys) {
          treeInstance.setExpandedKeys(defaultExpandedKeys.value);
        }
      }
    });
  }
};

onMounted(async () => {
  // 查询当前登录人所属公司下的所有部门
  deptList.value = handleTree(await DeptApi.companyLevelChildrenDepts())
  let deptId = useUserStore().getUser.deptId
  projectList.value = await IotProjectInfoApi.getIotProjectInfoUser(deptId);
  // 查询当前任务已经选中的设备信息
  open();
})
</script>

<style scoped>
.edit-input {
  margin-right: 10px;
}
.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}
.action-cell {
  display: flex;
  gap: 8px;
}

/* 1. 穿梭框父容器：居中 + 内边距 */
.transfer-container {
  text-align: center;
  padding: 0px; /* 上下内边距，避免紧贴对话框边缘 */
}

/* 2. 穿梭框组件：控制宽度，避免过窄或过宽 */
.transfer-component {
  width: 100%; /* 占对话框90%宽度，兼顾美观和内容显示 */
  min-width: 600px;
}

/* 3. 直接调整 el-transfer 左右窗口的宽度 */
:deep(.el-transfer-panel) {
  width: 40% !important; /* 强制设置左右面板宽度，确保两侧面板对等 */
}

/* 3. 深度选择器：修改el-transfer选项样式（解决内容省略问题） */
:deep(.el-transfer-panel__item) {
  /* white-space: nowrap;  文本不换行，保证一行显示 */
  /* overflow: hidden;  超出部分隐藏 */
  /* text-overflow: ellipsis;  超出显示省略号 */
  /* max-width: 100%;  确保文本不超出选项容器宽度 */
  /* padding: 6px 6px;  适当增加内边距，优化点击体验 */
}

:deep(.el-transfer-panel__item) {
  display: flex !important;
  align-items: center !important;
  height: 32px !important;
  line-height: 32px !important;
  padding: 0 8px !important;
  margin: 0 !important;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 4. 选项文本：确保继承父容器宽度，省略号正常生效 */
.transfer-option-text {
  display: inline-block;
  max-width: 100%;
}

/* 设备名称显示区域样式 */
.device-names {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px; /* 根据实际列宽调整 */
}

:deep(.el-transfer-panel__list) {
  width: 100% !important; /* 使面板内部内容宽度占满 */
}

/* 责任人名称显示区域样式 */
.responsible-names {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px; /* 根据实际列宽调整 */
}

/* 添加部门名称的样式 */
.dept-names {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px; /* 根据实际列宽调整 */
  display: inline-block;
  vertical-align: bottom;
}

/* 部门选择器样式优化 */
:deep(.department-tree-select .el-select__tags) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex-wrap: nowrap;
}

:deep(.department-tree-select .el-select__tags .el-tag) {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
}


:deep(.department-tree-select .el-select__tags .el-tag + .el-tag) {
  margin-left: 6px;
}

:deep(.department-tree-select .el-select__tags-text) {
  display: inline-block;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
}


/* 当有多个标签被折叠时显示的 "+N" 标签样式 */
:deep(.department-tree-select .el-select__collapse-tags) {
  white-space: nowrap;
  display: inline-block;
}

.task-edit-form {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}
</style>
