<template>
  <div class="add-project-container">
    <div class="add-project-content" v-loading="loading">
      <routerBack
        :show-save="!loading && !isPreview"
        :loading="loading"
        @save="saveClick"
      />
      <div class="tabs-content">
        <div class="project-tab-content-wrapper">
          <div class="tab-content">
            <el-form
              ref="formRef"
              label-width="150"
              :model="formData"
              :rules="rules"
              :disabled="isPreview"
            >
              <el-collapse
                v-model="activeCollapse"
                v-collapse-nav="navigationItems"
              >
                <!-- 项目基本信息：字段完全对齐数据库 -->
                <el-collapse-item title="项目基本信息" name="项目基本信息">
                  <el-row :gutter="24">
                    <el-col :span="12">
                      <el-form-item label="项目信息" prop="projectId">
                        <el-select
                          v-model="formData.projectId"
                          placeholder="请选择项目信息"
                          no-data-text="暂无数据"
                          @change="changeProject"
                        >
                          <el-option
                            v-for="item in projectList"
                            :key="item.id"
                            :label="item.projectName"
                            :value="item.id"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目外文名称">
                        <el-input
                          v-model="formData.projectForeignName"
                          placeholder="请输入项目外文名称"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="申报单位">
                        <el-input
                          v-model="formData.sbdw"
                          placeholder="请输入申报单位"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="所属二级企业">
                        <el-input
                          v-model="formData.ssejqy"
                          placeholder="请输入所属二级企业"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目公司名称">
                        <el-input
                          v-model="formData.xmgsmc"
                          placeholder="请输入项目公司名称"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="项目预计起始时间" prop="xmkgsjyj">
                        <el-date-picker
                          v-model="formData.xmkgsjyj"
                          type="date"
                          placeholder="请选择项目预计起始时间"
                          value-format="YYYY-MM-DD"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="项目预计完成时间">
                        <el-date-picker
                          v-model="formData.xmjgsjyj"
                          type="date"
                          placeholder="请选择项目预计完成时间"
                          value-format="YYYY-MM-DD"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="项目阶段">
                        <CommonSelector
                          v-model="formData.xmjd"
                          dictName="xmjd"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="运营年限">
                        <el-input
                          v-model="formData.yynxn"
                          :min="0"
                          placeholder="请输入运营年限"
                        >
                          <template #suffix>
                            <span>年</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="填报人">
                        <el-input
                          v-model="formData.tbr"
                          placeholder="请输入填报人"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="填报人联系电话">
                        <el-input
                          v-model="formData.tbrlxdh"
                          placeholder="请输入填报人联系电话"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="项目建设期">
                        <el-input
                          v-model="formData.xmjsqy"
                          :min="0"
                          placeholder="请输入项目建设期"
                        >
                          <template #suffix>
                            <span>月</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="项目流转状态" prop="projectLzType">
                        <CommonSelector
                          v-model="formData.projectLzType"
                          dictName="xmlzzt"
                        ></CommonSelector>
                      </el-form-item>
                    </el-col>

                    <el-col :span="20">
                      <el-form-item label="建成后成效" prop="jchcx">
                        <el-input
                          v-model="formData.jchcx"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入建成后成效"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>
                <el-collapse-item
                  title="国资委中央企业投资信息"
                  name="国资委中央企业投资信息"
                >
                  <div class="tzxx">
                    <!-- 战略类A：按数据库字段补充所有表单项 -->
                    <div class="row">
                      <div class="row_title">战略类（A类）</div>
                      <el-row :gutter="24">
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="是否国家中长期规划重大项目(A1)"
                            prop="sfgjzcqghzdxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.sfgjzcqghzdxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="是否国家有关部门下达的重点项目(A2)"
                            prop="sfgjygbmxddzdxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.sfgjygbmxddzdxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="大规模设备更新(A3)"
                            prop="dgmsbgx"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.dgmsbgx"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="战略性新兴产业百大工程(A4)"
                            prop="zlxxxcybdgc"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.zlxxxcybdgc"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="列入央企产业焕新和未来产业启航行动的项目(A5)"
                            prop="lryqcyhxhwlcyqhxddxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.lryqcyhxhwlcyqhxddxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="强链补链重点项目(A6)"
                            prop="qlblzdxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.qlblzdxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="对应重大或重点项目名录名称"
                          >
                            <el-input
                              v-model="formData.dyzdhzdxmmlmc"
                              placeholder="请输入对应重大或重点项目名录名称"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="战略性新兴产业分类（如有，必填）"
                          >
                            <el-input
                              v-model="formData.zlxxxcyfl"
                              placeholder="请输入战略性新兴产业分类"
                            />
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </div>
                    <div class="row">
                      <div class="row_title">发展类（B类）</div>

                      <!-- 发展类B：按数据库字段补充所有表单项 -->
                      <el-row :gutter="24">
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="列入企业发展战略性新兴产业工作方案的项目(B1)"
                            prop="lrqyfzzlxxxcygzfadxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.lrqyfzzlxxxcygzfadxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="粮食、能源、矿产资源保障项目(B2)"
                            prop="lsnykczybzxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.lsnykczybzxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="传统产业高端化、智能化、绿色化转型升级项目(B3)"
                            prop="ctcygdh"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.ctcygdh"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="支撑企业发展的重点项目(B4)"
                            prop="zcqyfzdddxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.zcqyfzdddxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="制造业技术改造项目"
                            prop="zzyjsgzxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.zzyjsgzxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </div>
                    <div class="row">
                      <div class="row_title">关注类（C类）</div>

                      <!-- 关注类C：按数据库字段补充所有表单项 -->
                      <el-row :gutter="24">
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="对外并购类投资项目(C1)"
                            prop="dwbgltzxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.dwbgltzxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="特别监管类项目(C2)"
                            prop="tbjglxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.tbjglxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="境外特别关注类项目(C3)"
                            prop="jwtbgzlxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.jwtbgzlxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="对外参股类投资项目(C4)"
                            prop="dwcglxtzxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.dwcglxtzxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="房地产投资项目(C5)"
                            prop="fdctzxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.fdctzxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="PPP投资项目(C6)"
                            prop="ppptzxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.ppptzxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="两高项目(C7)"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.lgxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </div>
                    <div class="row">
                      <!-- 管控类D：按数据库字段补充所有表单项 -->
                      <div class="row_title">管控类（D类）</div>

                      <el-row :gutter="24">
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="非主业投资项目(D1)"
                            prop="fzytzxm"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.fzytzxm"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="持牌金融机构(D2)"
                            prop="zpjrjg"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.zpjrjg"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="类金融机构(D3)"
                            prop="ljrjg"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.ljrjg"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="其他金融机构(D4)"
                            prop="qtjrjg"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.qtjrjg"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="基金及基金管理公司(D5)"
                            prop="jjjjjglgs"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.jjjjjglgs"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col :span="20">
                          <el-form-item
                            label-width="340px"
                            label="创业投资基金(D6)"
                            prop="cytzjj"
                          >
                            <CommonSelector
                              :radio="true"
                              v-model="formData.cytzjj"
                              dictName="sf"
                            />
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </el-collapse-item>
                <!-- 最终分类情况：补充长文本输入框 -->
                <el-collapse-item title="最终分类情况" name="最终分类情况">
                  <el-row :gutter="24">
                    <el-col :span="20">
                      <el-form-item label="最终分类情况说明">
                        <el-input
                          v-model="formData.zzflqk"
                          type="textarea"
                          :rows="5"
                          placeholder="请输入最终分类情况详细说明"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>
                <!-- 可研/决策信息（单位：万元）：独立表格，专属方法/数据源 -->
                <el-collapse-item
                  title="可研/决策信息（单位：万元）"
                  name="可研/决策信息（单位：万元）"
                >
                  <div class="kyjc-table-wrap">
                    <div class="left-table">
                      <table class="kyjc-left-table">
                        <thead>
                          <tr>
                            <td class="col-serial">序号</td>
                            <td class="col-indicator">指标项</td>
                            <td class="col-total">合计</td>
                          </tr>
                        </thead>
                        <tbody>
                          <tr
                            v-for="(row, idx) in financialIndicators"
                            :key="row.serialNumber"
                            :class="idx % 2 === 0 ? 'even-row' : 'odd-row'"
                          >
                            <td class="col-serial">{{ row.serialNumber }}</td>
                            <td
                              class="col-indicator"
                              :style="{
                                textIndent: row.level * 20 + 'px',
                                textAlign: 'left',
                              }"
                            >
                              {{ row.indicatorName }}
                            </td>
                            <td class="col-total">
                              <span v-if="!row.skipAutoTotal"
                                >{{
                                  row.total ? row.total.toFixed(2) : "0.00"
                                }}万元</span
                              >
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                    <div class="right-table">
                      <el-table
                        :data="financialIndicators"
                        border
                        :row-class-name="tableRowClassName"
                        row-key="serialNumber"
                        class="table-stripe-colors"
                      >
                        <el-table-column
                          v-for="time in dynamicTimeList"
                          :key="time"
                          :label="time"
                          width="140"
                          align="center"
                        >
                          <template #default="{ row }">
                            <el-input
                              v-if="!row.skipAutoTotal"
                              v-model="row[time]"
                              :min="0"
                              :precision="2"
                              controls-position="right"
                              @change="handleFinancialChange(row)"
                              :disabled="isPreview"
                              class="two-tone-input"
                              style="width: 100%"
                            >
                              <template #suffix>
                                <span>万元</span>
                              </template>
                            </el-input>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </div>
                </el-collapse-item>

                <!-- 年度投资计划：基础信息 -->
                <el-collapse-item title="年度投资计划" name="年度投资计划">
                  <el-row :gutter="24">
                    <el-col :span="24">
                      <div class="row_title">投资目标</div>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="计划年份" prop="jhnf">
                        <el-date-picker
                          v-model="formData.jhnf"
                          type="year"
                          format="YYYY"
                          value-format="YYYY"
                          placeholder="请选择计划年份"
                          picker-options="{ disabledDate: (date) => date > new Date() }"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="新建/续建" prop="xjXj">
                        <CommonSelector v-model="formData.xjXj" dictName="xj" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="年度投资目标" prop="ndTzMb">
                        <el-input
                          v-model="formData.ndTzMb"
                          placeholder="请输入年度投资目标"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="项目预计工期" prop="xmYjGq">
                        <el-input
                          v-model="formData.xmYjGq"
                          placeholder="请输入项目预计工期（如12个月）"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="项目融资落地时间或预计落地时间">
                        <el-date-picker
                          v-model="formData.xmRzLdSjHyyjLdSj"
                          type="date"
                          placeholder="请选择时间"
                          value-format="YYYY-MM-DD"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="预计实现资本金内部收益率"
                        prop="yjSxZbjNbsyl"
                      >
                        <el-input
                          v-model="formData.yjSxZbjNbsyl"
                          :min="0"
                          :precision="2"
                          :max="999.99"
                          controls-position="right"
                          placeholder="请输入收益率"
                          style="width: 100%"
                        >
                          <template #suffix>
                            <span>%</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="项目计划总投资类型"
                        prop="xmTzZeXmJhZtzLx"
                      >
                        <el-input
                          v-model="formData.xmTzZeXmJhZtzLx"
                          placeholder="请输入项目计划总投资类型"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="计划类型" prop="jhLx">
                        <el-input
                          v-model="formData.jhLx"
                          placeholder="请输入计划类型"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <div class="row_title">当前进展</div>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="当前进展阶段" prop="dqJzJd">
                        <el-input
                          v-model="formData.dqJzJd"
                          placeholder="请输入当前进展阶段"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="项目融资是否已经落地"
                        prop="xmRzSfYjLd"
                      >
                        <CommonSelector
                          v-model="formData.xmRzSfYjLd"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="当前进展情况" prop="dqJzQk">
                        <el-input
                          v-model="formData.dqJzQk"
                          placeholder="请输入当前进展情况"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="项目实际开工时间">
                        <el-date-picker
                          v-model="formData.xmSjKgSj"
                          type="date"
                          placeholder="请选择时间"
                          value-format="YYYY-MM-DD"
                        />
                      </el-form-item>
                    </el-col>
                    <!-- 长文本字段：span24通栏，用文本域 -->
                    <el-col :span="20">
                      <el-form-item
                        label-width="340px"
                        label="预期实现效果"
                        prop="yqSxXg"
                      >
                        <el-input
                          v-model="formData.yqSxXg"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入预期实现效果详细说明"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="20">
                      <el-form-item
                        label-width="340px"
                        label="2025年投资金额(全口径)目标(决算)与计划差异说明"
                      >
                        <el-input
                          v-model="formData.nTzJqMbjyYjhCySm"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入差异说明"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="20">
                      <el-form-item
                        label-width="340px"
                        label="2025年计划投资目标(决算)与计划差异说明"
                      >
                        <el-input
                          v-model="formData.nJhTzMbjyYjhCySm"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入差异说明"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="20">
                      <el-form-item
                        label-width="340px"
                        label="项目主要风险及主要风险应对举措"
                      >
                        <el-input
                          v-model="formData.xmZyFxJzyFxYdcj"
                          type="textarea"
                          :rows="4"
                          placeholder="请输入主要风险及对应的应对举措"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <!-- 项目年度计划表格（单位：万元）：独立子组件表格，专属方法/数据源 -->
                <el-collapse-item
                  title="项目年度计划表格（单位：万元）"
                  name="项目年度计划表格（单位：万元）"
                >
                  <div class="annualPlans">
                    <annualPlan
                      v-model="formData.xmndjh"
                      :dynamic-time-list="annualDynamicTimeList"
                      :is-preview="isPreview"
                      @handleAnnualPlanChange="handleAnnualPlanTableChange"
                    ></annualPlan>
                  </div>
                </el-collapse-item>

                <!-- 项目年度计划(资金支付口径)：金额类字段统一用数字输入框，精度2，单位万元 -->
                <el-collapse-item
                  title="项目年度计划(资金支付口径)"
                  name="项目年度计划(资金支付口径)"
                >
                  <el-row :gutter="24">
                    <el-col :span="6">
                      <el-form-item
                        label-width="180px"
                        label="资金支付比例(%)"
                        prop="zjfzBl"
                      >
                        <el-input
                          v-model="formData.zjfzBl"
                          :min="0"
                          :max="100"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        >
                          <template #suffix>
                            <span>%</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label-width="180px" label="年度计划总额">
                        <el-input
                          v-model="formData.ndJhZe"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label-width="180px" label="资本金-能建方">
                        <el-input
                          v-model="formData.zbjPtF"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label-width="180px" label="资本金-外部股东">
                        <el-input
                          v-model="formData.zbjWbGd"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label-width="180px" label="债权融资">
                        <el-input
                          v-model="formData.zqRz"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label-width="180px" label="回款再投入">
                        <el-input
                          v-model="formData.hkZtr"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label-width="180px" label="其他">
                        <el-input
                          v-model="formData.qt"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item
                        label-width="180px"
                        label="我方仅指本单位出资"
                      >
                        <el-input
                          v-model="formData.wfJzBdwCz"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>
                <!-- 2026年参股单位出资情况修正 -->
                <el-collapse-item
                  title="2026年参股单位出资情况修正(单位:万元)"
                  name="2026年参股单位出资情况修正(单位:万元)"
                >
                  <div class="tab-handle">
                    <el-button
                      v-if="!isPreview"
                      type="primary"
                      size="small"
                      @click="addGdxx"
                      >新增</el-button
                    >
                  </div>
                  <el-table
                    :data="formData.cgdwczqkxz"
                    style="width: 100%"
                    empty-text="暂无数据"
                    border
                  >
                    <el-table-column type="index" label="序号" width="60" />
                    <el-table-column
                      prop="gdmc"
                      label="单位名称"
                      min-width="200"
                    >
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.gdmc"
                          placeholder="请填写单位名称"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="cze"
                      label="我方出资额（万元）"
                      min-width="200"
                    >
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.cze"
                          placeholder="请输入我方出资额（万元）"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column prop="bz" label="差异说明" min-width="260">
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.bz"
                          type="textarea"
                          :rows="2"
                          placeholder="请输入差异说明"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      v-if="!isPreview"
                      label="操作"
                      width="80"
                      fixed="right"
                    >
                      <template #default="scope">
                        <el-button
                          link
                          type="danger"
                          size="small"
                          @click="deleteGdxx(scope.$index)"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </el-collapse-item>
              </el-collapse>
            </el-form>
          </div>
          <div class="navigation-wrapper">
            <CollapseNavigation
              :nav-items="navigationItems"
              :active-item="activeCollapse"
              title="目录导航"
              width="auto"
              @nav-click="handleNavClick"
            />
          </div>
        </div>
      </div>

      <div class="add-project-header">
        <div class="header-left"></div>
        <div class="header-right">
          <el-button type="default" @click="backClick">返回</el-button>
          <template v-if="!loading && !isPreview">
            <el-button type="primary" @click="saveClick">保存</el-button>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, getCurrentInstance, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import annualPlan from "./annualPlan.vue";
