<template>
  <div class="add-project-container">
    <div class="add-project-content" v-loading="loading">
      <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 class="tabs-content">
        <div class="project-tab-content">
          <div class="tab-content">
            <el-form :model="formData" :label-width="200" :disabled="isPreview">
              <el-collapse v-model="activeCollapse">
                <!-- 基本信息：字段完全对齐数据库 -->
                <el-collapse-item title="基本信息" name="基本信息">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="项目信息" required>
                        <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-date-picker
                          v-model="formData.xmkgsjyj"
                          type="date"
                          placeholder="请选择项目预计起始时间"
                          value-format="YYYY-MM-DD"
                        />
                      </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-date-picker
                          v-model="formData.xmjgsjyj"
                          type="date"
                          placeholder="请选择项目预计完成时间"
                          value-format="YYYY-MM-DD"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="填报人">
                        <el-input
                          v-model="formData.tbr"
                          placeholder="请输入填报人"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="填报人联系电话">
                        <el-input
                          v-model="formData.tbrlxdh"
                          placeholder="请输入填报人联系电话"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目建设期 (月)">
                        <el-input-number
                          v-model="formData.xmjsqy"
                          :min="0"
                          placeholder="请输入项目建设期 (月)"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目流转状态（审批状态）">
                        <el-select
                          v-model="formData.projectLzType"
                          placeholder="请选择项目流转状态"
                        >
                          <el-option label="待立项" value="1" />
                          <el-option label="立项审批中" value="3" />
                          <el-option label="已立项" value="5" />
                          <el-option label="决策填报中" value="7" />
                          <el-option label="决策审批中" value="8" />
                          <el-option label="已决策" value="9" />
                          <el-option label="再决策填报中" value="11" />
                          <el-option label="再决策审批中" value="12" />
                          <el-option label="再决策审批通过" value="13" />
                          <el-option label="再决策审批不通过" value="15" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目阶段">
                        <el-select
                          v-model="formData.xmjd"
                          placeholder="请选择项目阶段"
                        >
                          <el-option label="筹备期" value="筹备期" />
                          <el-option label="建设期" value="建设期" />
                          <el-option label="运营期" value="运营期" />
                          <el-option label="收尾期" value="收尾期" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="运营年限（年）">
                        <el-input-number
                          v-model="formData.yynxn"
                          :min="0"
                          placeholder="请输入运营年限（年）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="建成后成效">
                        <el-input
                          v-model="formData.jchcx"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入建成后成效"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="计划年份">
                        <el-input
                          v-model="formData.jhnf"
                          placeholder="请输入计划年份（如2026）"
                          maxlength="4"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="新建/续建">
                        <el-select v-model="formData.xjXj" placeholder="请选择">
                          <el-option label="新建" value="新建" />
                          <el-option label="续建" value="续建" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="年度投资目标">
                        <el-input
                          v-model="formData.ndTzMb"
                          placeholder="请输入年度投资目标"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目预计工期">
                        <el-input
                          v-model="formData.xmYjGq"
                          placeholder="请输入项目预计工期"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <!-- 战略类A：按数据库字段补充所有表单项 -->
                <el-collapse-item title="战略类A" name="战略类A">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="是否国家中长期规划重大项目(A1)">
                        <el-radio-group v-model="formData.sfgjzcqghzdxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="是否国家有关部门下达的重点项目(A2)">
                        <el-radio-group v-model="formData.sfgjygbmxddzdxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="大规模设备更新(A3)">
                        <el-radio-group v-model="formData.dgmsbgx">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="战略性新兴产业百大工程(A4)">
                        <el-radio-group v-model="formData.zlxxxcybdgc">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="列入央企产业焕新和未来产业启航行动的项目(A5)"
                      >
                        <el-radio-group v-model="formData.lryqcyhxhwlcyqhxddxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="强链补链重点项目(A6)">
                        <el-radio-group v-model="formData.qlblzdxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="对应重大或重点项目名录名称">
                        <el-input
                          v-model="formData.dyzdhzdxmmlmc"
                          placeholder="请输入对应重大或重点项目名录名称"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="战略性新兴产业分类（如有，必填）">
                        <el-input
                          v-model="formData.zlxxxcyfl"
                          placeholder="请输入战略性新兴产业分类"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

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

                <!-- 关注类C：按数据库字段补充所有表单项 -->
                <el-collapse-item title="关注类（C类）" name="关注类（C类）">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="对外并购类投资项目(C1)">
                        <el-radio-group v-model="formData.dwbgltzxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="特别监管类项目(C2)">
                        <el-radio-group v-model="formData.tbjglxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="境外特别关注类项目(C3)">
                        <el-radio-group v-model="formData.jwtbgzlxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="对外参股类投资项目(C4)">
                        <el-radio-group v-model="formData.dwcglxtzxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="房地产投资项目(C5)">
                        <el-radio-group v-model="formData.fdctzxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="PPP投资项目(C6)">
                        <el-radio-group v-model="formData.ppptzxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="两高项目(C7)">
                        <el-radio-group v-model="formData.lgxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <!-- 管控类D：按数据库字段补充所有表单项 -->
                <el-collapse-item title="管控类（D类）" name="管控类（D类）">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="非主业投资项目(D1)">
                        <el-radio-group v-model="formData.fzytzxm">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="持牌金融机构(D2)">
                        <el-radio-group v-model="formData.zpjrjg">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="类金融机构(D3)">
                        <el-radio-group v-model="formData.ljrjg">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="其他金融机构(D4)">
                        <el-radio-group v-model="formData.qtjrjg">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="基金及基金管理公司(D5)">
                        <el-radio-group v-model="formData.jjjjjglgs">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="创业投资基金(D6)">
                        <el-radio-group v-model="formData.cytzjj">
                          <el-radio label="0">否</el-radio>
                          <el-radio label="1">是</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <!-- 最终分类情况：补充长文本输入框 -->
                <el-collapse-item title="最终分类情况" name="最终分类情况">
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <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>

                <!-- 可研/决策信息（单位：万元）：保留原有功能，提交字段改为kyjcxx -->
                <el-collapse-item
                  title="可研/决策信息（单位：万元）"
                  name="可研/决策信息（单位：万元）"
                >
                  <el-table
                    :data="financialIndicators"
                    style="width: 100%"
                    border
                    :cell-style="tableCellStyle"
                  >
                    <!-- 序号列 -->
                    <el-table-column
                      prop="serialNumber"
                      label="序号"
                      width="80"
                      align="center"
                    />
                    <!-- 指标项列（层级缩进） -->
                    <el-table-column
                      prop="indicatorName"
                      label="指标项"
                      min-width="280"
                    >
                      <template #default="{ row }">
                        <span :style="{ textIndent: `${row.level * 20}px` }">
                          {{ row.indicatorName }}
                        </span>
                      </template>
                    </el-table-column>
                    <!-- 合计列（自动统计） -->
                    <el-table-column label="合计" width="120" align="center">
                      <template #default="{ row }">
                        <span
                          >{{
                            row.total ? row.total.toFixed(2) : "0.00"
                          }}万元</span
                        >
                      </template>
                    </el-table-column>
                    <!-- 动态时间表头：当前时间+后续15期（年/年月） -->
                    <el-table-column
                      v-for="time in dynamicTimeList"
                      :key="time"
                      :label="time"
                      width="140"
                      align="center"
                    >
                      <template #default="{ row }">
                        <el-input-number
                          v-model="row[time]"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          @change="handleDataChange(row)"
                          :disabled="isPreview"
                          style="width: 100%"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                </el-collapse-item>

                <!-- 新增：项目年度计划表格（单位：万元） -->
                <el-collapse-item
                  title="项目年度计划表格（单位：万元）"
                  name="项目年度计划表格（单位：万元）"
                >
                </el-collapse-item>
              </el-collapse>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, getCurrentInstance } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
