<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 :model="formData" label-width="150" :disabled="isPreview">
              <el-collapse
                v-model="activeCollapse"
                v-collapse-nav="navigationItems"
              >
                <el-collapse-item title="项目基本信息" name="项目基本信息">
                  <el-row :gutter="24">
                    <el-col :span="24">
                      <el-form-item label="年度" required>
                        <el-date-picker
                          v-model="formData.nd"
                          type="year"
                          placeholder="请选择年度"
                          format="YYYY"
                          value-format="YYYY"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目名称" required>
                        <el-select
                          v-model="formData.projectId"
                          :disabled="projectDisabled"
                          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.xmgsmc"
                          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="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="财务报表类型">
                        <CommonSelector
                          v-model="formData.cwbblx"
                          dictName="cwbblx"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="项目类别">
                        <CommonSelector
                          v-model="formData.xmlx"
                          dictName="xmlx"
                        ></CommonSelector>
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="所属行业">
                        <CommonSelector
                          v-model="formData.sshy"
                          dictName="participation_industry"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="投资模式分类">
                        <CommonSelector
                          v-model="formData.tzms"
                          dictName="tzms"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="投资回收方式">
                        <CommonSelector
                          v-model="formData.tzhsfs"
                          dictName="tzhsfs"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item label="下年项目阶段">
                        <CommonSelector
                          v-model="formData.xnxmjd"
                          dictName="xmjd"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <DynamicTable
                    :columns="transferColumns"
                    :disabled="isPreview"
                    v-model="formData.projectGdxxs"
                  >
                  </DynamicTable>
                </el-collapse-item>

                <el-collapse-item title="投资额完成情况" name="投资额完成情况"
                  ><el-row gutter="20">
                    <el-col :span="12">
                      <el-form-item
                        label-width="160px"
                        label="项目投资总额（决策值）"
                      >
                        <el-input
                          precision="2"
                          v-model="formData.tzzejc"
                          placeholder="请输入项目投资总额（决策值）"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label-width="160px"
                        label="我方资本金出资额-决策值"
                      >
                        <el-input
                          precision="2"
                          v-model="formData.wfzbjczejc"
                          placeholder="请输入我方资本金出资额-决策值"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label-width="160px"
                        :label="`投资总额${currentYear - 1}实际值`"
                      >
                        <el-input
                          precision="2"
                          v-model="formData.tzzesj"
                          :placeholder="`投资总额${currentYear - 1}实际值`"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label-width="160px"
                        label="我方资本金出资额--实际值"
                      >
                        <el-input
                          precision="2"
                          v-model="formData.wfzbjczesj"
                          placeholder="请输入我方资本金出资额--实际值"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label-width="160px"
                        :label="`投资总额${currentYear}计划值`"
                      >
                        <el-input
                          precision="2"
                          v-model="formData.tzzejhz"
                          :placeholder="`投资总额${currentYear}计划值`"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <!-- <el-collapse-item
                  :title="dynamicTitles.yearlyUpdateTitle"
                  :name="dynamicTitles.yearlyUpdateTitle"
                >
                  <el-row gutter="20">
                    <el-col :span="12">
                      <el-form-item
                        label-width="160px"
                        label="本年完成 投资回收决策目标值"
                      >
                        <el-input
                          precision="2"
                          v-model="formData.bnwc"
                          type="number"
                          placeholder="请输入本年完成 投资回收决策目标值"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label-width="160px"
                        label="截止本年累计（决策目标值）"
                      >
                        <el-input
                          precision="2"
                          v-model="formData.jzbnlj"
                          type="number"
                          placeholder="请输入截止本年累计（决策目标值）"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label-width="160px" label="下一年完成数">
                        <el-input
                          precision="2"
                          v-model="formData.xynwcs"
                          type="number"
                          placeholder="请输入下一年完成数"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label-width="160px" label="本年计划">
                        <el-input
                          precision="2"
                          v-model="formData.bnjh"
                          type="number"
                          placeholder="请输入本年计划"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item
                        label-width="160px"
                        label="本年完成--投资回收实际值"
                      >
                        <el-input
                          precision="2"
                          v-model="formData.bnwcsjz"
                          type="number"
                          placeholder="请输入本年完成--投资回收实际值"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label-width="160px"
                        label="截止本年累计--投资回收实际值"
                      >
                        <el-input
                          precision="2"
                          v-model="formData.jzbnljsjz"
                          type="number"
                          placeholder="请输入截止本年累计--投资回收实际值"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label-width="160px" label="累计欠收">
                        <el-input
                          precision="2"
                          v-model="formData.ljqs"
                          type="number"
                          placeholder="请输入累计欠收"
                        >
                          <template #suffix>
                            <span>万元</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label-width="160px" label="完成率">
                        <el-input
                          precision="2"
                          v-model="formData.wcl"
                          type="number"
                          placeholder="请输入完成率"
                        >
                          <template #suffix>
                            <span>%</span>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="24">
                      <el-form-item label="计划与决策目标值差异说明">
                        <el-input
                          v-model="formData.jhyjcmbcysm"
                          type="textarea"
                          rows="3"
                          placeholder="请输入计划与决策目标值差异说明"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="实际与计划差异说明">
                        <el-input
                          v-model="formData.sjyjhcysm"
                          type="textarea"
                          rows="3"
                          placeholder="请输入实际与计划差异说明"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="存在主要问题">
                        <el-input
                          v-model="formData.czdzywt"
                          type="textarea"
                          rows="3"
                          placeholder="请输入存在主要问题"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="采取措施及开展情况">
                        <el-input
                          v-model="formData.cqcsjgzkzqk"
                          type="textarea"
                          rows="3"
                          placeholder="请输入采取措施及开展情况"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="备注">
                        <el-input
                          v-model="formData.bz"
                          type="textarea"
                          rows="3"
                          placeholder="请输入备注"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item> -->
                <el-collapse-item
                  :title="dynamicTitles.yearlyUpdateTitle"
                  :name="dynamicTitles.yearlyUpdateTitle"
                >
                  <InvestmentRecoveryTable
                    v-model="formData.tzhsjc"
                    :is-preview="isPreview"
                    table-type="plan"
                    :table-title="`${currentYear}年投资回收计划`"
                  />
                </el-collapse-item>

                <!-- <el-collapse-item
                  title="截止12月末累计应收"
                  name="截止12月末累计应收"
                >
                  <FinancialTable
                    v-model="formData.jzymljys"
                    :is-preview="isPreview"
                  />
                </el-collapse-item>

                <el-collapse-item
                  title="截止12月末累计实收"
                  name="截止12月末累计实收"
                >
                  <FinancialTable
                    v-model="formData.jzymljsh"
                    :is-preview="isPreview"
                  />
                </el-collapse-item> -->

                <!-- <el-collapse-item
                  title="投资回收（计划）"
                  name="投资回收（计划）"
                >
                  <FinancialTable
                    v-model="formData.tzhsjh"
                    :showSerialColumn="false"
                    :is-preview="isPreview"
                    :showNameColumn="false"
                    :showTotalColumn="false"
                  />
                </el-collapse-item> -->

                <el-collapse-item
                  :title="dynamicTitles.yearlyCompletionTitle"
                  :name="dynamicTitles.yearlyCompletionTitle"
                >
                  <InvestmentRecoveryTable
                    v-model="formData.tzhswcqkndgx"
                    :is-preview="isPreview"
                    table-type="year"
                    :table-title="dynamicTitles.yearlyCompletionTitle"
                  />
                </el-collapse-item>

                <el-collapse-item
                  :title="dynamicTitles.monthlyCompletionTitle"
                  :name="dynamicTitles.monthlyCompletionTitle"
                >
                  <InvestmentRecoveryTable
                    v-model="formData.tzhswcqkydgx"
                    :is-preview="isPreview"
                    table-type="month"
                    :table-title="dynamicTitles.monthlyCompletionTitle"
                    :plan-data="formData.tzhsjh"
                    :decision-data="formData.tzhsjc"
                    :last-year-plan-data="formData.lastyeartzhs"
                    :yearly-plan-data="formData.tzhsjc"
                    :yearly-completion-data="formData.tzhswcqkndgx"
                    :current-year="currentYear"
                  />
                </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>

      <!-- 预览模式底部信息区域 -->
      <el-collapse
        v-model="activeCollapse"
        v-if="isPreview"
        style="margin-top: 20px"
      >
        <el-collapse-item title="相关信息" name="相关信息">
          <div style="padding: 20px; color: #909399; text-align: center">
            <p>此为预览模式，如需编辑请返回列表页点击"编辑"按钮</p>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script setup>
