<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">
          <div class="tab-content">
            <el-form :model="formData" label-width="150" :disabled="isPreview">
              <el-collapse v-model="activeCollapse">
                <!-- 移除原有的选择类型折叠面板 -->
                <el-collapse-item title="登记类型" name="登记类型">
                  <el-form-item label="登记类型">
                    <el-tag v-if="formData.djlx == 1">中止</el-tag>
                    <el-tag v-if="formData.djlx == 2">重启</el-tag>
                    <el-tag v-if="formData.djlx == 3">终止</el-tag>
                    <el-tag v-if="formData.djlx == 4">退出</el-tag>
                  </el-form-item>
                </el-collapse-item>

                <!-- 基本信息 -->
                <el-collapse-item title="基本信息" name="基本信息">
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <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="8">
                      <el-form-item label="项目编号">
                        <el-input
                          v-model="formData.projectCode"
                          placeholder="请输入项目编号"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="是否联合体">
                        <el-input
                          v-model="formData.sfybb"
                          placeholder="请输入是否联合体"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="8">
                      <el-form-item label="申报单位">
                        <el-input
                          v-model="formData.sbdw"
                          placeholder="请输入申报单位"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="所属二级企业">
                        <el-input
                          v-model="formData.ssejqy"
                          placeholder="请输入所属二级企业"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="8">
                      <el-form-item label="一级分类">
                        <el-input
                          v-model="formData.tzsxyjfl"
                          placeholder="请输入一级分类"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="二级分类">
                        <el-input
                          v-model="formData.tzsxejfl"
                          placeholder="请输入二级分类"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="投资板块">
                        <el-input
                          v-model="formData.tzbk"
                          placeholder="请输入投资板块"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="细分板块">
                        <el-input
                          v-model="formData.jnw"
                          placeholder="请输入境内/外"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="项目公司全称">
                        <el-input
                          v-model="formData.xmgsqc"
                          placeholder="请输入项目公司全称"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="项目批复时间">
                        <el-input
                          v-model="formData.cwbblx"
                          placeholder="请输入财务报表类型"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="报备时间">
                        <el-input
                          v-model="formData.tcrq"
                          placeholder="请输入退出日期"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="项目建设期 (月)">
                        <el-input
                          v-model="formData.xmjsqy"
                          :min="0"
                          placeholder="请输入项目建设期 (月)"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="运营年限（年）">
                        <el-input
                          v-model="formData.yynxn"
                          :min="0"
                          placeholder="请输入运营年限（年）"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="8">
                      <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="8">
                      <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="8">
                      <el-form-item label="退出申请日期">
                        <el-date-picker
                          v-model="formData.tcsqrq"
                          type="date"
                          placeholder="请选择退出申请日期"
                          value-format="YYYY-MM-DD"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="申请日期">
                        <el-date-picker
                          v-model="formData.yjwcsj"
                          type="date"
                          placeholder="请选择预计完成时间"
                          value-format="YYYY-MM-DD"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="8">
                      <el-form-item label="填报人">
                        <el-input
                          v-model="formData.tblxr"
                          placeholder="请输入填报人"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="填报人联系电话">
                        <el-input
                          v-model="formData.tblxrdh"
                          placeholder="请输入填报人联系电话"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="当前净资产">
                        <el-input
                          v-model="formData.dqjzc"
                          :min="0"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="24">
                      <el-form-item label="项目的主要建设内容">
                        <el-input
                          v-model="formData.jsnrjgm"
                          type="textarea"
                          rows="3"
                          placeholder="请输入项目的主要建设内容"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="24">
                      <el-form-item label="我方出资人及持股比例">
                        <el-input
                          v-model="formData.cgRatio"
                          type="textarea"
                          rows="3"
                          placeholder="请输入我方出资人及持股比例"
                        />
                      </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-width="0">
                        <DynamicTable
                          :showDeleteButton="false"
                          :showAddButton="false"
                          :columns="transferColumns"
                          :disabled="isPreview"
                          v-model="formData.xmtzxy"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <!-- 资金构成 -->
                <el-collapse-item title="资金构成" name="资金构成">
                  <el-table
                    :data="formData.zjgc"
                    border
                    style="width: 100%"
                    size="small"
                  >
                    <el-table-column
                      prop="index"
                      label="序号"
                      width="80"
                      align="center"
                    />
                    <el-table-column
                      prop="label"
                      label="指标"
                      min-width="300"
                    />
                    <el-table-column
                      prop="unit"
                      label="单位"
                      width="100"
                      align="center"
                    />
                    <el-table-column
                      prop="value"
                      label="人民币计价"
                      align="right"
                      min-width="200"
                    >
                      <template #default="{ row }">
                        <el-input
                          v-if="row.editable && !isPreview"
                          v-model="row.value"
                          :precision="2"
                          controls-position="right"
                          placeholder="0.00"
                          type="number"
                          style="width: 100%"
                          @change="handleZjgcChange(row)"
                        />
                        <span v-else>{{ row.value || "-" }}</span>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-collapse-item>

                <!-- 财务评价指标 -->
                <el-collapse-item title="财务评价指标" name="财务评价指标">
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-form-item
                        label-width="260px"
                        label="决策:项目投资内部收益率(税前):"
                      >
                        <el-input
                          v-model="formData.jcxmtznbsylsq"
                          :precision="2"
                          :disabled="isPreview"
                          placeholder="0.00"
                          type="number"
                          suffix="%"
                          @change="handleFinancialIndexChange('jcxmtznbsylsq')"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item
                        label-width="260px"
                        label="项目资本金内部收益率:"
                      >
                        <el-input
                          v-model="formData.xmzbjnbsyl"
                          :precision="2"
                          :disabled="isPreview"
                          placeholder="0.00"
                          type="number"
                          suffix="%"
                          @change="handleFinancialIndexChange('xmzbjnbsyl')"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item
                        label-width="260px"
                        label="项目投资回收期(税前):"
                      >
                        <el-input
                          v-model="formData.xmtzhsq"
                          :disabled="isPreview"
                          placeholder="0.00"
                          suffix="年"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item
                        label-width="260px"
                        label="实际:预测项目全投资内部收益率(税前):"
                      >
                        <el-input
                          v-model="formData.sjycxmqtznbsylsq"
                          :precision="2"
                          :disabled="isPreview"
                          placeholder="0.00"
                          type="number"
                          suffix="%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item
                        label-width="260px"
                        label="预测项目资本金内部收益率(税后):"
                      >
                        <el-input
                          v-model="formData.ycxmzbjnbsylsh"
                          :precision="2"
                          :disabled="isPreview"
                          placeholder="0.00"
                          type="number"
                          suffix="%"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <!-- 项目中止内容 -->
                <el-collapse-item
                  v-if="formData.djlx == 1"
                  title="项目中止内容"
                  name="项目中止内容"
                >
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="中止原因">
                        <el-input
                          v-model="formData.zzyy"
                          type="textarea"
                          rows="2"
                          placeholder="请输入中止原因"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="中止详细原因">
                        <el-input
                          v-model="formData.zzxxyy"
                          type="textarea"
                          rows="3"
                          placeholder="请输入中止详细原因"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="其他说明">
                        <el-input
                          v-model="formData.qtsm"
                          type="textarea"
                          rows="3"
                          placeholder="请输入其他说明"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="中止报告">
                        <FileUploader
                          v-model="formData.xmzzbg"
                          :disabled="isPreview"
                        ></FileUploader>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="其他相关支撑材料">
                        <FileUploader
                          v-model="formData.qtxgzccl"
                          :disabled="isPreview"
                        ></FileUploader>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="报批报备文件">
                        <FileUploader
                          v-model="formData.bpbbwjlj"
                          :disabled="isPreview"
                        ></FileUploader>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <!-- 项目重启内容 -->
                <el-collapse-item
                  v-if="formData.djlx == 2"
                  title="项目重启内容"
                  name="项目重启内容"
                >
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-form-item label="计划重启时间">
                        <el-date-picker
                          v-model="formData.jhcqsj"
                          type="date"
                          placeholder="请选择计划重启时间"
                          value-format="YYYY-MM-DD"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="重启原因">
                        <el-input
                          v-model="formData.cqyy"
                          type="textarea"
                          rows="2"
                          placeholder="请输入重启原因"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="其他说明">
                        <el-input
                          v-model="formData.qtsm"
                          type="textarea"
                          rows="3"
                          placeholder="请输入其他说明"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="重启报告">
                        <FileUploader
                          v-model="formData.xmcqbg"
                          :disabled="isPreview"
                        ></FileUploader>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="决策文件">
                        <FileUploader
                          v-model="formData.jcwj"
                          :disabled="isPreview"
                        ></FileUploader>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="报批报备文件">
                        <FileUploader
                          v-model="formData.bpbbwjlj"
                          :disabled="isPreview"
                        ></FileUploader>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <!-- 项目终止内容 -->
                <el-collapse-item
                  v-if="formData.djlx == 3"
                  title="项目终止内容"
                  name="项目终止内容"
                >
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="终止原因">
                        <el-input
                          v-model="formData.zhongzyy"
                          type="textarea"
                          rows="2"
                          placeholder="请输入终止原因"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="终止原因详细分析">
                        <el-input
                          v-model="formData.zhongzyyxxfx"
                          type="textarea"
                          rows="3"
                          placeholder="请输入终止原因详细分析"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="项目实施现状">
                        <el-input
                          v-model="formData.xmssxz"
                          type="textarea"
                          rows="3"
                          placeholder="请输入项目实施现状"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="可能发生的法律纠纷和经济损失">
                        <el-input
                          v-model="formData.knfsdfljfhjjss"
                          type="textarea"
                          rows="3"
                          placeholder="请输入可能发生的法律纠纷和经济损失"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="其他说明">
                        <el-input
                          v-model="formData.qtsm"
                          type="textarea"
                          rows="3"
                          placeholder="请输入其他说明"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="终止报告">
                        <FileUploader
                          v-model="formData.xmzhongzbg"
                          :disabled="isPreview"
                        ></FileUploader>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="其他相关支撑材料">
                        <FileUploader
                          v-model="formData.qtxgzccl"
                          :disabled="isPreview"
                        ></FileUploader>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="报批报备文件">
                        <FileUploader
                          v-model="formData.bpbbwjlj"
                          :disabled="isPreview"
                        ></FileUploader>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <!-- 项目退出内容 -->
                <el-collapse-item
                  v-if="formData.djlx == 4"
                  title="项目退出内容"
                  name="项目退出内容"
                >
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-form-item label="账面净值">
                        <el-input
                          v-model="formData.zmjz"
                          :min="0"
                          :precision="2"
                          placeholder="0.00"
                          type="number"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="退出盘活收入">
                        <el-input
                          v-model="formData.tcphsr"
                          :min="0"
                          :precision="2"
                          placeholder="0.00"
                          type="number"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="已收到退出/盘活资金">
                        <el-input
                          v-model="formData.ysdtcphzj"
                          :min="0"
                          :precision="2"
                          placeholder="0.00"
                          type="number"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="存在的问题">
                        <el-input
                          v-model="formData.czdwt"
                          type="textarea"
                          rows="3"
                          placeholder="请输入存在的问题"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="下一步工作措施">
                        <el-input
                          v-model="formData.xxbgzcs"
                          type="textarea"
                          rows="3"
                          placeholder="请输入下一步工作措施"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="退出原因">
                        <el-input
                          v-model="formData.tcyy"
                          type="textarea"
                          rows="2"
                          placeholder="请输入退出原因"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="退出原因详细分析">
                        <el-input
                          v-model="formData.tcyyxxfx"
                          type="textarea"
                          rows="3"
                          placeholder="请输入退出原因详细分析"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="项目实施现状">
                        <el-input
                          v-model="formData.xmssxz"
                          type="textarea"
                          rows="3"
                          placeholder="请输入项目实施现状"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="可能发生的法律纠纷和经济损失">
                        <el-input
                          v-model="formData.knfsdfljfhjjss"
                          type="textarea"
                          rows="3"
                          placeholder="请输入可能发生的法律纠纷和经济损失"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="其他说明">
                        <el-input
                          v-model="formData.qtsm"
                          type="textarea"
                          rows="3"
                          placeholder="请输入其他说明"
                          :disabled="isPreview"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>
              </el-collapse>
            </el-form>
          </div>
        </div>
      </div>
      <div class="add-project-header">
        <div class="header-left"></div>
        <div class="header-right">
          <el-button type="default" @click="backClick">返回</el-button>
          <template v-if="!loading && !isPreview">
            <el-button type="primary" @click="saveClick">保存</el-button>
          </template>
        </div>
      </div>
    </div>

    <!-- 新增：选择类型弹窗 -->
    <el-dialog
      v-model="showTypeDialog"
      title="选择登记类型"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form :model="formData" label-width="140">
        <el-form-item
          style="margin-bottom: 24px"
          label="请选择登记类型"
          required
        >
          <el-radio-group v-model="formData.djlx">
            <el-radio value="1">中止</el-radio>
            <el-radio value="2">重启</el-radio>
            <el-radio value="3">终止</el-radio>
            <el-radio value="4">退出</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showTypeDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmType">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  onMounted,
  getCurrentInstance,
  watch,
  nextTick,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import DynamicTable from "@/components/FormDynamicTable/index.vue";
