<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <!--                                    <el-form-item label="项目ID" prop="projectId">
                                        <el-input v-model="queryParams.projectId" placeholder="请输入项目ID" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>-->
            <el-form-item label="项目编号" prop="projectCode">
              <el-input v-model="queryParams.projectCode" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目类别" prop="projectCategory">
              <el-select v-model="queryParams.projectCategory" placeholder="请选择项目类别" clearable>
                <el-option v-for="dict in project_category" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <!--                                    <el-form-item label="变更次数" prop="changeNumber">
                                        <el-input v-model="queryParams.changeNumber" placeholder="请输入变更次数" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="项目经理ID" prop="projectManagerId">
                                        <el-input v-model="queryParams.projectManagerId" placeholder="请输入项目经理ID" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="项目经理姓名" prop="projectManagerName">
                                        <el-input v-model="queryParams.projectManagerName" placeholder="请输入项目经理姓名" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="部门负责人ID" prop="deptHeadId">
                                        <el-input v-model="queryParams.deptHeadId" placeholder="请输入部门负责人ID" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="部门负责人姓名" prop="deptHeadName">
                                        <el-input v-model="queryParams.deptHeadName" placeholder="请输入部门负责人姓名" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="分管副总ID" prop="responsibleVpId">
                                        <el-input v-model="queryParams.responsibleVpId" placeholder="请输入分管副总ID" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="分管副总姓名" prop="responsibleVpName">
                                        <el-input v-model="queryParams.responsibleVpName" placeholder="请输入分管副总姓名" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="申请变更时间" prop="applyChangeDate">
                                        <el-date-picker clearable
                                                        v-model="queryParams.applyChangeDate"
                                                        type="date"
                                                        value-format="YYYY-MM-DD"
                                                        placeholder="请选择申请变更时间"
                                        />
                                    </el-form-item>
                                    <el-form-item label="项目合同额" prop="contractAmount">
                                        <el-input v-model="queryParams.contractAmount" placeholder="请输入项目合同额" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="项目合同净额" prop="contractNetAmount">
                                        <el-input v-model="queryParams.contractNetAmount" placeholder="请输入项目合同净额" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="变更原因" prop="changeReason">
                                        <el-input v-model="queryParams.changeReason" placeholder="请输入变更原因" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="后续工作" prop="followUpWork">
                                        <el-input v-model="queryParams.followUpWork" placeholder="请输入后续工作" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="项目变更状态" prop="projectChangeStatus">
                                        <el-select v-model="queryParams.projectChangeStatus" placeholder="请选择项目变更状态" clearable >
                                            <el-option v-for="dict in project_change_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
                                        </el-select>
                                    </el-form-item>-->
            <!--                                    <el-form-item label="激活标识" prop="activeFlag">
                                        <el-select v-model="queryParams.activeFlag" placeholder="请选择激活标识" clearable >
                                            <el-option v-for="dict in active_flag" :key="dict.value" :label="dict.label" :value="dict.value"/>
                                        </el-select>
                                    </el-form-item>-->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oa/erp:erpProjectChange:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
                        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/erp:erpProjectChange:edit']">修改</el-button>
                    </el-col> -->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oa/erp:erpProjectChange:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:erpProjectChange:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="erpProjectChangeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center" v-if="columns[0].visible" />
        <el-table-column label="项目变更编号" align="center" prop="projectChangeCode" width="180" v-if="columns[1].visible" />
        <el-table-column label="项目ID" align="center" prop="projectId" width="120" v-if="columns[2].visible" />
        <el-table-column label="项目编号" align="center" prop="projectCode" width="150" v-if="columns[3].visible" />
        <el-table-column label="项目名称" align="center" prop="projectName" width="200" show-overflow-tooltip v-if="columns[4].visible" />
        <el-table-column label="项目类别" align="center" prop="projectCategory" width="150" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="project_category" :value="scope.row.projectCategory" />
          </template>
        </el-table-column>
        <el-table-column label="变更类型" align="center" prop="changeType" width="100" v-if="columns[6].visible">
          <template #default="scope">
            <dict-tag :options="change_type" :value="scope.row.changeType ? scope.row.changeType.split(',') : []" />
          </template>
        </el-table-column>
        <el-table-column label="变更次数" align="center" prop="changeNumber" width="80" v-if="columns[7].visible" />
        <el-table-column label="项目经理ID" align="center" prop="projectManagerId" width="80" v-if="columns[8].visible" />
        <el-table-column label="项目经理" align="center" prop="projectManagerName" width="100" show-overflow-tooltip v-if="columns[9].visible" />
        <el-table-column label="部门负责人ID" align="center" prop="deptHeadId" width="140" v-if="columns[10].visible" />
        <el-table-column label="部门负责人" align="center" prop="deptHeadName" width="140" show-overflow-tooltip v-if="columns[11].visible" />
        <el-table-column label="分管副总ID" align="center" prop="responsibleVpId" width="140" v-if="columns[12].visible" />
        <el-table-column label="分管副总姓名" align="center" prop="responsibleVpName" width="160" show-overflow-tooltip v-if="columns[13].visible" />
        <el-table-column label="申请变更时间" align="center" prop="applyChangeDate" width="180" v-if="columns[14].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyChangeDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目合同额" align="center" prop="contractAmount" width="150" v-if="columns[15].visible" />
        <el-table-column label="项目合同净额" align="center" prop="contractNetAmount" width="150" v-if="columns[16].visible" />
        <el-table-column label="项目当前情况" align="center" prop="currentStatus" min-width="200" show-overflow-tooltip v-if="columns[17].visible" />
        <el-table-column label="变更原因" align="center" prop="changeReason" min-width="200" show-overflow-tooltip v-if="columns[18].visible" />
        <el-table-column label="后续工作" align="center" prop="followUpWork" min-width="200" show-overflow-tooltip v-if="columns[19].visible" />
        <el-table-column label="项目变更状态" align="center" prop="projectChangeStatus" width="140" v-if="columns[20].visible">
          <template #default="scope">
            <dict-tag :options="project_change_status" :value="scope.row.projectChangeStatus" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" width="140" v-if="columns[21].visible">
          <template #default="scope">
            <dict-tag :options="wf_business_status" :value="scope.row.flowStatus" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="180" show-overflow-tooltip v-if="columns[22].visible" />
        <el-table-column label="激活标识" align="center" prop="activeFlag" width="120" v-if="columns[23].visible">
          <template #default="scope">
            <dict-tag :options="active_flag" :value="scope.row.activeFlag" />
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createName" width="140" v-if="columns[24].visible" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[25].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="130" >
          <template #default="scope">
            <!-- 查看按钮：非草稿状态显示 -->
            <el-tooltip v-if="scope.row.projectChangeStatus !== '1'" content="查看" placement="top">
              <el-button link type="primary" icon="DocumentChecked" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <!-- 修改按钮：草稿、驳回或撤回状态显示 -->
            <el-tooltip
              v-if="scope.row.projectChangeStatus === '1' || scope.row.flowStatus === 'back' || scope.row.flowStatus === 'cancel'"
              content="修改"
              placement="top"
            >
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:erpProjectChange:edit']"></el-button>
            </el-tooltip>
            <!-- 新增变更按钮：仅在该项目最新且已完成的变更记录上显示 -->
            <el-tooltip v-if="isLatestCompletedChange(scope.row)" content="新增变更" placement="top">
              <el-button link type="success" icon="Plus" @click="handleAddChange(scope.row)" v-hasPermi="['oa/erp:erpProjectChange:add']"></el-button>
            </el-tooltip>
            <!-- 审批记录按钮：审批中或完成状态显示 -->