import {
  reactive,
  watch,
  ref,
  onMounted,
  getCurrentInstance,
  h,
  computed,
  nextTick,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import DynamicTable from "@/components/FormDynamicTable/index.vue";
import FinancialTable from "@/components/FinancialTable.vue";
import InvestmentRecoveryTable from "@/components/InvestmentRecoveryTable.vue";
import routerBack from "@/components/common/routerBack.vue";
import CollapseNavigation from "@/components/CollapseNavigation/index.vue";
import { useProjectDetail } from "@/composables/useProjectDetail";
const transferColumns = ref([
  {
    prop: "njfcgbl",
    label: "能建方持股比例",
    type: "input",
    headerGroup: "能建内容",
    placeholder: "请填写能建方持股比例",
  },
  {
    prop: "njfcgblqk",
    label: "能建方持股比例情况",
    type: "input",
    headerGroup: "能建内容",
    placeholder: "请填写能建方持股比例情况",
  },
  {
    prop: "njfcgqk",
    label: "能建外持股比例情况",
    type: "textarea",
    headerGroup: "能建以外",
    placeholder: "请填写能建外持股比例情况",
  },
  {
    prop: "zwfcgbl",
    label: "政府方持股比例",
    type: "input",
    headerGroup: "能建以外",
    placeholder: "请填写政府方持股比例",
  },
  {
    prop: "jjcgbl",
    label: "基金持股比例",
    type: "input",
    headerGroup: "能建以外",
    placeholder: "请输入基金持股比例",
    min: 0,
  },
  {
    prop: "njfglmc",
    label: "能建方关联名称",
    headerGroup: "能建以外",
    type: "textarea",
    placeholder: "请输入能建方关联名称",
  },
]);
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

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

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

  // 点击导航时自动展开对应的折叠面板
  if (!activeCollapse.value.includes(item.name)) {
    activeCollapse.value.push(item.name);
  }

  // 等待 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); // 增加延迟确保动画完成
  });
};