// 初始化全局变量
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

// ========== 基础配置 ==========
const activeCollapse = ref([
  "基本信息",
  "可研/决策信息（单位：万元）",
  "项目年度计划表格（单位：万元）",
  "战略类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([]); // 动态时间列表（表头）
const financialIndicators = ref([]); // 财务表格渲染数据
const annualPlanIndicators = 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: true,
    parentCode: ["1.1", "1.2", "1.3"],
  },
  { 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,
  },
]);

// ========== 年度计划表格原始配置（完全还原截图结构） ==========
const annualPlanOriginConfig = ref([
  { level: 0, indicatorName: "年度投资计划", isTotal: false },
  { level: 1, indicatorName: "计划投资完成及资金来源", isTotal: false },
  { level: 2, indicatorName: "计划资金来源（全口径）", isTotal: false },
  {
    level: 3,
    indicatorName: "合计",
    isTotal: true,
    parentCode: ["资本金", "债权融资", "回款再投入", "其他"],
  },
  { level: 3, indicatorName: "资本金", isTotal: false },
  {
    level: 4,
    indicatorName: "小计",
    isTotal: true,
    parentCode: ["能建方", "外部股东"],
  },
  { level: 4, indicatorName: "能建方", isTotal: false },
  { level: 4, indicatorName: "外部股东", isTotal: false },
  { level: 3, indicatorName: "债权融资", isTotal: false },
  {
    level: 4,
    indicatorName: "小计",
    isTotal: true,
    parentCode: ["其中:非并表项目我方贷款/担保额"],
  },
  { level: 4, indicatorName: "其中:非并表项目我方贷款/担保额", isTotal: false },
  { level: 3, indicatorName: "回款再投入", isTotal: false },
  { level: 3, indicatorName: "其他", isTotal: false },
  {
    level: 4,
    indicatorName: "小计",
    isTotal: true,
    parentCode: ["其中:我方其他出资"],
  },
  { level: 4, indicatorName: "其中:我方其他出资", isTotal: false },
  { level: 2, indicatorName: "资金来源（新口径）", isTotal: false },
  {
    level: 3,
    indicatorName: "合计",
    isTotal: true,
    parentCode: ["资本金", "债权融资", "回款再投入", "其他"],
  },
  { level: 3, indicatorName: "资本金", isTotal: false },
  {
    level: 4,
    indicatorName: "小计",
    isTotal: true,
    parentCode: ["能建方", "外部股东"],
  },
  { level: 4, indicatorName: "能建方", isTotal: false },
  { level: 4, indicatorName: "外部股东", isTotal: false },
  { level: 3, indicatorName: "债权融资", isTotal: false },
  { level: 3, indicatorName: "回款再投入", isTotal: false },
  { level: 3, indicatorName: "其他", isTotal: false },
  {
    level: 1,
    indicatorName: "合计",
    isTotal: true,
    parentCode: ["计划投资完成及资金来源"],
  },
  { level: 1, indicatorName: "政府付费", isTotal: false },
]);