<!--            <el-tooltip v-if="scope.row.projectChangeStatus === '2' || scope.row.projectChangeStatus === '3'" content="审批记录" placement="top">-->
<!--              <el-button link type="info" icon="DocumentCopy" @click="handleApprovalRecord(scope.row)"></el-button>-->
<!--            </el-tooltip>-->
            <!-- 历史变更记录按钮 -->
            <el-tooltip content="历史变更记录" placement="top">
              <el-button link type="warning" icon="Clock" @click="handleViewHistory(scope.row)"></el-button>
            </el-tooltip>
            <!-- 删除按钮：草稿、驳回或撤回状态显示 -->
<!--            <el-tooltip-->
<!--              v-if="scope.row.projectChangeStatus === '1' || scope.row.flowStatus === 'back' || scope.row.flowStatus === 'cancel'"-->
<!--              content="删除"-->
<!--              placement="top"-->
<!--            >-->
<!--              <el-button-->
<!--                link-->
<!--                type="danger"-->
<!--                icon="Delete"-->
<!--                @click="handleDelete(scope.row)"-->
<!--                v-hasPermi="['oa/erp:erpProjectChange:remove']"-->
<!--              ></el-button>-->
<!--            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 审批记录 -->
    <ApprovalRecord ref="approvalRecordRef" />

    <!-- 项目变更历史记录抽屉 -->
    <el-drawer v-model="historyDrawer.visible" :title="historyDrawer.title" size="700px" :close-on-click-modal="true">
      <el-timeline v-if="historyDrawer.list && historyDrawer.list.length > 0">
        <el-timeline-item
          v-for="(item, index) in historyDrawer.list"
          :key="index"
          :timestamp="`第 ${item.changeNumber} 次变更 (${parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}')} 申请人: ${item.createName || '未知'})`"
          placement="top"
          type="primary"
          size="large"
        >
          <el-card shadow="hover">
            <div v-for="(msg, mIndex) in item.messages" :key="mIndex" style="margin-bottom: 15px; font-size: 14px; line-height: 1.5">
              <el-tag
                :type="msg.type === '预算变更' ? 'success' : msg.type === '情况说明' ? 'info' : 'warning'"
                size="small"
                style="margin-right: 10px"
                effect="dark"
                >{{ msg.type }}</el-tag
              >
              <span style="color: #606266">{{ msg.desc }}</span>
            </div>
            <div v-if="item.messages.length === 0" style="color: #909399; font-size: 13px">本次变更未修改预算金额与进度计划。</div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <el-empty v-else description="暂无历史变更记录数据" />
    </el-drawer>
  </div>