import FileUploader from "@/components/FileUploader/index.vue";
import routerBack from "@/components/common/routerBack.vue";
import { useProjectDetail } from "@/composables/useProjectDetail";
const transferColumns = ref([
  {
    prop: "njfcgbl",
    label: "审批时",
    type: "input",
    disabled: true,
    headerGroup: "投资总额（万元）",
    placeholder: "请输入审批时金额",
  },
  {
    prop: "njfcgblqk",
    label: "已投资",
    type: "input",
    headerGroup: "投资总额（万元）",
    placeholder: "审批时已投资金额",
  },
  {
    prop: "njfcgblqk_nt",
    label: "审批时",
    disabled: true,
    type: "input",
    headerGroup: "我方资本金出资（万元）",
    placeholder: "请填写审批时",
  },
  {
    prop: "zwfcgbl",
    label: "已投资",
    type: "input",
    headerGroup: "我方资本金出资（万元）",
    placeholder: "请填写已投资",
  },
  {
    prop: "jjcgbl",
    disabled: true,
    label: "审批时",
    type: "input",
    headerGroup: "项目全投资内部收益率（税前）%",
    placeholder: "请填写预计",
    min: 0,
  },
  {
    prop: "njfglmc",
    label: "预计",
    type: "input",
    headerGroup: "项目全投资内部收益率（税前）%",
    placeholder: "请填写预计",
  },
  {
    prop: "jjcgbl2",
    label: "审批时",
    disabled: true,
    type: "input",
    headerGroup: "项目全投资内部收益率（税后）%",
    placeholder: "请填写预计",
    min: 0,
  },
  {
    prop: "njfglmc2",
    label: "预计",
    type: "input",
    headerGroup: "项目全投资内部收益率（税后）%",
    placeholder: "请填写预计",
  },
]);

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