// 表单数据
let initTableData = () => {
  // 使用 Object.assign 直接替换整个对象，而不是合并
  formData.jzymljys = {
    indicatorList: [
      { name: "一月", isTextRow: false, noTotal: false },
      { name: "二月", isTextRow: false, noTotal: false },
      { name: "三月", isTextRow: false, noTotal: false },
      { name: "四月", isTextRow: false, noTotal: false },
      { name: "五月", isTextRow: false, noTotal: false },
      { name: "六月", isTextRow: false, noTotal: false },
      { name: "七月", isTextRow: false, noTotal: false },
      { name: "八月", isTextRow: false, noTotal: false },
      { name: "九月", isTextRow: false, noTotal: false },
      { name: "十月", isTextRow: false, noTotal: false },
      { name: "十一月", isTextRow: false, noTotal: false },
      { name: "十二月", isTextRow: false, noTotal: false },
    ],

    dynamicTimeList: [
      { label: "政府付费", prop: "a1" },
      { label: "政府补贴", prop: "a2" },
      { label: "使用者付费", prop: "a3" },
      { label: "使用者欠付", prop: "a4" },
      { label: "补贴收入", prop: "a5" },
      {
        label: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
        prop: "a6",
      },
      { label: "资产盘活", prop: "a7" },
      { label: "股权分红", prop: "a8" },
      { label: "其他", prop: "a9" },
      {
        label: "目标（决策）与计划差异说明",
        prop: "a10",

        isTextRow: true,
      },
    ],

    // 表格数据（子组件自动初始化，无需手动赋值）
    tableData: [],
  };

  formData.jzymljsh = {
    indicatorList: [
      { name: "一月", isTextRow: false, noTotal: false },
      { name: "二月", isTextRow: false, noTotal: false },
      { name: "三月", isTextRow: false, noTotal: false },
      { name: "四月", isTextRow: false, noTotal: false },
      { name: "五月", isTextRow: false, noTotal: false },
      { name: "六月", isTextRow: false, noTotal: false },
      { name: "七月", isTextRow: false, noTotal: false },
      { name: "八月", isTextRow: false, noTotal: false },
      { name: "九月", isTextRow: false, noTotal: false },
      { name: "十月", isTextRow: false, noTotal: false },
      { name: "十一月", isTextRow: false, noTotal: false },
      {
        name: "十二月",
        isTextRow: false,
        noTotal: false,
      },
    ],

    dynamicTimeList: [
      { label: "政府付费", prop: "a1" },
      { label: "政府补贴", prop: "a2" },
      { label: "使用者付费", prop: "a3" },
      { label: "使用者欠付", prop: "a4" },
      { label: "补贴收入", prop: "a5" },
      {
        label: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
        prop: "a6",
      },
      { label: "资产盘活", prop: "a7" },
      { label: "股权分红", prop: "a8" },
      { label: "其他", prop: "a9" },
      {
        label: "目标（决策）与计划差异说明",
        prop: "a10",

        isTextRow: true,
      },
    ],

    // 表格数据（子组件自动初始化，无需手动赋值）
    tableData: [],
  };

  formData.tzhsjc = {
    // 指标列表
    indicatorList: [
      { name: "建设期政府付费", isTextRow: false, noTotal: false },
      { name: "运营期政府付费", isTextRow: false, noTotal: false },
      { name: "投资价差收取", isTextRow: false, noTotal: false },
      { name: "参股项目投资回收", isTextRow: false, noTotal: false },
      { name: "代建工程款回收", isTextRow: false, noTotal: false },
      { name: "政府付费", isTextRow: false, noTotal: false },
      { name: "政府补贴", isTextRow: false, noTotal: false },
      { name: "使用者付费", isTextRow: false, noTotal: false },
      { name: "使用者欠付", isTextRow: false, noTotal: false },
      { name: "补贴收入", isTextRow: false, noTotal: false },
      {
        name: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
        isTextRow: false,
        noTotal: false,
      },
      { name: "资产盘活", isTextRow: false, noTotal: false },
      { name: "股权分红", isTextRow: false, noTotal: false },
      { name: "其他", isTextRow: false, noTotal: false },
      // 关键：标记为文本行+不需要合计
      { name: "目标（决策）与计划差异说明", isTextRow: true, noTotal: true },
    ],

    // 时间列表（月度）
    dynamicTimeList: ["一季度", "二季度", "三季度", "四季度"],
    // 表格数据（子组件会自动初始化，父组件可传初始值）
    tableData: [],
  };

  formData.tzhsjh = {
    // 指标列表
    indicatorList: [
      {
        name: " ",
      },
    ],

    // 时间列表（月度）- 使用动态年度
    get dynamicTimeList() {
      const year = formData.nd;
      const yearStr = `${year}年`;
      const q1Str = `${year}年（一季度）`;
      const q2Str = `${year}年（二季度）`;
      const q3Str = `${year}年（三季度）`;
      const q4Str = `${year}年（四季度）`;

      return [
        // 第一组：投资回收（决策） -> 动态年度
        {
          label: "合计",
          prop: "a1",
          headerGroup: "投资回收（决策）",
          subGroup: yearStr,
        },
        {
          label: "政府付费",
          prop: "a2",
          headerGroup: "投资回收（决策）",
          subGroup: yearStr,
        },
        {
          label: "政府补助",
          prop: "a3",
          headerGroup: "投资回收（决策）",
          subGroup: yearStr,
        },
        {
          label: "使用者付费",
          prop: "a4",
          headerGroup: "投资回收（决策）",
          subGroup: yearStr,
        },
        {
          label: "使用者欠付",
          prop: "a5",
          headerGroup: "投资回收（决策）",
          subGroup: yearStr,
        },
        {
          label: "补贴收入",
          prop: "a6",
          headerGroup: "投资回收（决策）",
          subGroup: yearStr,
        },
        {
          label: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
          prop: "a7",
          headerGroup: "投资回收（决策）",
          subGroup: yearStr,
        },
        {
          label: "资产盘活",
          prop: "a8",
          headerGroup: "投资回收（决策）",
          subGroup: yearStr,
        },
        {
          label: "股权分红",
          prop: "a9",
          headerGroup: "投资回收（决策）",
          subGroup: yearStr,
        },
        {
          label: "其他",
          prop: "a10",
          headerGroup: "投资回收（决策）",
          subGroup: yearStr,
        },
        {
          label: "目标（决策）与计划差异说明",
          isTextRow: true,
          prop: "a11",
          headerGroup: "投资回收（决策）",
          subGroup: yearStr,
        },

        {
          label: "合计",
          prop: "a34",
          headerGroup: "投资回收（计划）",
          subGroup: yearStr,
        },
        {
          label: "政府付费",
          prop: "a35",
          headerGroup: "投资回收（计划）",
          subGroup: yearStr,
        },
        {
          label: "政府补助",
          prop: "a36",
          headerGroup: "投资回收（计划）",
          subGroup: yearStr,
        },
        {
          label: "使用者付费",
          prop: "a37",
          headerGroup: "投资回收（计划）",
          subGroup: yearStr,
        },
        {
          label: "使用者欠付",
          prop: "a38",
          headerGroup: "投资回收（计划）",
          subGroup: yearStr,
        },
        {
          label: "补贴收入",
          prop: "a39",
          headerGroup: "投资回收（计划）",
          subGroup: yearStr,
        },
        {
          label: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
          prop: "a40",
          headerGroup: "投资回收（计划）",
          subGroup: yearStr,
        },
        {
          label: "资产盘活",
          prop: "a41",
          headerGroup: "投资回收（计划）",
          subGroup: yearStr,
        },
        {
          label: "股权分红",
          prop: "a42",
          headerGroup: "投资回收（计划）",
          subGroup: yearStr,
        },
        {
          label: "其他",
          prop: "a43",
          headerGroup: "投资回收（计划）",
          subGroup: yearStr,
        },
        {
          label: "目标（决策）与计划差异说明",
          isTextRow: true,
          prop: "a44",
          headerGroup: "投资回收（计划）",
          subGroup: yearStr,
        },

        // 第三组：投资回收（计划） -> 一季度
        {
          label: "合计",
          prop: "a23",
          headerGroup: "投资回收（计划）",
          subGroup: q1Str,
        },
        {
          label: "政府付费",
          prop: "a24",
          headerGroup: "投资回收（计划）",
          subGroup: q1Str,
        },
        {
          label: "政府补助",
          prop: "a25",
          headerGroup: "投资回收（计划）",
          subGroup: q1Str,
        },
        {
          label: "使用者付费",
          prop: "a26",
          headerGroup: "投资回收（计划）",
          subGroup: q1Str,
        },
        {
          label: "使用者欠付",
          prop: "a27",
          headerGroup: "投资回收（计划）",
          subGroup: q1Str,
        },
        {
          label: "补贴收入",
          prop: "a28",
          headerGroup: "投资回收（计划）",
          subGroup: q1Str,
        },
        {
          label: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
          prop: "a29",
          headerGroup: "投资回收（计划）",
          subGroup: q1Str,
        },
        {
          label: "资产盘活",
          prop: "a30",
          headerGroup: "投资回收（计划）",
          subGroup: q1Str,
        },
        {
          label: "股权分红",
          prop: "a31",
          headerGroup: "投资回收（计划）",
          subGroup: q1Str,
        },
        {
          label: "其他",
          prop: "a32",
          headerGroup: "投资回收（计划）",
          subGroup: q1Str,
        },
        {
          label: "目标（决策）与计划差异说明",
          isTextRow: true,
          prop: "a33",
          headerGroup: "投资回收（计划）",
          subGroup: q1Str,
        },
        // 第四组：投资回收（计划） -> 动态年度

        // 第五组：投资回收（计划） -> 二季度
        {
          label: "合计",
          prop: "a45",
          headerGroup: "投资回收（计划）",
          subGroup: q2Str,
        },
        {
          label: "政府付费",
          prop: "a46",
          headerGroup: "投资回收（计划）",
          subGroup: q2Str,
        },
        {
          label: "政府补助",
          prop: "a47",
          headerGroup: "投资回收（计划）",
          subGroup: q2Str,
        },
        {
          label: "使用者付费",
          prop: "a48",
          headerGroup: "投资回收（计划）",
          subGroup: q2Str,
        },
        {
          label: "使用者欠付",
          prop: "a49",
          headerGroup: "投资回收（计划）",
          subGroup: q2Str,
        },
        {
          label: "补贴收入",
          prop: "a50",
          headerGroup: "投资回收（计划）",
          subGroup: q2Str,
        },
        {
          label: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
          prop: "a51",
          headerGroup: "投资回收（计划）",
          subGroup: q2Str,
        },
        {
          label: "资产盘活",
          prop: "a52",
          headerGroup: "投资回收（计划）",
          subGroup: q2Str,
        },
        {
          label: "股权分红",
          prop: "a53",
          headerGroup: "投资回收（计划）",
          subGroup: q2Str,
        },
        {
          label: "其他",
          prop: "a54",
          headerGroup: "投资回收（计划）",
          subGroup: q2Str,
        },
        {
          label: "目标（决策）与计划差异说明",
          isTextRow: true,
          prop: "a55",
          headerGroup: "投资回收（计划）",
          subGroup: q2Str,
        },
        // 第六组：投资回收（计划） -> 三季度
        {
          label: "合计",
          prop: "a56",
          headerGroup: "投资回收（计划）",
          subGroup: q3Str,
        },
        {
          label: "政府付费",
          prop: "a57",
          headerGroup: "投资回收（计划）",
          subGroup: q3Str,
        },
        {
          label: "政府补助",
          prop: "a58",
          headerGroup: "投资回收（计划）",
          subGroup: q3Str,
        },
        {
          label: "使用者付费",
          prop: "a59",
          headerGroup: "投资回收（计划）",
          subGroup: q3Str,
        },
        {
          label: "使用者欠付",
          prop: "a60",
          headerGroup: "投资回收（计划）",
          subGroup: q3Str,
        },
        {
          label: "补贴收入",
          prop: "a61",
          headerGroup: "投资回收（计划）",
          subGroup: q3Str,
        },
        {
          label: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
          prop: "a62",
          headerGroup: "投资回收（计划）",
          subGroup: q3Str,
        },
        {
          label: "资产盘活",
          prop: "a63",
          headerGroup: "投资回收（计划）",
          subGroup: q3Str,
        },
        {
          label: "股权分红",
          prop: "a64",
          headerGroup: "投资回收（计划）",
          subGroup: q3Str,
        },
        {
          label: "其他",
          prop: "a65",
          headerGroup: "投资回收（计划）",
          subGroup: q3Str,
        },
        {
          label: "目标（决策）与计划差异说明",
          isTextRow: true,
          prop: "a66",
          headerGroup: "投资回收（计划）",
          subGroup: q3Str,
        },
        // 第七组：投资回收（计划） -> 四季度
        {
          label: "合计",
          prop: "a67",
          headerGroup: "投资回收（计划）",
          subGroup: q4Str,
        },
        {
          label: "政府付费",
          prop: "a68",
          headerGroup: "投资回收（计划）",
          subGroup: q4Str,
        },
        {
          label: "政府补助",
          prop: "a69",
          headerGroup: "投资回收（计划）",
          subGroup: q4Str,
        },
        {
          label: "使用者付费",
          prop: "a70",
          headerGroup: "投资回收（计划）",
          subGroup: q4Str,
        },
        {
          label: "使用者欠付",
          prop: "a71",
          headerGroup: "投资回收（计划）",
          subGroup: q4Str,
        },
        {
          label: "补贴收入",
          prop: "a72",
          headerGroup: "投资回收（计划）",
          subGroup: q4Str,
        },
        {
          label: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
          prop: "a73",
          headerGroup: "投资回收（计划）",
          subGroup: q4Str,
        },
        {
          label: "资产盘活",
          prop: "a74",
          headerGroup: "投资回收（计划）",
          subGroup: q4Str,
        },
        {
          label: "股权分红",
          prop: "a75",
          headerGroup: "投资回收（计划）",
          subGroup: q4Str,
        },
        {
          label: "其他",
          prop: "a76",
          headerGroup: "投资回收（计划）",
          subGroup: q4Str,
        },
        {
          label: "目标（决策）与计划差异说明",
          isTextRow: true,
          prop: "a77",
          headerGroup: "投资回收（计划）",
          subGroup: q4Str,
        },
      ];
    },
    // 表格数据（子组件会自动初始化，父组件可传初始值）
    tableData: [],
  };

  formData.tzhswcqkndgx = {
    tableData: [],
  };

  formData.tzhswcqkydgx = {
    tableData: [],
  };

  formData.tzhsjc = {
    tableData: [],
  };
};
const formData = reactive({
  nd: new Date().getFullYear().toString(), // 年度，默认当前年份
  jzymljys: {},
  jzymljsh: {},
  tzhsjc: {},
  tzhsjh: {},
  tzhswcqkndgx: {},
  tzhswcqkydgx: {},
  tzhsjc: {}, // 投资回收完成情况年度计划
  lastyeartzhs: null, // 去年投资回收计划数据
  projectGdxxs: [],
});