import routerBack from "@/components/common/routerBack.vue";
import CollapseNavigation from "@/components/CollapseNavigation/index.vue";
// ========== 年度计划子组件专属时间列表【核心：适配任意年份，父子唯一统一】 ==========
const annualDynamicTimeList = ref([]);

// ========== 【核心通用方法1】从表格数据自动解析基准年（适配2022/2023/任意年回显） ==========
// 解析锚点：匹配数据中的「XX-小记」字段，提取XX作为基准年，无则兜底用【系统年+1】（贴合原有新增逻辑）
const getBaseYearFromTableData = (tableData) => {
  if (!Array.isArray(tableData) || tableData.length === 0) {
    return new Date().getFullYear() + 1;
  }
  const firstRowKeys = Object.keys(tableData[0]);
  const matchKey = firstRowKeys.find((key) => key.includes("-小记"));
  if (matchKey) {
    const baseYear = Number(matchKey.split("-")[0]);
    return baseYear;
  }
  return new Date().getFullYear() + 1;
};

// ========== 【核心通用方法2】根据基准年生成时间列表（保留原有字段结构，支持传参） ==========
// 新增模式：传系统年+1；编辑模式：传解析出的基准年（2022/2023/任意）
const getCurrentYearTimeList = (baseYear) => {
  const targetYear = baseYear || new Date().getFullYear() + 1;
  const preYear = targetYear - 1;
  const timeList = [
    `${preYear}及以前`,
    `${targetYear}`,
    `${targetYear}-小记`,
    `${targetYear}-一季度`,
    `${targetYear}-二季度`,
    `${targetYear}-三季度`,
    `${targetYear}-四季度`,
    `${targetYear + 1}`,
    `${targetYear + 2}`,
    `${targetYear + 3}`,
    `${targetYear + 4}`,
    `${targetYear + 5}`,
  ];
  annualDynamicTimeList.value = timeList;
};