const { projectDisabled, cachedInfo } = useProjectDetail();

// ========== 基础配置 ==========
const activeCollapse = ref([
  "基本信息",
  "项目中止内容",
  "项目重启内容",
  "项目终止内容",
  "项目退出内容",
  "项目投资效益",
  "资金构成",
  "登记类型",
  "财务评价指标",
]);
const loading = ref(false);
const isPreview = ref(!!route.query.isPreview);
const projectList = ref([]);
const rcCgqyglId = ref(route.query.id || "");
// 新增：控制类型选择弹窗显示
const showTypeDialog = ref(false);

// ========== 表单数据（完全适配原有后端字段） ==========
const formData = reactive({
  // 原有字段
  xmtzxy: [{}],
  projectGdxxs: [
    {
      njfcgbl: "",
      njfcgblqk_nt: "",
      jjcgbl: "",
      jjcgbl2: "",
      njfcgblqk: "",
      zwfcgbl: "",
      njfglmc: "",
      njfglmc2: "",
    },
  ],

  // 资金构成（使用原有zjgc字段，默认初始化表格结构）
  zjgc: [
    { index: "—", label: "项目资金构成", unit: "", value: "", editable: false },
    {
      index: "1",
      label: "项目资本金",
      unit: "万元",
      value: "",
      editable: true,
    },
    {
      index: "1.1",
      label: "能建方出资",
      unit: "万元",
      value: "",
      editable: true,
    },
    {
      index: "1.2",
      label: "外部股东",
      unit: "万元",
      value: "",
      editable: true,
    },
    { index: "2", label: "贷款", unit: "万元", value: "", editable: true },
    {
      index: "2.1",
      label: "其中: 非并表项目我方贷款/担保额",
      unit: "万元",
      value: "",
      editable: true,
    },
    { index: "3", label: "其他出资", unit: "万元", value: "", editable: true },
    {
      index: "3.1",
      label: "其中: 能建方出资",
      unit: "万元",
      value: "",
      editable: true,
    },
    { index: "", label: "批复总投资", unit: "万元", value: "", editable: true },
  ],

  xmzzbg: [],
  qtxgzccl: [],
  bpbbwjlj: [],

  cqyy: "",
  xmcqbg: [],
  jcwj: [],
});