// 计算属性：动态生成年份相关的标题
const currentYear = computed(
  () => formData.nd || new Date().getFullYear().toString(),
);
const lastYear = computed(() => {
  const year = parseInt(currentYear.value);
  return (year - 1).toString();
});

// 动态标题
const dynamicTitles = computed(() => ({
  // 投资回收累计完成情况-年度更新
  yearlyUpdateTitle: `${currentYear.value}年投资回收计划`,
  // 投资回收完成情况-年度更新
  yearlyCompletionTitle: `${currentYear.value - 1}年投资回收累计完成情况（年度更新）`,
  // 投资回收完成情况-月度更新
  monthlyCompletionTitle: `${currentYear.value}年投资回收完成情况（月度更新）`,
}));

// 折叠面板默认展开项（动态计算）
const getActiveCollapseItems = () => [
  "项目基本信息",
  "出资情况",
  "合同约定权益获取",
  "分红情况",
  "投资额完成情况",
  "投资回收（决策）",
  "投资回收（计划）",
  dynamicTitles.value.yearlyUpdateTitle,
  "净现金流",
  "截止12月末累计实收",
  "资金流出",
  "分红情况",
  dynamicTitles.value.yearlyCompletionTitle,
  dynamicTitles.value.monthlyCompletionTitle,
];