// ========== 参股单位出资情况修正 ==========
const addGdxx = () => {
  if (!formData.cgdwczqkxz) formData.cgdwczqkxz = [];
  formData.cgdwczqkxz.push({ gdmc: "", cze: "", bz: "" });
};
const deleteGdxx = (index) => {
  formData.cgdwczqkxz.splice(index, 1);
};

// ========== 表单验证 ==========
const formRef = ref(null);
const requiredSelect = { required: true, message: "请选择", trigger: "change" };
const requiredInput = { required: true, message: "请填写", trigger: "blur" };
const rules = {
  projectId: [{ required: true, message: "请选择项目信息", trigger: "change" }],
  projectLzType: [
    { required: true, message: "请选择审批状态", trigger: "change" },
  ],
  jchcx: [{ required: true, message: "请输入建成后成效", trigger: "blur" }],
  xmkgsjyj: [
    { required: true, message: "请选择项目预计起始时间", trigger: "change" },
  ],
  xmjgsjyj: [
    { required: true, message: "请选择项目预计完成时间", trigger: "change" },
  ],
  sfgjzcqghzdxm: [requiredSelect],
  sfgjygbmxddzdxm: [requiredSelect],
  dgmsbgx: [requiredSelect],
  zlxxxcybdgc: [requiredSelect],
  lryqcyhxhwlcyqhxddxm: [requiredSelect],
  qlblzdxm: [requiredSelect],
  lrqyfzzlxxxcygzfadxm: [requiredSelect],
  lsnykczybzxm: [requiredSelect],
  ctcygdh: [requiredSelect],
  zcqyfzdddxm: [requiredSelect],
  zzyjsgzxm: [requiredSelect],
  dwbgltzxm: [requiredSelect],
  tbjglxm: [requiredSelect],
  jwtbgzlxm: [requiredSelect],
  dwcglxtzxm: [requiredSelect],
  fdctzxm: [requiredSelect],
  ppptzxm: [requiredSelect],
  fzytzxm: [requiredSelect],
  zpjrjg: [requiredSelect],
  ljrjg: [requiredSelect],
  qtjrjg: [requiredSelect],
  jjjjjglgs: [requiredSelect],
  cytzjj: [requiredSelect],
  jhnf: [{ required: true, message: "请选择计划年份", trigger: "change" }],
  xjXj: [{ required: true, message: "请选择新建/续建", trigger: "change" }],
  ndTzMb: [{ required: true, message: "请输入年度投资目标", trigger: "blur" }],
  xmYjGq: [{ required: true, message: "请输入项目预计工期", trigger: "blur" }],
  yjSxZbjNbsyl: [
    {
      required: true,
      message: "请输入预计实现资本金内部收益率",
      trigger: "blur",
    },
  ],
  xmTzZeXmJhZtzLx: [
    { required: true, message: "请输入项目计划总投资类型", trigger: "blur" },
  ],
  jhLx: [{ required: true, message: "请输入计划类型", trigger: "blur" }],
  dqJzJd: [{ required: true, message: "请输入当前进展阶段", trigger: "blur" }],
  dqJzQk: [{ required: true, message: "请输入当前进展情况", trigger: "blur" }],
  xmRzSfYjLd: [
    {
      required: true,
      message: "请选择项目融资是否已经落地",
      trigger: "change",
    },
  ],
  yqSxXg: [{ required: true, message: "请输入预期实现效果", trigger: "blur" }],
  zjfzBl: [{ required: true, message: "请输入资金支付比例", trigger: "blur" }],
  zbjPtF: [{ required: true, message: "请输入能建方金额", trigger: "blur" }],
  zbjWbGd: [{ required: true, message: "请输入外部股东金额", trigger: "blur" }],
  zqRz: [{ required: true, message: "请输入债权融资金额", trigger: "blur" }],
  hkZtr: [{ required: true, message: "请输入回款再投入金额", trigger: "blur" }],
  qt: [{ required: true, message: "请输入其他金额", trigger: "blur" }],
};