</template>

<script setup name="ErpProjectChange" lang="ts">
import { delErpProjectChange, listErpProjectChange, getProjectChangeHistory } from '@/api/oa/erp/erpProjectChange';
import { ErpProjectChangeQuery, ErpProjectChangeVO } from '@/api/oa/erp/erpProjectChange/types';
import { useRoute, useRouter } from 'vue-router';
import { onActivated } from 'vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';

const route = useRoute();
const router = useRouter();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const refreshFlagKey = 'erpProjectChangeListShouldRefresh';
const { active_flag, change_type, project_change_status, project_category, wf_business_status, project_phases } = toRefs<any>(
  proxy?.useDict('active_flag', 'change_type', 'project_change_status', 'project_category', 'wf_business_status', 'project_phases')
);

// 项目变更列表数据（表格数据源）
const erpProjectChangeList = ref<ErpProjectChangeVO[]>([]);
// 记录每个项目最新且已完成的变更次数，用于控制“新增变更”按钮显示
const latestCompletedChangeMap = ref<Record<string, number>>({});
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `序号`, visible: true },
  { key: 1, label: `项目变更编号`, visible: true },
  { key: 2, label: `项目ID`, visible: false },
  { key: 3, label: `项目编号`, visible: true },
  { key: 4, label: `项目名称`, visible: true },
  { key: 5, label: `项目类别`, visible: true },
  { key: 6, label: `变更类型`, visible: true },
  { key: 7, label: `变更次数`, visible: true },
  { key: 8, label: `项目经理ID`, visible: false },
  { key: 9, label: `项目经理`, visible: true },
  { key: 10, label: `部门负责人ID`, visible: false },
  { key: 11, label: `部门负责人`, visible: true },
  { key: 12, label: `分管副总ID`, visible: false },
  { key: 13, label: `分管副总姓名`, visible: false },
  { key: 14, label: `申请变更时间`, visible: true },
  { key: 15, label: `项目合同额`, visible: false },
  { key: 16, label: `项目合同净额`, visible: false },
  { key: 17, label: `项目当前情况`, visible: false },
  { key: 18, label: `变更原因`, visible: false },
  { key: 19, label: `后续工作`, visible: false },
  { key: 20, label: `项目变更状态`, visible: true },
  { key: 21, label: `流程状态`, visible: false },
  { key: 22, label: `备注`, visible: false },
  { key: 23, label: `激活标识`, visible: false },
  { key: 24, label: `创建人`, visible: true },
  { key: 25, label: `创建时间`, visible: true }
]);

