<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
                          v-model="formData.xmjsqy"
                          :min="0"
                          placeholder="请输入项目建设期 (月)"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目流转状态（审批状态）">
                        <CommonSelector
                          v-model="formData.projectLzType"
                          dictName="xmlzzt"
                        ></CommonSelector>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目阶段">
                        <CommonSelector
                          v-model="formData.xmjd"
                          dictName="project_phase"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="运营年限（年）">
                        <el-input
                          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-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)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.sfgjzcqghzdxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="是否国家有关部门下达的重点项目(A2)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.sfgjygbmxddzdxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="大规模设备更新(A3)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.dgmsbgx"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="战略性新兴产业百大工程(A4)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.zlxxxcybdgc"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="列入央企产业焕新和未来产业启航行动的项目(A5)"
                      >
                        <CommonSelector
                          :radio="true"
                          v-model="formData.lryqcyhxhwlcyqhxddxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="强链补链重点项目(A6)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.qlblzdxm"
                          dictName="sf"
                        />
                      </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)"
                      >
                        <CommonSelector
                          :radio="true"
                          v-model="formData.lrqyfzzlxxxcygzfadxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="粮食、能源、矿产资源保障项目(B2)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.lsnykczybzxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="传统产业高端化、智能化、绿色化转型升级项目(B3)"
                      >
                        <CommonSelector
                          :radio="true"
                          v-model="formData.ctcygdh"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="支撑企业发展的重点项目(B4)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.zcqyfzdddxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="制造业技术改造项目">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.zzyjsgzxm"
                          dictName="sf"
                        />
                      </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)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.dwbgltzxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="特别监管类项目(C2)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.tbjglxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="境外特别关注类项目(C3)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.jwtbgzlxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="对外参股类投资项目(C4)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.dwcglxtzxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="房地产投资项目(C5)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.fdctzxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="PPP投资项目(C6)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.ppptzxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="两高项目(C7)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.lgxm"
                          dictName="sf"
                        />
                      </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)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.fzytzxm"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="持牌金融机构(D2)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.zpjrjg"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="类金融机构(D3)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.ljrjg"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="其他金融机构(D4)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.qtjrjg"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="基金及基金管理公司(D5)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.jjjjjglgs"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="创业投资基金(D6)">
                        <CommonSelector
                          :radio="true"
                          v-model="formData.cytzjj"
                          dictName="sf"
                        />
                      </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>

                <!-- 可研/决策信息（单位：万元）：独立表格，专属方法/数据源 -->
                <el-collapse-item
                  title="可研/决策信息（单位：万元）"
                  name="可研/决策信息（单位：万元）"
                >
                  <el-table
                    :data="financialIndicators"
                    style="width: 100%"
                    border
                    :cell-style="tableCellStyle"
                    row-key="serialNumber"
                  >
                    <!-- 序号列 -->
                    <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
                          v-model="row[time]"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          @change="handleFinancialChange(row)"
                          :disabled="isPreview"
                          style="width: 100%"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                </el-collapse-item>

                <!-- 年度投资计划：基础信息 -->
                <el-collapse-item title="年度投资计划" name="年度投资计划">
                  <el-row :gutter="20">
                    <!-- 基础短字段：span12分栏 -->
                    <el-col :span="12">
                      <el-form-item label="计划年份">
                        <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="12">
                      <el-form-item label="新建/续建">
                        <CommonSelector v-model="formData.xjXj" dictName="xj" />
                      </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="请输入项目预计工期（如12个月）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <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="12">
                      <el-form-item label="预计实现资本金内部收益率(%)">
                        <el-input
                          v-model="formData.yjSxZbjNbsyl"
                          :min="0"
                          :precision="2"
                          :max="999.99"
                          controls-position="right"
                          placeholder="请输入收益率"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目计划总投资类型">
                        <el-input
                          v-model="formData.xmTzZeXmJhZtzLx"
                          placeholder="请输入项目计划总投资类型"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="计划类型">
                        <el-input
                          v-model="formData.jhLx"
                          placeholder="请输入计划类型"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="当前进展阶段">
                        <el-input
                          v-model="formData.dqJzJd"
                          placeholder="请输入当前进展阶段"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目融资是否已经落地">
                        <CommonSelector
                          v-model="formData.xmRzSfYjLd"
                          dictName="sf"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="当前进展情况">
                        <el-input
                          v-model="formData.dqJzQk"
                          placeholder="请输入当前进展情况"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <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="24">
                      <el-form-item label="预期实现效果">
                        <el-input
                          v-model="formData.yqSxXg"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入预期实现效果详细说明"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item
                        label="2025年投资金额(全口径)目标(决算)与计划差异说明"
                      >
                        <el-input
                          v-model="formData.nTzJqMbjyYjhCySm"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入差异说明"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item
                        label="2025年计划投资目标(决算)与计划差异说明"
                      >
                        <el-input
                          v-model="formData.nJhTzMbjyYjhCySm"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入差异说明"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item 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="20">
                    <el-col :span="12">
                      <el-form-item label="资金支付比例(%)">
                        <el-input
                          v-model="formData.zjfzBl"
                          :min="0"
                          :max="100"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="债权融资(万元)">
                        <el-input
                          v-model="formData.zqRz"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="年度计划总额(万元)">
                        <el-input
                          v-model="formData.ndJhZe"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="回款再投入(万元)">
                        <el-input
                          v-model="formData.hkZtr"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="资本金-配套方(万元)">
                        <el-input
                          v-model="formData.zbjPtF"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="其他(万元)">
                        <el-input
                          v-model="formData.qt"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="资本金-外部股东(万元)">
                        <el-input
                          v-model="formData.zbjWbGd"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="我方仅指本单位出资(万元)">
                        <el-input
                          v-model="formData.wfJzBdwCz"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>
                <!-- 2026年参股单位出资情况修正 -->
                <el-collapse-item
                  title="2026年参股单位出资情况修正(单位:万元)"
                  name="2026年参股单位出资情况修正(单位:万元)"
                >
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="参股单位出资情况修正">
                        <DynamicTable
                          :columns="transferColumns"
                          :disabled="isPreview"
                          v-model="formData.cgdwczqkxz"
                          :default-row="{
                            mc: '',
                            fj: '',
                            bz: '',
                          }"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>
              </el-collapse>
            </el-form>
          </div>
        </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 DynamicTable from "@/components/FormDynamicTable/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 transferColumns = ref([
  {
    prop: "mc",
    label: "单位名称",
    type: "input",
    placeholder: "请填写单位名称",
  },
  {
    prop: "fj",
    label: "我方出资额（万元）",
    type: "input",
    placeholder: "请输入我方出资额（万元）",
    min: 0,
    precision: 2,
  },
  {
    prop: "bz",
    label: "差异说明",
    type: "textarea",
    rows: 2,
    placeholder: "请输入差异说明",
  },
]);

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

// ========== 基础配置：两个表格共用（仅时间列表，无其他关联） ==========
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: 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,
  },
]);

// ========== 表单数据：完全对齐数据库，两个表格的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: 17 }, (_, 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 = () => {
  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;
      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 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);

      // 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 = () => {
  if (!formData.projectId) 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,
  };

  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 {
    // 新增模式：先生成时间列表（系统年+1）→ 再初始化两个表格，互不影响
    getCurrentYearTimeList(); // 无参=系统年+1，贴合原有逻辑
    generateDynamicTime(); // 可研表格时间初始化
    initAnnualPlanTable(); // 年度计划表格本地初始化
  }
});
</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;
}
// 年度计划表格子组件容器
.annualPlans {
  width: 100%;
  overflow-x: auto;
}
// 修复数字输入框样式
:deep(.el-input-number) {
  width: 100%;
}
</style>