// ========== 路由/实例/全局方法 ==========
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

// ========== 导航配置（由 v-collapse-nav 指令自动生成） ==========
const navigationItems = ref([]);

// 导航点击处理
const handleNavClick = (item) => {
  console.log("Navigation clicked:", item);

  // 等待 DOM 更新后滚动
  nextTick(() => {
    setTimeout(() => {
      const targetId = `collapse-${item.name}`;
      const targetElement = document.getElementById(targetId);

      console.log("Scrolling to element:", {
        targetId,
        found: !!targetElement,
        element: targetElement,
      });

      if (targetElement) {
        // 使用 scrollIntoView 获得更平滑的效果
        targetElement.scrollIntoView({
          behavior: "smooth",
          block: "start",
          inline: "nearest",
        });

        // 可选：添加额外的偏移量调整
        setTimeout(() => {
          const elementPosition = targetElement.getBoundingClientRect().top;
          if (elementPosition < 80) {
            // 如果距离顶部太近，向上滚动一点
            window.scrollBy({
              top: elementPosition - 80,
              behavior: "smooth",
            });
          }
        }, 300);
      } else {
        console.error("Element not found:", targetId);
        console.log(
          "Available collapse elements:",
          document.querySelectorAll('[id^="collapse-"]'),
        );
      }
    }, 300); // 增加延迟确保动画完成
  });
};