// ========== 新增：弹窗确认选择类型 ==========
const confirmType = () => {
  if (!formData.djlx) {
    return ElMessage.warning("请选择登记类型");
  }
  showTypeDialog.value = false;
};

// ========== 新增：资金构成变更处理方法 ==========
const handleZjgcChange = (row) => {
  // 1. 批复总投资变更 → 同步到投资总额（万元）-审批时
  if (row.label === "批复总投资" && row.value !== "") {
    // 确保xmtzxy有数据行
    if (!formData.xmtzxy[0]) formData.xmtzxy[0] = {};
    formData.xmtzxy[0].njfcgbl = row.value;
  }

  // 2. 项目资本金变更 → 同步到我方资本金出资（万元）-审批时
  if (row.label === "项目资本金" && row.value !== "") {
    if (!formData.xmtzxy[0]) formData.xmtzxy[0] = {};
    formData.xmtzxy[0].njfcgblqk_nt = row.value;
  }
};

// ========== 新增：财务指标变更处理方法 ==========
const handleFinancialIndexChange = (field) => {
  if (!formData.xmtzxy[0]) formData.xmtzxy[0] = {};

  // 1. 决策:项目投资内部收益率(税前) → 同步到项目全投资内部收益率（税前）%-审批时
  if (field === "jcxmtznbsylsq" && formData.jcxmtznbsylsq !== "") {
    formData.xmtzxy[0].jjcgbl = formData.jcxmtznbsylsq;
  }

  // 2. 项目资本金内部收益率 → 同步到项目全投资内部收益率（税后）%-审批时
  if (field === "xmzbjnbsyl" && formData.xmzbjnbsyl !== "") {
    formData.xmtzxy[0].jjcgbl2 = formData.xmzbjnbsyl;
  }
};

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