// ========== 表单数据：完全对齐数据库字段，无冗余！ ==========
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: [],
  // 年度计划信息（JSON，与新增表格绑定）
  xmndjh: [],

  // 其他扩展字段
  jhnf: "",
  xjXj: "",
  ndTzMb: "",
  xmYjGq: "",
  xmRzLdSjHyyjLdSj: "",
  yjSxZbjNbsyl: 0.0,
  xmTzZeXmJhZtzLx: "",
  jhLx: "",
  dqJzJd: "",
  dqJzQk: "",
  xmRzSfYjLd: "",
  xmSjKgSj: "",
  yqSxXg: "",
  nTzJqMbjyYjhCySm: "",
  nJhTzMbjyYjhCySm: "",
  xmZyFxJzyFxYdcj: "",

  // 金额类JSON字段
  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 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(); // 生成表头后初始化财务表格
  initAnnualPlanTable(); // 生成表头后初始化年度计划表格
};

// ========== 初始化财务表格数据 ==========
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;
};

// ========== 初始化年度计划表格数据 ==========
const initAnnualPlanTable = () => {
  if (dynamicTimeList.value.length === 0) return;
  const tableData = annualPlanOriginConfig.value.map((item) => {
    const row = { ...item, total: 0 };
    dynamicTimeList.value.forEach((time) => (row[time] = 0));
    return row;
  });
  annualPlanIndicators.value = tableData;
};

// ========== 财务表格数据变更：更新行合计+父项合计 ==========
const handleDataChange = (currentRow) => {
  updateRowTotal(currentRow);
  updateAllTotalRow();
};

// ========== 年度计划表格数据变更：更新行合计+父项合计 ==========
const handleAnnualPlanChange = (currentRow) => {
  updateRowTotal(currentRow);
  updateAnnualPlanTotalRow();
};

// ========== 更新单行合计 ==========
const updateRowTotal = (row) => {
  row.total = dynamicTimeList.value.reduce((sum, time) => {
    return sum + (Number(row[time]) || 0);
  }, 0);
};

// ========== 更新财务表格所有父项合计行 ==========
const updateAllTotalRow = () => {
  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 updateAnnualPlanTotalRow = () => {
  annualPlanIndicators.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 = annualPlanIndicators.value.find(
        (item) => item.indicatorName === code,
      );
      if (childRow) {
        totalRow.total += Number(childRow.total) || 0;
        dynamicTimeList.value.forEach((time) => {
          totalRow[time] += Number(childRow[time]) || 0;
        });
      }
    });
  });
};

// ========== 批量初始化所有行合计 ==========
const initAllRowTotal = () => {
  financialIndicators.value.forEach(
    (row) => !row.isTotal && updateRowTotal(row),
  );
  updateAllTotalRow();

  annualPlanIndicators.value.forEach(
    (row) => !row.isTotal && updateRowTotal(row),
  );
  updateAnnualPlanTotalRow();
};

// ========== 回填财务表格数据（按序号+指标名双匹配，避免错位） ==========
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;
    });
  });
  initAllRowTotal();
};