// ========== 基础配置：两个表格共用（仅时间列表，无其他关联） ==========
const activeCollapse = ref([
  "项目基本信息",
  "年度投资计划",
  "项目年度计划(资金支付口径)",
  "国资委中央企业投资信息",
  "2026年参股单位出资情况修正(单位:万元)",
  "可研/决策信息（单位：万元）",
  "项目年度计划表格（单位：万元）",
  "战略类A",
  "发展类（B类）",
  "关注类（C类）",
  "管控类（D类）",
  "最终分类情况",
]);
const loading = ref(false);
const isPreview = ref(!!route.query.isPreview);
const projectList = ref([]);
const rcCgqyglId = ref(route.query.id || "");
const timeHeaderType = ref("year"); // year/ month 切换时间表头类型
const dynamicTimeList = ref([]); // 可研表格专属时间列表，与年度计划彻底隔离

// ========== 数据源完全隔离：可研表格 & 年度计划表格 各自独立 ==========
// 1. 可研/决策信息表格：专属数据源（独立）
const financialIndicators = ref([]); // 可研表格渲染数据源

// ========== 可研/决策信息表格：原始配置+专属初始化/方法（完全独立） ==========
const financialOriginConfig = ref([
  {
    serialNumber: "1",
    indicatorName: "项目筹资(建设期投资)",
    level: 0,
    isTotal: false,
  },
  {
    serialNumber: "1.1",
    indicatorName: "项目资本金(股权融资)",
    level: 1,
    isTotal: false,
  },
  { serialNumber: "1.1.1", indicatorName: "能建方", level: 2, isTotal: false },
  {
    serialNumber: "1.1.2",
    indicatorName: "其他社会资本方",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: "1.2",
    indicatorName: "借款(债权融资)",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "1.2.1",
    indicatorName: "银行贷款",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: "1.2.1.1",
    indicatorName: "其中:非并表项目我方贷款/担保额",
    level: 3,
    isTotal: false,
  },
  { serialNumber: "1.3", indicatorName: "其他出资", level: 1, isTotal: false },
  {
    serialNumber: "1.3.1",
    indicatorName: "其中:能建方出资",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: " ",
    indicatorName: "筹资总额",
    level: 1,
    isTotal: false,
    skipAutoTotal: true,
  },
  { serialNumber: "2", indicatorName: "经营情况", level: 0, isTotal: false },
  {
    serialNumber: "2.1",
    indicatorName: "营业总收入",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "2.2",
    indicatorName: "营业总成本",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "2.2.1",
    indicatorName: "其中:营业成本",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: "2.2.2",
    indicatorName: "其中:折旧及摊销",
    level: 2,
    isTotal: false,
  },
  { serialNumber: "2.3", indicatorName: "利润总额", level: 1, isTotal: false },
  { serialNumber: "2.4", indicatorName: "所得税", level: 1, isTotal: false },
  { serialNumber: "2.5", indicatorName: "净利润", level: 1, isTotal: false },
  {
    serialNumber: "2.6",
    indicatorName: "能建方分红(税前)",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "2.7",
    indicatorName: "能建方分红(税后)",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "2.8",
    indicatorName: "未分配利润",
    level: 1,
    isTotal: false,
  },
  { serialNumber: "3", indicatorName: "资金偿还", level: 0, isTotal: false },
  { serialNumber: "3.1", indicatorName: "银行贷款", level: 1, isTotal: false },
  { serialNumber: "3.1.1", indicatorName: "项目贷", level: 2, isTotal: false },
  {
    serialNumber: "3.1.2",
    indicatorName: "项目贷利息",
    level: 2,
    isTotal: false,
  },
  { serialNumber: "3.2", indicatorName: "其他资金", level: 1, isTotal: false },
  {
    serialNumber: "3.2.1",
    indicatorName: "其他资金本金",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: "3.2.2",
    indicatorName: "其他资金利息(融资费用)",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: "4",
    indicatorName: "项目公司其他财务指标",
    level: 0,
    isTotal: false,
  },
  {
    serialNumber: "4.1",
    indicatorName: "资产总额(期末值)",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "4.2",
    indicatorName: "负债总额(期末值)",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "4.3",
    indicatorName: "经营活动产生的现金流净额",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "4.3.1",
    indicatorName: "经营活动产生的现金流入",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: "4.3.2",
    indicatorName: "经营活动产生的现金流出",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: "4.4",
    indicatorName: "投资活动产生的现金流净额",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "4.4.1",
    indicatorName: "投资活动产生的现金流入",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: "4.4.2",
    indicatorName: "投资活动产生的现金流出",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: "4.5",
    indicatorName: "筹资活动产生的现金流净额",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "4.5.1",
    indicatorName: "筹资活动产生的现金流入",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: "4.5.2",
    indicatorName: "筹资活动产生的现金流出",
    level: 2,
    isTotal: false,
  },
  {
    serialNumber: "4.6",
    indicatorName: "利息备付率",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "4.7",
    indicatorName: "偿债备付率",
    level: 1,
    isTotal: false,
  },
  {
    serialNumber: "4.8",
    indicatorName: "投资回收额",
    level: 1,
    isTotal: false,
  },
]);