// ========== 选择项目同步名称及相关信息 ==========
const changeProject = (val) => {
  loading.value = true;
  proxy.$post({
    url: "/api/project/getProjectFinalInfo",
    data: { id: val },
    callback: (data) => {
      loading.value = false;
      if (!data) return;

      // // 回填基础信息
      // formData.projectName = data.projectName || "";
      // formData.sbdw = data.sbdw || "";
      // formData.xmgsqc = data.xmgsqc || "";
      // formData.xmkgsjyj = data.xmkgsjyj || "";
      // formData.xmjgsjyj = data.xmjgsjyj || "";
      // formData.yynxn = data.yynxn || 0;
      // formData.xmjsqy = data.xmjsqy || 0;

      // // 回填项目投资效益表格数据
      // formData.projectGdxxs[0].njfcgblqk_nt =
      //   data.projectXmtzzes?.at(1)?.children?.at(0)?.rmbjj || "";
      // formData.projectGdxxs[0].njfcgbl =
      //   data.projectXmtzzes?.at(2)?.rmbjj || "";
      // formData.projectGdxxs[0].jjcgbl = data.projectCwpjzbs?.at(0)?.num || "";
      // formData.projectGdxxs[0].jjcgbl2 = data.projectCwpjzbs?.at(1)?.num || "";

      // // 回填资金构成（兼容后端返回的zjgc数据）
      // if (data.zjgc && Array.isArray(data.zjgc)) {
      //   formData.zjgc = data.zjgc.map((item) => ({
      //     ...item,
      //     editable: item.editable !== false,
      //   }));
      // }

      // // 回填财务评价指标
      // formData.jcxmtznbsylsq = data.jcxmtznbsylsq || "";
      // formData.xmzbjnbsyl = data.xmzbjnbsyl || "";
      // formData.xmtzhsq = data.xmtzhsq || "";
      // formData.sjycxmqtznbsylsq = data.sjycxmqtznbsylsq || "";
      // formData.ycxmzbjnbsylsh = data.ycxmzbjnbsylsh || "";
    },
    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/getXmtcInfo",
    data: { id: rcCgqyglId.value },
    callback: async (data) => {
      loading.value = false;
      if (!data) return ElMessage.error("未查询到数据");

      // 回填表单数据（自动适配所有原有字段）
      Object.assign(formData, data);

      // 确保资金构成字段是数组格式
      if (!Array.isArray(formData.zjgc)) {
        formData.zjgc = [
          {
            index: "—",
            label: "项目资金构成",
            unit: "",
            value: "",
            editable: false,
          },
          {
            index: "1",
            label: "项目资本金",
            unit: "万元",
            value: "",
            editable: true,
          },
          {
            index: "1.1",
            label: "能建方出资",
            unit: "万元",
            value: "",
            editable: true,
          },
          {
            index: "1.2",
            label: "外部股东",
            unit: "万元",
            value: "",
            editable: true,
          },
          {
            index: "2",
            label: "贷款",
            unit: "万元",
            value: "",
            editable: true,
          },
          {
            index: "2.1",
            label: "其中: 非并表项目我方贷款/担保额",
            unit: "万元",
            value: "",
            editable: true,
          },
          {
            index: "3",
            label: "其他出资",
            unit: "万元",
            value: "",
            editable: true,
          },
          {
            index: "3.1",
            label: "其中: 能建方出资",
            unit: "万元",
            value: "",
            editable: true,
          },
          {
            index: "",
            label: "批复总投资",
            unit: "万元",
            value: "",
            editable: true,
          },
        ];
      }

      // 编辑状态下如果已有类型值，不弹出弹窗；否则弹出
      if (!isPreview.value) {
        nextTick(() => {
          showTypeDialog.value = true;
        });
      }
    },
    error: () => {
      loading.value = false;
      ElMessage.error("获取详情失败");
    },
  });
};