const activeCollapse = ref(getActiveCollapseItems());

// 监听年度变化，更新 activeCollapse
watch(
  () => formData.nd,
  () => {
    activeCollapse.value = getActiveCollapseItems();
  },
  { immediate: false },
);

let options = ref();

// ========== 选择项目同步名称（通用） ==========
const changeProject = (val) => {
  proxy.$post({
    url: "/api/project/getProjectFinalInfo",
    data: { id: val },
    callback: (data) => {
      loading.value = false;
      formData.projectName = data.projectName || "";
      formData.sbdw = data.sbdw || "";
      formData.xmgsmc = data.xmgsmc || "";
      formData.xmkgsjyj = data.xmkgsjyj || "";
      formData.xmjgsjyj = data.xmjgsjyj || "";
      formData.xmjd = data.xmjd || "";
      formData.yynxn = data.yynxn || "";
      formData.xmjsqy = data.xmjsqy || "";
    },
    error: () => {
      loading.value = false;
      ElMessage.error("获取项目详情失败");
    },
  });
  const selectItem = projectList.value.find((item) => item.id === val);
  if (selectItem) formData.projectName = selectItem.projectName;
};
// 加载状态
const loading = ref(false);
const { projectDisabled, cachedInfo } = useProjectDetail();
// 是否预览模式
const isPreview = ref(!!route.query.isPreview);
// 项目列表数据
const projectList = ref([]);
// 当前编辑的记录ID
const rcCgqyglId = ref(route.query.id || "");