// ========== 表单数据：完全对齐数据库，两个表格的JSON字段完全独立 ==========
const formData = reactive({
  // // 基础字段
  // projectId: "",
  // projectName: "",
  // projectForeignName: "",
  // sbdw: "", // 申报单位
  // ssejqy: "", // 所属二级企业
  // xmgsmc: "", // 项目公司名称
  // xmkgsjyj: "", // 项目预计起始时间
  // xmjgsjyj: "", // 项目预计完成时间
  // tbr: "", // 填报人
  // tbrlxdh: "", // 填报人联系电话
  // xmjsqy: 0, // 项目建设期（月）
  // projectLzType: "", // 项目流转状态（审批状态）
  // xmjd: "", // 项目阶段
  // yynxn: 0, // 运营年限（年）
  // jchcx: "", // 建成后成效
  // // 战略类A
  // sfgjzcqghzdxm: null,
  // sfgjygbmxddzdxm: null,
  // dgmsbgx: null,
  // zlxxxcybdgc: null,
  // lryqcyhxhwlcyqhxddxm: null,
  // qlblzdxm: null,
  // dyzdhzdxmmlmc: "",
  // zlxxxcyfl: "",
  // // 发展类B
  // lrqyfzzlxxxcygzfadxm: null,
  // lsnykczybzxm: null,
  // ctcygdh: null,
  // zcqyfzdddxm: null,
  // zzyjsgzxm: null,
  // // 关注类C
  // dwbgltzxm: null,
  // tbjglxm: null,
  // jwtbgzlxm: null,
  // dwcglxtzxm: null,
  // fdctzxm: null,
  // ppptzxm: null,
  // lgxm: null,
  // // 管控类D
  // fzytzxm: null,
  // zpjrjg: null,
  // ljrjg: null,
  // qtjrjg: null,
  // jjjjjglgs: null,
  // cytzjj: null,
  // // 最终分类
  // zzflqk: "",
  // // 两个表格的JSON字段：完全独立，无任何关联
  // kyjcxx: [], // 可研/决策信息表格：专属提交字段
  // xmndjh: [], // 项目年度计划表格：专属提交字段（子组件双向绑定）
  // // 年度投资计划基础信息
  // jhnf: "",
  // xjXj: "",
  // ndTzMb: "",
  // xmYjGq: "",
  // xmRzLdSjHyyjLdSj: "",
  // yjSxZbjNbsyl: "",
  // xmTzZeXmJhZtzLx: "",
  // jhLx: "",
  // dqJzJd: "",
  // dqJzQk: "",
  // xmRzSfYjLd: "",
  // xmSjKgSj: "",
  // yqSxXg: "",
  // nTzJqMbjyYjhCySm: "",
  // nJhTzMbjyYjhCySm: "",
  // xmZyFxJzyFxYdcj: "",
  // // 项目年度计划(资金支付口径) 金额类字段
  // zjfzBl: 0.0,
  // zqRz: 0.0,
  // ndJhZe: 0.0,
  // hkZtr: 0.0,
  // zbjPtF: 0.0,
  // qt: 0.0,
  // zbjWbGd: 0.0,
  // wfJzBdwCz: 0.0,
  cgdwczqkxz: [],
});

// ========== 【专属方法】可研/决策信息表格：初始化（独立） ==========
const initFinancialTable = () => {
  if (dynamicTimeList.value.length === 0) return;
  const tableData = financialOriginConfig.value.map((item) => {
    const row = { ...item, total: 0 };
    // 仅为可研表格的行赋值时间字段，与年度计划无关
    dynamicTimeList.value.forEach((time) => (row[time] = 0));
    return row;
  });
  financialIndicators.value = tableData;
  // 初始化可研表格的合计
  initFinancialRowTotal();
};

// ========== 【专属方法】项目年度计划表格：初始化（独立，仅新增模式执行，不覆盖接口数据） ==========
const initAnnualPlanTable = () => {
  // 仅新增模式初始化，编辑模式由接口回填，不执行此方法
  if (rcCgqyglId.value) return;
  if (annualDynamicTimeList.value.length === 0) return;
  // 生成17行带唯一id的独立数据（保留基础id，子组件会保留所有字段）
  const tableData = Array.from({ length: 25 }, (_, index) => ({
    id: index + 1, // 子组件唯一标识，必须保留
    total: 0,
    ...annualDynamicTimeList.value.reduce(
      (obj, time) => ({ ...obj, [time]: 0 }),
      {},
    ),
  }));
  formData.xmndjh = tableData;
};

// ========== 【专属方法】可研/决策信息表格：单行合计计算（独立） ==========
const updateFinancialRowTotal = (row) => {
  row.total = dynamicTimeList.value.reduce((sum, time) => {
    return sum + (Number(row[time]) || 0);
  }, 0);
};

// ========== 【专属方法】可研/决策信息表格：全量合计行更新（独立） ==========
const updateAllFinancialTotalRow = () => {
  financialIndicators.value.forEach((totalRow) => {
    if (!totalRow.isTotal || !totalRow.parentCode) return;
    totalRow.total = 0;
    dynamicTimeList.value.forEach((time) => (totalRow[time] = 0));
    totalRow.parentCode.forEach((code) => {
      const childRow = financialIndicators.value.find(
        (item) => item.serialNumber === code,
      );
      if (childRow) {
        totalRow.total += Number(childRow.total) || 0;
        dynamicTimeList.value.forEach((time) => {
          totalRow[time] += Number(childRow[time]) || 0;
        });
      }
    });
  });
};

// ========== 【专属方法】可研/决策信息表格：批量初始化合计（独立） ==========
const initFinancialRowTotal = () => {
  // 仅计算可研表格的非合计行
  financialIndicators.value.forEach(
    (row) => !row.isTotal && updateFinancialRowTotal(row),
  );
  // 仅更新可研表格的合计行
  updateAllFinancialTotalRow();
  // 同步到可研的提交字段
  formData.kyjcxx = [...financialIndicators.value];
};

// ========== 【专属方法】可研/决策信息表格：数据变更回调（独立，仅影响自身） ==========
const handleFinancialChange = (currentRow) => {
  if (isPreview.value) return;
  // 仅更新可研表格的当前行合计
  updateFinancialRowTotal(currentRow);
  // 仅更新可研表格的全量合计行
  updateAllFinancialTotalRow();
  // 仅同步可研表格的提交字段
  formData.kyjcxx = [...financialIndicators.value];
};

// ========== 【专属方法】项目年度计划表格：子组件回调（独立，仅影响自身） ==========
const handleAnnualPlanTableChange = (newData) => {
  if (isPreview.value) return;
  formData.xmndjh = newData;
};

// ========== 可研表格动态时间生成：仅可研用，与年度计划无关 ==========
const generateDynamicTime = () => {
  const now = new Date();
  const currentYear = now.getFullYear();
  const currentMonth = now.getMonth() + 1;
  const timeList = [];
  for (let i = 0; i <= 15; i++) {
    if (timeHeaderType.value === "year") {
      timeList.push(String(currentYear + i));
    } else {
      const calcYear = currentYear + Math.floor((currentMonth + i - 1) / 12);
      const calcMonth = ((currentMonth + i - 1) % 12) + 1;
      timeList.push(`${calcYear}-${calcMonth.toString().padStart(2, "0")}`);
    }
  }
  dynamicTimeList.value = timeList;
  // 仅初始化可研表格，年度计划表格单独初始化
  initFinancialTable();
};

