<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="客户名称" prop="manufactureName">
        <el-input
          v-model="queryParams.manufactureName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="合同编号" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="起止日期" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create',undefined)"
          v-hasPermi="['rq:iot-project-info:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['rq:iot-project-info:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap ref="tableContainerRef">
    <div class="table-container">
      <el-table ref="tableRef" v-loading="loading" :data="list" :stripe="true" style="width: 100%" :cell-style="{padding: '5px'}">
        <el-table-column :label="t('iotDevice.serial')" :width="columnWidths.serial" align="center" v-if="false">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="left" prop="manufactureName" :width="columnWidths.manufactureName" />
        <el-table-column label="合同名称" align="center" prop="contractName" :width="columnWidths.contractName" >
          <template #default="scope">
            <el-link type="primary" @click="showTaskList(scope.row)">
              {{ scope.row.contractName }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="合同编号" align="center" prop="contractCode" :width="columnWidths.contractCode" />
        <el-table-column label="总工作量" align="center" prop="workloadTotal" :width="columnWidths.workloadTotal" />
        <el-table-column label="已完成工作量" align="center" prop="workloadFinish" :width="columnWidths.workloadFinish" />
        <el-table-column
          label="合同开始时间"
          align="center"
          prop="startTime"
          :formatter="dateFormatter2"
          :width="columnWidths.startTime"
        />
        <el-table-column
          label="合同完成时间"
          align="center"
          prop="endTime"
          :formatter="dateFormatter2"
          :width="columnWidths.endTime"
        />
        <el-table-column :label="t('project.payment')" align="center" prop="payment" :width="columnWidths.payment">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.PMS_PROJECT_SETTLEMENT" :value="scope.row.payment" />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          :width="columnWidths.createTime"
        />
        <el-table-column label="操作" align="center" :width="columnWidths.operation" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['rq:iot-project-info:update']"
            >
              编辑
            </el-button>
            <el-button
              link
              type="primary"
              @click="assignTask(scope.row)"
              v-hasPermi="['rq:iot-project-task:create']"
            >
              分配任务
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['rq:iot-project-info:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 任务列表区域 -->
  <ContentWrap v-if="selectedProject">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>任务列表 - {{ selectedProject.contractName }}</span>
          <el-button link @click="closeTaskList" class="close-btn">
            <Icon icon="ep:close" />
          </el-button>
        </div>
      </template>
      <el-table :data="taskList" v-loading="taskLoading">
        <el-table-column label="井号" align="center" prop="wellName" />
        <!--
        <el-table-column :label="t('project.wellType')" align="center" prop="wellType" min-width="70">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.PMS_PROJECT_WELL_TYPE" :value="scope.row.wellType" />
          </template>
        </el-table-column>
        <el-table-column :label="t('project.wellCategory')" align="center" prop="wellCategory" min-width="70">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.PMS_PROJECT_WELL_CATEGORY" :value="scope.row.wellCategory" />
          </template>
        </el-table-column> -->
        <el-table-column :label="t('project.status')" align="center" prop="status" min-width="70">
          <template #default="scope">
            <el-link type="primary" @click="openTimelineDialog(scope.row)">
              <!-- 修改这里：添加状态判断逻辑 -->
              <template v-if="scope.row.status !== null && scope.row.status !== undefined && scope.row.status !== ''">
                <dict-tag :type="DICT_TYPE.PMS_PROJECT_TASK_SCHEDULE" :value="scope.row.status" />
              </template>
              <template v-else>
                未更新状态
              </template>
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="施工地点" align="center" prop="location" />
        <el-table-column :label="t('project.technology')" align="center" prop="technique" min-width="70">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.PMS_PROJECT_TECHNOLOGY" :value="scope.row.technique" />
          </template>
        </el-table-column>
        <el-table-column label="设计工作量" align="center" prop="workloadDesign" />
        <el-table-column label="施工队伍" align="center">
          <template #default="{ row }">
            <el-tooltip
              :content="getAllDeptNames(row.deptIds)"
              placement="top"
            >
              <span class="dept-names">
                {{ getBriefDeptNames(row.deptIds) }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="施工设备" align="center">
          <template #default="{ row }">
            <el-tooltip
              :content="getAllDeviceNames(row.deviceIds)"
              placement="top"
            >
              <span class="device-names">
                {{ getDeviceNames(row.deviceIds) }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="责任人" align="center">
          <template #default="{ row }">
            <el-tooltip
              :content="getAllResponsiblePersonNames(row.responsiblePerson)"
              placement="top"
            >
              <span class="responsible-names">
                {{ getResponsiblePersonNames(row.responsiblePerson) }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      </el-table>
    </el-card>
  </ContentWrap>

  <!-- Timeline 时间线 Dialog - 已修改为 el-steps -->
  <el-dialog v-model="timelineDialogVisible" :title="`任务进度 - ${currentTaskRow ? currentTaskRow.wellName : ''}`" :width="dialogWidth">
    <div v-if="stepsData.length > 0">
      <el-steps direction="horizontal" :active="currentStepIndex" finish-status="success">
        <el-step
          v-for="(step, index) in stepsData"
          :key="index"
          :title="step.title"
          :description="step.description"
          :status="step.status"
        />
      </el-steps>
    </div>
    <el-empty v-else description="暂无进度数据" :image-size="100" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="timelineDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter,dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { IotProjectInfoApi, IotProjectInfoVO } from '@/api/pms/iotprojectinfo'
import {IotProjectTaskApi} from '@/api/pms/iotprojecttask'
import IotProjectInfoForm from './IotProjectInfoForm.vue'
import {useUserStore} from "@/store/modules/user";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import { IotDeviceApi } from '@/api/pms/device' // 引入设备API
import * as UserApi from "@/api/system/user"; // 引入用户API
import * as DeptApi from "@/api/system/dept"; // 引入部门API
import { handleTree } from "@/utils/tree"; // 引入树形处理工具
import { IotProjectTaskScheduleApi } from '@/api/pms/iotprojecttaskschedule'
import dayjs from 'dayjs' // 引入 dayjs 用于时间格式化
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue'

/** 项目信息 列表 */
defineOptions({ name: 'iotProjectInfo' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 任务列表相关状态
const taskLoading = ref(false) // 任务列表的加载中
const taskList = ref([]) // 任务列表的数据
const selectedProject = ref(null) // 当前选中的项目
const deptList = ref([]) // 部门列表
const deviceMap = ref({}) // 设备映射表
const responsiblePersonList = ref([]) // 责任人列表

const timelineData = ref<Array<{ timestamp: string; content: string }>>([]) // 时间线数据
const taskScheduleDictOptions = ref<any[]>([]) // 任务进度字典选项
const timelineDialogVisible = ref(false) // 控制时间线弹窗显示
const currentTaskRow = ref<any>(null) // 当前选中的任务行数据

const stepsData = ref<Array<{title: string, description?: string, status?: string}>>([]) // 步骤数据
const currentStepIndex = ref(0) // 当前步骤索引

// 表格引用
const tableRef = ref()
// 表格容器引用
const tableContainerRef = ref()

const loading = ref(true) // 列表的加载中
const list = ref<IotProjectInfoVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deptId: undefined,
  deptName: undefined,
  contractName: undefined,
  contractCode: undefined,
  workloadTotal: undefined,
  workloadFinish: undefined,
  startTime: [],
  endTime: [],
  location: undefined,
  technique: undefined,
  payment: undefined,
  createTime: [],
  userName: undefined,
  userId: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const { push } = useRouter() // 路由跳转

// 列宽度配置
const columnWidths = ref({
  serial: '50px',
  manufactureName: '120px',
  contractName: '150px',
  contractCode: '120px',
  workloadTotal: '100px',
  workloadFinish: '120px',
  startTime: '150px',
  endTime: '150px',
  payment: '100px',
  createTime: '150px',
  operation: '200px'
})

// 计算文本宽度
const getTextWidth = (text: string, fontSize = 14) => {
  const span = document.createElement('span');
  span.style.visibility = 'hidden';
  span.style.position = 'absolute';
  span.style.whiteSpace = 'nowrap';
  span.style.fontSize = `${fontSize}px`;
  span.style.fontFamily = 'inherit';
  span.innerText = text;

  document.body.appendChild(span);
  const width = span.offsetWidth;
  document.body.removeChild(span);

  return width;
};

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.deptId = useUserStore().getUser.deptId;
    const data = await IotProjectInfoApi.getIotProjectInfoPage(queryParams)
    list.value = data.list
    total.value = data.total

    // 列表加载完成后，如果列表有数据，则默认选中第一行
    if (list.value.length > 0) {
      // 使用 nextTick 确保 DOM 更新后再执行选中操作
      nextTick(() => {
        showTaskList(list.value[0]);
        // 计算列宽
        calculateColumnWidths();
      });
    } else {
      // 如果没有数据，确保任务列表区域关闭
      closeTaskList();
    }

  } finally {
    loading.value = false
  }
}

// 计算列宽度
const calculateColumnWidths = () => {
  const MIN_WIDTH = 80; // 最小列宽
  const PADDING = 25; // 列内边距
  const FLEXIBLE_COLUMNS = ['manufactureName', 'contractName', 'contractCode']; // 可伸缩列

  // 确保表格容器存在
  if (!tableContainerRef.value?.$el) return;

  const container = tableContainerRef.value.$el;
  const containerWidth = container.clientWidth;

  // 1. 计算所有列的最小宽度
  const minWidths: Record<string, number> = {};
  let totalMinWidth = 0;

  // 计算列最小宽度的函数
  const calculateColumnMinWidth = (key: string, label: string, getValue: Function) => {
    const headerWidth = getTextWidth(label) * 1.2;
    let contentMaxWidth = 0;

    // 计算内容最大宽度
    list.value.forEach((row, index) => {
      const text = String(getValue ? getValue(row, index) : (row[key] || ''));
      const textWidth = getTextWidth(text);
      if (textWidth > contentMaxWidth) contentMaxWidth = textWidth;
    });

    const minWidth = Math.max(headerWidth, contentMaxWidth, MIN_WIDTH) + PADDING;
    minWidths[key] = minWidth;
    totalMinWidth += minWidth;
    return minWidth;
  };

  // 计算各列最小宽度
  calculateColumnMinWidth('serial', t('iotDevice.serial'), (row: any, index: number) => `${index + 1}`);
  calculateColumnMinWidth('manufactureName', '客户名称', (row: any) => row.manufactureName);
  calculateColumnMinWidth('contractName', '合同名称', (row: any) => row.contractName);
  calculateColumnMinWidth('contractCode', '合同编号', (row: any) => row.contractCode);
  calculateColumnMinWidth('workloadTotal', '总工作量', (row: any) => row.workloadTotal);
  calculateColumnMinWidth('workloadFinish', '已完成工作量', (row: any) => row.workloadFinish);
  calculateColumnMinWidth('startTime', '合同开始时间', (row: any) => dateFormatter2(null, null, row.startTime));
  calculateColumnMinWidth('endTime', '合同完成时间', (row: any) => dateFormatter2(null, null, row.endTime));
  calculateColumnMinWidth('payment', t('project.payment'), (row: any) => {
    const dict = getIntDictOptions(DICT_TYPE.PMS_PROJECT_SETTLEMENT)
      .find(d => d.value === row.payment);
    return dict ? dict.label : '';
  });
  calculateColumnMinWidth('createTime', '创建时间', (row: any) => dateFormatter(null, null, row.createTime));

  // 操作列固定宽度
  minWidths.operation = 200;
  totalMinWidth += 200;

  // 2. 计算可伸缩列最终宽度
  const newWidths: Record<string, string> = {};
  const availableWidth = containerWidth - 17; // 减去滚动条宽度

  // 应用最小宽度到所有列
  Object.keys(minWidths).forEach(key => {
    newWidths[key] = `${minWidths[key]}px`;
  });

  // 计算可伸缩列需要的宽度
  if (totalMinWidth < availableWidth) {
    // 有剩余空间：按比例分配给可伸缩列
    const extraSpace = availableWidth - totalMinWidth;
    const flexibleColumnCount = FLEXIBLE_COLUMNS.length;
    const spacePerColumn = Math.floor(extraSpace / flexibleColumnCount);

    FLEXIBLE_COLUMNS.forEach(key => {
      newWidths[key] = `${minWidths[key] + spacePerColumn}px`;
    });
  }

  // 3. 更新列宽配置
  columnWidths.value = newWidths;

  // 4. 触发表格重新布局
  nextTick(() => {
    tableRef.value?.doLayout();
  });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}


// 显示任务列表
const showTaskList = async (project) => {
  selectedProject.value = project
  taskLoading.value = true
  try {
    // 获取任务列表
    const queryParams = {
      projectId: project.id
    };
    const taskData = await IotProjectTaskApi.getIotProjectTaskPage(queryParams);
    taskList.value = taskData.list;

    // 收集所有设备ID和责任人ID
    const allDeviceIds = new Set();
    const allResponsiblePersonIds = new Set();

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

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

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

    // 批量获取责任人信息
    if (allResponsiblePersonIds.size > 0) {
      const personIdsArray = Array.from(allResponsiblePersonIds);
      const persons = await UserApi.companyDeptsEmployee({
        userIds: personIdsArray
      });
      responsiblePersonList.value = persons;
    }
  } catch (error) {
    console.error('加载任务列表失败:', error);
    message.error('加载任务列表失败');
  } finally {
    taskLoading.value = false;
  }
};

// 关闭任务列表
const closeTaskList = () => {
  selectedProject.value = null;
  taskList.value = [];
};

// 获取部门名称
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));
  return names.join(', ');
};

// 添加计算属性计算对话框宽度
const dialogWidth = computed(() => {
  if (stepsData.value.length === 0) return '700px';

  // 根据步骤数量计算宽度，每个步骤大约需要 200px
  const baseWidth = stepsData.value.length * 200;

  // 限制最小和最大宽度
  const minWidth = 400;
  const maxWidth = window.innerWidth * 0.9; // 最大为视口宽度的90%

  // 应用限制
  let calculatedWidth = Math.max(minWidth, baseWidth);
  calculatedWidth = Math.min(calculatedWidth, maxWidth);

  return `${calculatedWidth}px`;
});

// 获取设备名称
const getDeviceNames = (deviceIds) => {
  if (!deviceIds || deviceIds.length === 0) return '';

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

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

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

// 获取所有设备名称
const getAllDeviceNames = (deviceIds) => {
  if (!deviceIds || deviceIds.length === 0) return '无设备';

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

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

// 获取简略部门名称（用于表格显示）
const getBriefDeptNames = (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 === 0) return '';
  if (names.length > 2) {
    return `${names[0]}, ${names[1]}...`;
  }

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

// 获取所有部门名称（用于tooltip显示）
const getAllDeptNames = (deptIds) => {
  if (!deptIds || deptIds.length === 0) return '无施工队伍';
  return getDeptNames(deptIds);
};

// 获取责任人名称
const getResponsiblePersonNames = (responsiblePersonIds) => {
  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);

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

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

// 获取所有责任人名称
const getAllResponsiblePersonNames = (responsiblePersonIds) => {
  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 goToDetail = (id: number) => {
  push({
    name: 'IotProjectInfoDetail',
    params: { id }
  })
}

/** 打开 Timeline 时间线 Dialog - 已修改为 el-steps */
const openTimelineDialog = async (row: any) => {
  currentTaskRow.value = row
  timelineDialogVisible.value = true
  stepsData.value = [] // 清空旧数据
  currentStepIndex.value = -1 // 初始化为-1，不选中任何步骤

  try {
    // 获取任务进度字典
    if (taskScheduleDictOptions.value.length === 0) {
      await getTaskScheduleDictOptions()
    }

    // 获取时间线数据
    const params = { taskId: row.id } // 假设根据 taskId 获取
    const response = await IotProjectTaskScheduleApi.getIotProjectTaskSchedules(params)

    if (response && response.length > 0) {
      // 处理数据：转换时间戳、匹配字典label
      const sortedSchedules = response.sort((a, b) => a.status - b.status);

      // 生成步骤数据
      stepsData.value = sortedSchedules.map((item: any) => {
        // 格式化时间戳 (假设 startTime 是毫秒时间戳)
        const formattedTimestamp = item.startTime ? dayjs(item.startTime).format('YYYY-MM-DD HH:mm') : '时间未设置'

        // 查找 status 对应的字典 label
        const dictItem = taskScheduleDictOptions.value.find(dict => dict.value === item.status)
        const statusLabel = dictItem ? dictItem.label : `未知状态 (${item.status})`

        return {
          title: `${formattedTimestamp} ${statusLabel}`,
          description: '', // 初始为空
          status: undefined // 初始状态为任何特殊状态
        }
      })

      // 只有当任务有明确状态时才计算当前步骤
      if (row.status !== null && row.status !== undefined && row.status !== '') {
        const currentStatus = row.status;
        let activeIndex = -1;

        // 找到第一个状态大于当前任务状态的计划，当前步骤就是前一个
        for (let i = 0; i < sortedSchedules.length; i++) {
          if (currentStatus < sortedSchedules[i].status) {
            activeIndex = i - 0.5; // 中间状态
            break;
          } else if (currentStatus === sortedSchedules[i].status) {
            activeIndex = i; // 正好在这个节点上
            break;
          }
        }

        // 如果当前状态大于所有计划进度状态，则显示最后一步已完成
        if (activeIndex === -1 && sortedSchedules.length > 0) {
          if (currentStatus > sortedSchedules[sortedSchedules.length - 1].status) {
            activeIndex = sortedSchedules.length;
          } else {
            activeIndex = sortedSchedules.length - 1;
          }
        }

        currentStepIndex.value = Math.max(0, activeIndex);

        // 更新步骤数据，设置当前步骤的描述和状态
        if (currentStepIndex.value >= 0 && currentStepIndex.value < stepsData.value.length) {
          stepsData.value = stepsData.value.map((step, index) => ({
            ...step,
            description: index === currentStepIndex.value ? '当前进度' : '',
            status: index === currentStepIndex.value ? 'process' : undefined
          }))
        }
      }
    } else {
      stepsData.value = []
    }
  } catch (error) {
    console.error('获取任务进度时间线失败:', error)
    message.error('获取任务进度失败')
    stepsData.value = []
  }
}

/** 获取任务进度字典数据 */
const getTaskScheduleDictOptions = async () => {
  try {
    taskScheduleDictOptions.value = getIntDictOptions(DICT_TYPE.PMS_PROJECT_TASK_SCHEDULE)
  } catch (error) {
    console.error('获取任务进度字典失败:', error)
    taskScheduleDictOptions.value = []
  }
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if(id===undefined){
    push({ name: 'IotProjectInfo', params: { type} })
  }else{
    push({ name: 'IotProjectInfo', params: { type,id} })
  }
}

/** 分配任务操作 */
const assignTask = (row: IotProjectInfoVO) => {
  push({
    name: 'IotProjectTaskInfo',
    query: {
      projectId: row.id,
      contractName: row.contractName
    },
    params: {type: 'create'}
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    queryParams.deptId = useUserStore().getUser.deptId;
    const data = await IotProjectTaskApi.getIotProjectTaskList(queryParams)
    if(data.length===0){
      // 删除的二次确认
      await message.delConfirm()
      // 发起删除
      await IotProjectInfoApi.deleteIotProjectInfo(id)
      message.success(t('common.delSuccess'))
    }else {
      message.error(t('form.relatedProject'))
    }

    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await IotProjectInfoApi.exportIotProjectInfo(queryParams)
    download.excel(data, '项目信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 声明 ResizeObserver 实例
let resizeObserver: ResizeObserver | null = null;

/** 初始化 **/
onMounted(async () => {
  deptList.value = handleTree(await DeptApi.companyLevelChildrenDepts());
  getList()
  // 预加载任务进度字典
  getTaskScheduleDictOptions()

  // 创建 ResizeObserver 监听表格容器尺寸变化
  if (tableContainerRef.value?.$el) {
    resizeObserver = new ResizeObserver(() => {
      // 使用防抖避免频繁触发
      clearTimeout((window as any).resizeTimer);
      (window as any).resizeTimer = setTimeout(() => {
        calculateColumnWidths();
      }, 100);
    });
    resizeObserver.observe(tableContainerRef.value.$el);
  }
})

onUnmounted(() => {
  // 清除 ResizeObserver
  if (resizeObserver && tableContainerRef.value?.$el) {
    resizeObserver.unobserve(tableContainerRef.value.$el);
    resizeObserver = null;
  }

  // 清除定时器
  if ((window as any).resizeTimer) {
    clearTimeout((window as any).resizeTimer);
  }
})

// 监听列表数据变化重新计算列宽
watch(list, () => {
  nextTick(calculateColumnWidths)
}, { deep: true })

</script>

<style scoped>
/* 任务列表相关样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  padding: 0;
  min-height: auto;
}

.dept-names {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
  display: inline-block;
}

.device-names {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
  display: inline-block;
}

.responsible-names {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
  display: inline-block;
}

:deep(.el-step__description) {
  color: red !important;
}

:deep(.timeline-dialog) {
  max-width: 90vw;
}

/* 确保步骤标题完全显示 */
:deep(.timeline-dialog .el-step__title) {
  white-space: nowrap;
  overflow: visible;
  text-overflow: clip;
  max-width: none;
}

/* 调整步骤容器的布局 */
:deep(.timeline-dialog .el-steps--horizontal) {
  flex-wrap: nowrap;
  overflow-x: auto;
  justify-content: flex-start;
}

/* 调整对话框内容区域的滚动 */
:deep(.timeline-dialog .el-dialog__body) {
  overflow-x: auto;
}

/* 表格容器样式，确保水平滚动 */
.table-container {
  width: 100%;
  overflow-x: auto;
}

/* 确保表格单元格内容不换行 */
:deep(.el-table .cell) {
  white-space: nowrap;
}

/* 确保表格列标题不换行 */
:deep(.el-table th > .cell) {
  white-space: nowrap;
}

/* 调整表格最小宽度，确保内容完全显示 */
:deep(.el-table) {
  min-width: 100%;
}

/* 强制显示所有内容，防止省略号 */
:deep(.el-table td.el-table__cell),
:deep(.el-table th.el-table__cell) {
  overflow: visible !important;
}

:deep(.el-table .cell) {
  overflow: visible !important;
  text-overflow: clip !important;
}

</style>