// 获取项目列表
const getProjectData = (params = {}) => {
  proxy.$post({
    url: "/api/project/listProject",
    data: {
      page: 1,
      pagesize: 1000,
      attributes: [],

      menuType: "xmjc",
      ...params,
    },
    callback: (data) => {
      projectList.value = data.rows || [];
    },
  });
};

// 获取单条记录详情（编辑/预览）
const getRcCgqyglDetail = () => {
  if (!rcCgqyglId.value) return;

  loading.value = true;
  proxy.$post({
    url: "/api/project/getYyqtzhsInfo",
    data: { id: rcCgqyglId.value },
    callback: (data) => {
      loading.value = false;
      console.log(data.jzymljys, "jzymljys详情数据");
      console.log(data.jzymljsh, "jzymljsh详情数据");
      console.log(data.lastyeartzhs, "lastyeartzhs");

      // 合并其他非表格字段
      Object.assign(formData, data);
    },
  });
};

const backClick = () => {
  router.back(-1);
};

// 保存/提交表单
const saveClick = () => {
  // 基础校验
  if (!formData.projectId) {
    ElMessage.warning("请选择项目信息");
    return;
  }

  loading.value = true;
  // 区分新增/编辑
  const url = rcCgqyglId.value
    ? "/api/project/updateYyqtzhs"
    : "/api/project/createYyqtzhs";

  // 处理空数字字段：空值转为null，避免提交空字符串
  const submitData = {
    ...formData,
    projectId: formData.projectId + "",
    id: route.query.id || null,
  };

  proxy.$post({
    url: url,
    data: submitData,
    callback: (res) => {
      loading.value = false;
      ElMessage.success(rcCgqyglId.value ? "编辑成功" : "新增成功");
      router.back(-1);
    },
  });
};