// ========== 回填逻辑：完全隔离，各自处理自身表格 ==========
// 1. 可研/决策信息表格：专属回填（独立）
const fillFinancialTable = (backfillData) => {
  if (!Array.isArray(backfillData) || backfillData.length === 0) return;
  financialIndicators.value.forEach((frontRow) => {
    const backfillRow = backfillData.find(
      (item) =>
        item.serialNumber === frontRow.serialNumber &&
        item.indicatorName === frontRow.indicatorName,
    );
    if (!backfillRow) return;
    frontRow.total = Number(backfillRow.total) || 0;
    dynamicTimeList.value.forEach((time) => {
      frontRow[time] = Number(backfillRow[time]) || 0;
    });
  });
  // 仅初始化可研表格的合计
  initFinancialRowTotal();
};

// 2. 年度计划表格：专属回填【核心：用子组件的annualDynamicTimeList，不与可研混用】
const fillAnnualPlanTable = (backfillData) => {
  if (!Array.isArray(backfillData) || backfillData.length === 0) return;
  // 按唯一id匹配回填，保留所有原有字段，仅更新数字字段
  formData.xmndjh.forEach((frontRow) => {
    const backfillRow = backfillData.find((item) => item.id === frontRow.id);
    if (!backfillRow) return;
    // 仅赋值total，不碰其他字段
    frontRow.total = Number(backfillRow.total) || 0;
    // 仅遍历子组件的年度时间列表赋值，其他字段完全保留
    annualDynamicTimeList.value.forEach((time) => {
      frontRow[time] =
        backfillRow[time] !== undefined ? Number(backfillRow[time]) || 0 : 0;
    });
  });
};

// ========== 业务方法：获取项目列表（通用） ==========
const getProjectData = (params = {}) => {
  proxy.$post({
    url: "/api/project/listProject",
    data: {
      page: 1,
      pagesize: 1000,
      attributes: [],
      menuType: "xmjc",
      ...params,
    },
    callback: (data) => {
      projectList.value = data.rows || [];
    },
    error: () => ElMessage.warning("获取项目列表失败"),
  });
};

// ========== 选择项目同步名称（通用） ==========
const changeProject = (val) => {
  proxy.$post({
    url: "/api/project/getProjectFinalInfo",
    data: { id: val },
    callback: (data) => {
      loading.value = false;
      formData.projectName = data.projectName || "";
      if (
        data.cgdwczqkxz &&
        Array.isArray(data.cgdwczqkxz) &&
        data.cgdwczqkxz.length > 0
      ) {
        formData.cgdwczqkxz = [...data.cgdwczqkxz];
      } else {
        formData.cgdwczqkxz = [];
      }
    },
    error: () => {
      loading.value = false;
      ElMessage.error("获取项目详情失败");
    },
  });
  const selectItem = projectList.value.find((item) => item.id === val);
  if (selectItem) formData.projectName = selectItem.projectName;
};

// ========== 获取详情（编辑/预览）：核心整合【自动解析基准年+生成时间列表+回填】 ==========
const getJsqtzjcDetail = () => {
  if (!rcCgqyglId.value) return;
  loading.value = true;
  proxy.$post({
    url: "/api/project/getTzjh",
    data: { id: rcCgqyglId.value },
    callback: async (data) => {
      loading.value = false;
      if (!data) return ElMessage.error("未查询到数据");

      // 1. 回填基础字段，保留xmndjh的完整结构
      Object.assign(formData, data);

      // 回填参股单位出资情况修正
      if (
        data.cgdwczqkxz &&
        Array.isArray(data.cgdwczqkxz) &&
        data.cgdwczqkxz.length > 0
      ) {
        formData.cgdwczqkxz = [...data.cgdwczqkxz];
      }

      // 2. 可研表格：初始化时间+回填（与年度计划无关）
      if (data.kyjcxx && Array.isArray(data.kyjcxx) && data.kyjcxx.length > 0) {
        dynamicTimeList.value = Object.keys(data.kyjcxx[0]).filter((key) =>
          /^\d{4}(-\d{2})?$/.test(key),
        );
      } else {
        generateDynamicTime();
      }
      initFinancialTable();
      if (data.kyjcxx) fillFinancialTable(data.kyjcxx);

      // 3. 年度计划核心：自动解析基准年 → 生成匹配时间列表 → 等待DOM更新 → 回填
      if (data.xmndjh && Array.isArray(data.xmndjh) && data.xmndjh.length > 0) {
        const baseYear = getBaseYearFromTableData(data.xmndjh);
        getCurrentYearTimeList(baseYear);
        await nextTick(); // 强制等待时间列表生成完成，避免字段不匹配
        fillAnnualPlanTable(data.xmndjh); // 此时时间列表已就绪，安全回填
      }
    },
    error: () => {
      loading.value = false;
      ElMessage.error("获取投资计划详情失败");
    },
  });
};

// ========== 保存表单：保留原有逻辑【直接传递完整xmndjh，不过滤】 ==========
const saveClick = async () => {
  try {
    await formRef.value.validate();
  } catch {
    return ElMessage.warning("请填写所有必填项");
  }
  loading.value = true;
  const url = rcCgqyglId.value
    ? "/api/project/updateTzjh"
    : "/api/project/createTzjh";

  // 组装提交数据：【核心】xmndjh直接传递，不做任何过滤，保留所有字段
  const submitData = {
    ...formData,
    projectId: String(formData.projectId),
    // 可研表格：按需过滤（保留原有逻辑）
    kyjcxx: financialIndicators.value.map((row) => {
      const filterRow = {
        serialNumber: row.serialNumber,
        indicatorName: row.indicatorName,
        level: row.level,
        total: row.total,
      };
      dynamicTimeList.value.forEach((time) => (filterRow[time] = row[time]));
      return filterRow;
    }),
    // 年度计划表格：直接传完整的xmndjh，不做map过滤
    xmndjh: formData.xmndjh,
    cgdwczqkxz: formData.cgdwczqkxz ? [...formData.cgdwczqkxz] : [],
  };

  proxy.$post({
    url: url,
    data: submitData,
    callback: () => {
      loading.value = false;
      ElMessage.success("保存成功");
    },
    error: (err) => {
      loading.value = false;
      ElMessage.error(err.msg || "保存失败");
    },
  });
};