// ========== 保存表单 ==========
const saveClick = () => {
  // 新增：保存前校验类型是否选择
  if (!formData.djlx) {
    ElMessage.warning("请先选择登记类型");
    showTypeDialog.value = true;
    return;
  }

  if (!formData.projectId) return ElMessage.warning("请选择项目信息");
  loading.value = true;
  const url = rcCgqyglId.value
    ? "/api/project/updateXmtc"
    : "/api/project/createXmtc";

  // 组装提交数据（完全使用原有字段，不新增）
  const submitData = {
    ...formData,
    projectId: String(formData.projectId),
  };

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

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

onMounted(() => {
  getProjectData();
  if (cachedInfo) {
    formData.projectName = cachedInfo.projectName || "";
    formData.projectId = cachedInfo.projectId || "";
  }

  // 非预览状态下自动弹出类型选择弹窗
  if (!isPreview.value) {
    if (rcCgqyglId.value) {
      // 编辑状态：先获取详情，再判断是否弹出
      getJsqtzjcDetail();
    } else {
      // 新增状态：直接弹出
      nextTick(() => {
        showTypeDialog.value = true;
      });
    }
  } else {
    // 预览状态：获取详情但不弹出弹窗
    if (rcCgqyglId.value) {
      getJsqtzjcDetail();
    }
  }
});
</script>

<style scoped lang="less"></style>