// 页面初始化
onMounted(() => {
  // 获取项目列表
  getProjectData();
  if (cachedInfo) {
    formData.projectName = cachedInfo.projectName || "";
    formData.projectId = cachedInfo.projectId || "";
  }
  options.value = JSON.parse(sessionStorage.getItem("resourceData"));
  // 如果有ID则加载详情
  if (rcCgqyglId.value) {
    getRcCgqyglDetail();
  } else {
    initTableData();
    // 新增模式：从 store 读取缓存的项目信息
  }
});
</script>

<style scoped lang="less">
// 布局容器
.project-tab-content-wrapper {
  display: flex;
  gap: 20px;
  position: relative;
}

.tab-content {
  flex: 1;
  min-width: 0; // 防止flex子项溢出
}

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

.DynamicTable-slot {
  display: flex;
  div {
    text-align: center;
    line-height: 38px;
  }
  div:nth-child(1) {
    border: 1px solid #bbc0ca;
    flex: 2;
  }
  div:nth-child(2) {
    border: 1px solid #bbc0ca;
    flex: 4;
  }
  height: 40px;
  background-color: #f5f7fa;
}
.subtotal {
  background-color: #f5f7fa;
  height: 40px;
  display: flex;
  .label {
    width: 100px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    border-right: 1px solid #ebeef5;
  }
  .value {
    padding-left: 16px;
    width: 100%;
    line-height: 40px;
  }
}
</style>