// ========== 辅助方法（通用） ==========
const backClick = () => router.back(-1);

// 表格单元格样式
const tableCellStyle = ({ row, columnIndex }) => {
  const baseStyle = {
    border: "1px solid #ebeef5",
  };

  if (row.isTotal) {
    return { ...baseStyle, background: "#f5f7fa", fontWeight: "bold" };
  }
  // 左边三列（序号、指标项、合计）使用 #f7faff 背景色
  if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
    return { ...baseStyle, background: "#f7faff" };
  }
  return baseStyle;
};

// 表头样式
const tableHeaderCellStyle = () => ({
  background: "#f0f2f5",
  color: "#333",
  fontWeight: "600",
  textAlign: "center",
});

// 行类名（实现斑马纹效果）
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? "even-row" : "odd-row";
};

// ========== 页面初始化：新增/编辑分离，严格保障执行顺序 ==========
onMounted(() => {
  getProjectData();
  if (rcCgqyglId.value) {
    // 编辑/预览：拉取接口数据，内部自动解析基准年+生成时间列表，不执行本地初始化
    setTimeout(() => getJsqtzjcDetail(), 100);
  } else {
    // 新增模式：先生成时间列表（系统年+1）→ 再初始化两个表格，互不影响
    getCurrentYearTimeList(); // 无参=系统年+1，贴合原有逻辑
    generateDynamicTime(); // 可研表格时间初始化
    initAnnualPlanTable(); // 年度计划表格本地初始化
  }
});
</script>
<style lang="less" scoped>
// 布局容器
.project-tab-content-wrapper {
  display: flex;
  gap: 20px;
  position: relative;
}
::v-deep .el-radio {
  margin-right: 0;
}
.tab-content {
  flex: 1;
  min-width: 0; // 防止flex子项溢出
}

.navigation-wrapper {
  flex-shrink: 0;
  width: auto;
  padding-left: 10px;
}

.row_title {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  margin: 4px;
}
.tzxx {
  display: flex;
  flex-wrap: wrap;
  .row {
    border: 1px dashed #dcdfe6;
    padding: 24px;
    width: 50%;
    .row_title {
      font-size: 18px;
      font-weight: 500;
      text-align: center;
      margin-bottom: 16px;
    }
    .el-row {
      display: flex;
      align-items: flex-start;
    }
  }
}

// 双拼色输入框样式
:deep(.two-tone-input) {
  .el-input__wrapper {
    border-radius: 0;
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    padding: 0 8px;
  }
  .el-input__inner {
    background-color: transparent !important;
    text-align: right;
    padding-right: 45px;
    color: #333;
  }
  .el-input__suffix {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    color: #606266;
    font-size: 14px;
    pointer-events: none;
  }
  &.is-focus .el-input__wrapper {
    box-shadow: 0 0 0 1px #409eff inset;
  }
}

.add-project-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  .header-right {
    display: flex;
    gap: 12px;
  }
}

// ========== 可研/决策 左右分离表格 ==========
.kyjc-table-wrap {
  display: flex;
  align-items: flex-start;
  gap: 0;
  width: 100%;
  box-sizing: border-box;
}
.kyjc-table-wrap .left-table {
  flex-shrink: 0;
  position: sticky;
  left: 0;
  z-index: 2;
  background: #f7faff;
}
.kyjc-table-wrap .right-table {
  flex: 1;
  min-width: 0;
  overflow-x: auto;
}
.kyjc-left-table {
  border-collapse: collapse;
  border: 1px solid #ebeef5;
  border-right: 0;
  background: #f7faff;
}
.kyjc-left-table td {
  height: 48px;
  border: 1px solid #ebeef5;
  padding: 0 8px;
  text-align: center;
  vertical-align: middle;
  word-break: break-all;
  box-sizing: border-box;
}
.kyjc-left-table .col-serial {
  width: 80px;
}
.kyjc-left-table .col-indicator {
  width: 300px;
}
.kyjc-left-table .col-total {
  width: 120px;
}
.kyjc-left-table thead td {
  font-weight: 600;
  background: #f0f2f5;
  color: #333;
}
.kyjc-left-table .even-row td {
  background: #f7faff;
}
.kyjc-left-table .odd-row td {
  background: #f5f5f5;
}
.kyjc-table-wrap :deep(.el-table) {
  --el-table-border-color: #ebeef5;
  border-left: 1px solid #ebeef5 !important;
}
.kyjc-table-wrap :deep(.el-table__header tr),
.kyjc-table-wrap :deep(.el-table__body tr) {
  height: 48px !important;
}
.kyjc-table-wrap :deep(.el-table-cell) {
  padding: 0 !important;
  text-align: center;
  vertical-align: middle;
  box-sizing: border-box;
}
// 斑马纹与左侧保持一致
.kyjc-table-wrap :deep(.odd-row) {
  background-color: #f5f5f5 !important;
}
.kyjc-table-wrap :deep(.even-row) {
  background-color: #edf0f5 !important;
}

// ========== 小屏适配 ==========
@media screen and (max-width: 1600px) {
  .project-tab-content-wrapper {
    gap: 12px;
  }
  .navigation-wrapper {
    padding-left: 4px;
    :deep(.collapse-navigation) {
      width: 140px !important;
      .nav-item {
        padding: 8px 10px;
      }
      .nav-text {
        font-size: 12px;
      }
    }
  }
  .kyjc-left-table .col-indicator {
    width: 200px;
  }
  .kyjc-left-table .col-total {
    width: 100px;
  }
}
@media screen and (max-width: 1280px) {
  .project-tab-content-wrapper {
    gap: 8px;
  }
  .navigation-wrapper {
    padding-left: 0;
    :deep(.collapse-navigation) {
      width: 110px !important;
      .nav-item {
        padding: 6px 8px;
      }
      .nav-text {
        font-size: 11px;
      }
      .nav-dot {
        width: 4px;
        height: 4px;
        margin-right: 4px;
      }
    }
  }
  .kyjc-left-table .col-indicator {
    width: 160px;
    font-size: 12px;
  }
  .kyjc-left-table .col-serial {
    width: 50px;
    font-size: 12px;
  }
  .kyjc-left-table .col-total {
    width: 90px;
    font-size: 12px;
  }
}
</style>