// 查询表单参数（分页+筛选条件），与页面搜索区域绑定
const data = reactive<{ queryParams: ErpProjectChangeQuery }>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: undefined,
    projectCode: undefined,
    projectName: undefined,
    projectCategory: undefined,
    changeType: undefined,
    changeNumber: undefined,
    projectManagerId: undefined,
    projectManagerName: undefined,
    deptHeadId: undefined,
    deptHeadName: undefined,
    responsibleVpId: undefined,
    responsibleVpName: undefined,
    applyChangeDate: undefined,
    contractAmount: undefined,
    contractNetAmount: undefined,
    currentStatus: undefined,
    changeReason: undefined,
    followUpWork: undefined,
    projectChangeStatus: undefined,
    flowStatus: undefined,
    activeFlag: undefined,
    params: {}
  }
});

const { queryParams } = toRefs(data);

/** 查询项目变更申请列表 */
const getList = async () => {
  loading.value = true;
  const res = await listErpProjectChange(queryParams.value);
  erpProjectChangeList.value = res.rows;
  total.value = res.total;
  // 先按项目统计每个项目最新的变更次数（changeNumber 最大值）
  const latestNumberMap: Record<string, number> = {};
  erpProjectChangeList.value.forEach((item) => {
    const pid = String(item.projectId);
    const num = item.changeNumber ?? 0;
    if (!latestNumberMap[pid] || num > latestNumberMap[pid]) {
      latestNumberMap[pid] = num;
    }
  });
  // 再从中筛选出“状态为已完成(3)且为最新一次变更”的记录，用于控制是否允许继续新增变更
  const completedMap: Record<string, number> = {};
  erpProjectChangeList.value.forEach((item) => {
    if (item.projectChangeStatus === '3') {
      const pid = String(item.projectId);
      const num = item.changeNumber ?? 0;
      if (latestNumberMap[pid] === num) {
        completedMap[pid] = num;
      }
    }
  });
  latestCompletedChangeMap.value = completedMap;
  loading.value = false;
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: ErpProjectChangeVO[]) => {
  ids.value = selection.map((item) => item.projectChangeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作（与项目信息保持一致） */
const handleAdd = () => {
  proxy?.$tab.closePage(route);
  router.push({
    path: '/project/erpProjectChange/edit',
    query: { type: 'add' }
  });
};

/** 修改按钮操作（与项目信息保持一致） */
const handleUpdate = (row?: ErpProjectChangeVO) => {
  const _projectChangeId = row?.projectChangeId || ids.value[0];
  proxy?.$tab.closePage(route);
  router.push({
    path: '/project/erpProjectChange/edit',
    query: { id: _projectChangeId, type: 'update' }
  });
};

/** 查看按钮操作（与项目信息保持一致） */
const handleView = (row: ErpProjectChangeVO) => {
  proxy?.$tab.closePage(route);
  router.push({
    path: '/project/erpProjectChange/edit',
    query: { id: row.projectChangeId, type: 'view' }
  });
};

// 判断当前行是否为该项目“最新且已审批完成”的变更记录
// 只有满足该条件时，列表中才显示“新增变更”按钮
const isLatestCompletedChange = (row: ErpProjectChangeVO) => {
  if (row.projectChangeStatus !== '3') {
    return false;
  }
  const pid = String(row.projectId);
  return latestCompletedChangeMap.value[pid] === row.changeNumber;
};

/** 新增变更按钮操作（与项目信息保持一致） */
const handleAddChange = (row: ErpProjectChangeVO) => {
  proxy?.$tab.closePage(route);
  router.push({
    path: '/project/erpProjectChange/edit',
    query: { type: 'add', projectId: row.projectId }
  });
};

/** 审批记录按钮操作 */
const handleApprovalRecord = (row: ErpProjectChangeVO) => {
  approvalRecordRef.value?.init(row.projectChangeId);
};

// ================ 历史变更记录查看相关 ================
const historyDrawer = reactive({
  visible: false,
  title: '',
  list: [] as any[]
});

const handleViewHistory = async (row: any) => {
  historyDrawer.title = `变更历史记录（${row.projectName}）`;
  historyDrawer.visible = true;
  historyDrawer.list = [];

  try {
    proxy?.$modal.loading('正在提取变更历史记录...');
    const res = await getProjectChangeHistory(row.projectId);
    if (res.data) {
      const records = res.data;
      const historyList = [];

      const previousBudget: Record<string, number> = {};
      const previousProgressContent: Record<string, any> = {};
      const previousBasicInfo: Record<string, string> = {
        currentStatus: '',
        changeReason: '',
        followUpWork: ''
      };

      for (let i = 0; i < records.length; i++) {
        const item = records[i];
        const messages: any[] = [];

        // 1. 预算变更详情提取
        if (item.budgetList && item.budgetList.length > 0) {
          item.budgetList.forEach((budget: any) => {
            const after = Number(budget.budgetAfter || 0);
            const prev = previousBudget[budget.subjectName];
            // 第一次变更的变更前预算直接取本次自身的数据
            const before = prev !== undefined ? prev : Number(budget.budgetBefore || 0);

            if (before !== after) {
              messages.push({
                type: '预算变更',
                desc: `将预算变更中的【${budget.subjectName}】从变更前预算的 ${before.toFixed(2)} 变为变更后预算的 ${after.toFixed(2)}`
              });
            }
            // 记录该科目本次变更的最后状态，供下一次比对
            previousBudget[budget.subjectName] = after;
          });
        }

        // 2. 进度变更详情提取
        if (item.progressList && item.progressList.length > 0) {
          item.progressList.forEach((progress: any) => {
            const phaseKey = progress.planStageId; // 使用原计划阶段ID作为不变的唯一Key，防止为空时所有阶段混在一起
            const prev = previousProgressContent[phaseKey] || {
              start: progress.originalStart,
              end: progress.originalEnd,
              milestone: ''
            };

            const diffs = [];
            let startChanged = false;
            let endChanged = false;

            // 对比开始时间
            if (prev.start && progress.changedStart && prev.start !== progress.changedStart) {
              diffs.push(
                `原计划时间起的 ${proxy?.parseTime(prev.start, '{y}-{m}-{d}')} 变为变更后时间起的 ${proxy?.parseTime(progress.changedStart, '{y}-{m}-{d}')}`
              );
              startChanged = true;
            }
            // 对比结束时间
            if (prev.end && progress.changedEnd && prev.end !== progress.changedEnd) {
              diffs.push(
                `原计划时间止的 ${proxy?.parseTime(prev.end, '{y}-{m}-{d}')} 变为变更后时间止的 ${proxy?.parseTime(progress.changedEnd, '{y}-{m}-{d}')}`
              );
              endChanged = true;
            }
            // 里程碑变动情况
            let msDiff = '';
            // 判断是否是该阶段首次填入或与上一次填写的里程碑名不一致
            if (progress.milestoneName && prev.milestone !== progress.milestoneName) {
              const oldName = prev.milestone ? `“${prev.milestone}”` : '空白';
              msDiff = `里程碑名称从原来的${oldName}变为“${progress.milestoneName}”`;
            }

            if (diffs.length > 0 || msDiff) {
              const phaseLabel = proxy?.selectDictLabel(project_phases.value, progress.projectPhases) || progress.projectPhases || '未知';
              const diffStr = diffs.join('，');
              let finalDescText = diffStr;

              if (finalDescText && msDiff) {
                finalDescText += `，同时将${msDiff}`;
              } else if (msDiff) {
                finalDescText = `将${msDiff}`;
              }

              messages.push({
                type: '进度变更',
                desc: `将进度变更中【${phaseLabel}】阶段的 ` + finalDescText
              });
            }

            // 更新本次阶段的最终状态供后续比较，如果没有更改则继承上次的值（如果在本次记录中这些字段为空的话）
            previousProgressContent[phaseKey] = {
              start: startChanged ? progress.changedStart : prev.start,
              end: endChanged ? progress.changedEnd : prev.end,
              milestone: progress.milestoneName
            };
          });
        }

        // 3. 项目说明信息详情提取
        const basicDiffs = [];
        if (item.currentStatus && item.currentStatus !== previousBasicInfo.currentStatus) {
          const oldVal = previousBasicInfo.currentStatus ? `“${previousBasicInfo.currentStatus}”` : '空白';
          basicDiffs.push(`当前情况由 ${oldVal} 变更为 “${item.currentStatus}”`);
        }
        if (item.changeReason && item.changeReason !== previousBasicInfo.changeReason) {
          const oldVal = previousBasicInfo.changeReason ? `“${previousBasicInfo.changeReason}”` : '空白';
          basicDiffs.push(`变更原因由 ${oldVal} 变更为 “${item.changeReason}”`);
        }
        if (item.followUpWork && item.followUpWork !== previousBasicInfo.followUpWork) {
          const oldVal = previousBasicInfo.followUpWork ? `“${previousBasicInfo.followUpWork}”` : '空白';
          basicDiffs.push(`后续工作由 ${oldVal} 变更为 “${item.followUpWork}”`);
        }

        if (basicDiffs.length > 0) {
          messages.push({
            type: '情况说明',
            desc: basicDiffs.join('，')
          });
        }

        // 更新本次基础信息状态供下次对比使用
        previousBasicInfo.currentStatus = item.currentStatus || previousBasicInfo.currentStatus;
        previousBasicInfo.changeReason = item.changeReason || previousBasicInfo.changeReason;
        previousBasicInfo.followUpWork = item.followUpWork || previousBasicInfo.followUpWork;

        historyList.push({
          changeNumber: item.changeNumber,
          createTime: item.createTime,
          createName: item.createName || item.projectManagerName,
          messages: messages
        });
      }
      historyDrawer.list = historyList;
    }
  } catch (error) {
    console.error('加载变更历史记录失败', error);
  } finally {
    proxy?.$modal.closeLoading();
  }
};
// ========================================================

/** 删除按钮操作 */
const handleDelete = async (row?: ErpProjectChangeVO) => {
  const _projectChangeIds = row?.projectChangeId || ids.value;
  await proxy?.$modal.confirm('是否确认删除项目变更申请编号为"' + _projectChangeIds + '"的数据项？').finally(() => (loading.value = false));
  await delErpProjectChange(_projectChangeIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/erp/erpProjectChange/export',
    {
      ...queryParams.value
    },
    `erpProjectChange_${new Date().getTime()}.xlsx`
  );
};

/** 检查是否需要刷新列表 */
const checkShouldRefresh = () => {
  const flag = sessionStorage.getItem(refreshFlagKey);
  if (flag) {
    sessionStorage.removeItem(refreshFlagKey);
    handleQuery();
  }
};

onMounted(() => {
  getList();
  checkShouldRefresh();
});

onActivated(() => {
  checkShouldRefresh();
});
</script>