// ========== 回填年度计划表格数据（按指标名匹配，避免错位） ==========
const fillAnnualPlanTable = (backfillData) => {
  if (!Array.isArray(backfillData) || backfillData.length === 0) return;
  annualPlanIndicators.value.forEach((frontRow) => {
    const backfillRow = backfillData.find(
      (item) => item.indicatorName === frontRow.indicatorName,
    );
    if (!backfillRow) return;
    frontRow.total = Number(backfillRow.total) || 0;
    dynamicTimeList.value.forEach((time) => {
      frontRow[time] = Number(backfillRow[time]) || 0;
    });
  });
  initAllRowTotal();
};

// ========== 业务方法：获取项目列表 ==========
const getProjectData = () => {
  proxy.$post({
    url: "/api/project/listProject",
    data: { page: 1, pagesize: 1000, attributes: [], menuType: "xmjc" },
    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;
      if (!data) return ElMessage.error("未查询到数据");

      console.log(data, "data");
    },
    error: () => {
      loading.value = false;
      ElMessage.error("获取数据失败");
    },
  });
  const selectItem = projectList.value.find((item) => item.id === val);
  if (selectItem) formData.projectName = selectItem.projectName;
};

// ========== 核心修复：获取详情（编辑/预览），解决timeList未定义BUG ==========
const getJsqtzjcDetail = () => {
  if (!rcCgqyglId.value) return;
  loading.value = true;
  proxy.$post({
    url: "/api/project/getJsqtzjcInfo",
    data: { id: rcCgqyglId.value },
    callback: (data) => {
      loading.value = false;
      if (!data) return ElMessage.error("未查询到数据");
      Object.assign(formData, data); // 回填所有表单数据

      // 核心修复：从后端kyjcxx提取时间列表，无则生成默认时间
      if (data.kyjcxx && Array.isArray(data.kyjcxx) && data.kyjcxx.length > 0) {
        // 提取后端已有的时间字段（过滤非时间字段）
        const firstRow = data.kyjcxx[0];
        dynamicTimeList.value = Object.keys(firstRow).filter((key) =>
          /^\d{4}(-\d{2})?$/.test(key),
        );
      } else {
        generateDynamicTime(); // 无数据则生成默认时间
      }

      // 初始化表格后再回填数据
      if (dynamicTimeList.value.length === 0) generateDynamicTime();
      else {
        initFinancialTable();
        initAnnualPlanTable();
      }

      // 回填财务数据
      if (data.kyjcxx) fillFinancialTable(data.kyjcxx);
      // 回填年度计划数据
      if (data.xmndjh) fillAnnualPlanTable(data.xmndjh);
    },
    error: () => {
      loading.value = false;
      ElMessage.error("获取数据失败");
    },
  });
};

// ========== 核心修改：保存表单，提交字段改为kyjcxx和xmndjh ==========
const saveClick = () => {
  if (!formData.projectId) return ElMessage.warning("请选择项目信息");
  loading.value = true;
  const url = rcCgqyglId.value
    ? "/api/project/updateJsqtzjc"
    : "/api/project/createJsqtzjc";

  // 组装提交数据：财务数据赋值给kyjcxx，年度计划数据赋值给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: annualPlanIndicators.value.map((row) => {
      const filterRow = {
        indicatorName: row.indicatorName,
        level: row.level,
        total: row.total,
      };
      dynamicTimeList.value.forEach((time) => (filterRow[time] = row[time]));
      return filterRow;
    }),
  };

  proxy.$post({
    url: url,
    data: submitData,
    callback: () => {
      loading.value = false;
      ElMessage.success(rcCgqyglId.value ? "编辑成功" : "新增成功");
      router.back(-1);
    },
    error: (err) => {
      loading.value = false;
      ElMessage.error(err.msg || "保存失败");
    },
  });
};

// ========== 辅助方法 ==========
const backClick = () => router.back(-1);
const tableCellStyle = ({ row }) =>
  row.isTotal ? { background: "#f5f7fa", fontWeight: "bold" } : {};

// ========== 页面初始化 ==========
onMounted(() => {
  getProjectData();
  if (rcCgqyglId.value) {
    setTimeout(() => getJsqtzjcDetail(), 100);
  } else {
    generateDynamicTime(); // 新增模式直接生成时间
  }
});
</script>

<style scoped lang="less">
@import "@/styles/verticalManages.less";

.add-project-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.add-project-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.tab-content {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

// 表格样式优化
:deep(.el-table-cell) {
  padding-left: 8px !important;
  box-sizing: border-box;
}
:deep(.el-input-number__input) {
  text-align: right;
  padding-right: 25px;
}
:deep(.el-collapse-item__header) {
  font-weight: bold;
}
:deep(.el-table) {
  --el-table-border-color: #ebeef5;
}
// 文本域宽度适配
:deep(.el-textarea__inner) {
  width: 100% !important;
}
</style>
