<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" :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.key"
                            :label="item.projectName"
                            :value="item.id"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <!-- 6类主体成本指标体系一览表：给costTab1传初始化数据 -->
                <el-collapse-item
                  title="6类主体成本指标体系一览表"
                  name="6类主体成本指标体系一览表"
                >
                  <costTab
                    ref="costTab1Ref"
                    :isPreview="isPreview"
                    :init-table-data="formData.yjzb"
                    v-if="formData.yjzb && formData.yjzb.length > 0"
                  />
                  <costTab
                    ref="costTab1Ref2"
                    :isPreview="isPreview"
                    :init-table-data="formData.ejzb"
                    v-if="formData.ejzb && formData.ejzb.length > 0"
                  />
                </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>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, getCurrentInstance } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import costTab from "./costTab1.vue";
import routerBack from "@/components/common/routerBack.vue";
// 路由与全局实例
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

// 折叠面板默认展开项
const activeCollapse = ref([
  "项目信息",
  "6类主体成本指标体系一览表",
  "期中履约终止移交",
  "期满移交",
]);

// 🌟 新增：costTab1的ref引用，用于调用子组件方法
const costTab1Ref = ref(null);
// 🌟 修改1：新增ejzb对应的子组件ref引用
const costTab1Ref2 = ref(null);

// 表单核心数据
const formData = reactive({
  projectName: "",
  projectId: "",
  del: 0,
  createdAt: "",
  updatedAt: "",
  // 🌟 新增：costTab1的初始化数据（编辑时从接口获取，新增时用默认值）
  yjzb: [],
  // 🌟 修改2：将ejzb从对象改为数组（和yjzb保持一致）
  ejzb: [],
});

// 状态管理
const loading = ref(false);
const isPreview = ref(!!route.query.isPreview);
const projectList = ref([]);
const rcCgqyglId = ref(route.query.id || "");
let options = ref();

// 获取项目列表数据
const getProjectData = (params = {}) => {
  proxy.$post({
    url: "/api/project/listProject",
    data: {
      page: 1,
      pagesize: 1000,
      attributes: [],
      menuType: "xmjc",
      ...params,
    },
    callback: (data) => {
      projectList.value = data.rows || [];
    },
  });
};

// 选择项目同步名称
const changeProject = (val) => {
  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/getCbgl",
    data: { id: rcCgqyglId.value },
    callback: (data) => {
      loading.value = false;
      Object.assign(formData, data);
    },
  });
};

// 返回上一页
const backClick = () => {
  router.back(-1);
};

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

  loading.value = true;
  try {
    const costTab1EditedData = costTab1Ref.value?.getEditedTableData() || [];
    const costTab1EditedData2 = costTab1Ref2.value?.getEditedTableData() || [];
    console.log(costTab1EditedData, "costTab1EditedData");
    console.log(costTab1EditedData2, "costTab1EditedData2");

    const url = rcCgqyglId.value
      ? "/api/project/updateCbgl"
      : "/api/project/createCbgl";
    const submitData = {
      ...formData,
      projectId: formData.projectId + "",
      yjzb: costTab1EditedData,
      // 🌟 修改4：将ejzb的编辑后数据加入提交参数
      ejzb: costTab1EditedData2,
    };

    await proxy.$post({
      url: url,
      data: submitData,
      callback: () => {
        ElMessage.success("保存成功");
      },
    });
  } catch (error) {
    ElMessage.error("保存失败，请重试");
    console.error("保存失败：", error);
  } finally {
    loading.value = false;
  }
};

// 页面初始化
onMounted(() => {
  getProjectData();
  options.value = JSON.parse(sessionStorage.getItem("resourceData"));
  if (rcCgqyglId.value) {
    getJsqtzjcDetail();
  } else {
    // yjzb 初始化数据（保持原有逻辑）
    formData.yjzb = [
      {
        serialNumber: { value: "", placeholder: "1" },
        entityType: { value: "", placeholder: "交投本部" },
        rows: [
          {
            level1Code: { value: "", placeholder: " (1) " },
            level1Name: { value: "", placeholder: "ROA，辅以总资产周转率" },
            level1Content: {
              value: "",
              placeholder:
                "ROA=净利率×总资产周转率；重资产企业要不断提高净利水平，要不加快资产变现。",
            },

            level1Target: { value: "", placeholder: "中期ROA提升2%" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "①" },
            level2Name: { value: "", placeholder: "3类费用压降比例" },
            level2Content: {
              value: "",
              placeholder: "考核非生产性支出控制成果",
            },
            level2Target: { value: "", placeholder: "近期降1%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
          {
            level1Code: { value: "", placeholder: "(2)" },
            level1Name: { value: "", placeholder: "成本营收比" },
            level1Content: {
              value: "",
              placeholder: "衡量企业成本控制效率和资产盈利能力（重资产企业）。",
            },
            level1Target: { value: "", placeholder: "≥能建考核值的90%" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "②" },
            level2Name: { value: "", placeholder: "每亿元“投资+营收”管理费" },
            level2Content: { value: "", placeholder: "成本费用支出效率" },
            level2Target: { value: "", placeholder: "近期升5%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
          {
            level1Code: { value: "", placeholder: "(3)" },
            level1Name: { value: "", placeholder: "投资控制偏差率*" },
            level1Content: {
              value: "",
              placeholder: "考核建设项目投资控制能力。",
            },
            level1Target: { value: "", placeholder: "≤0" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "③" },
            level2Name: { value: "", placeholder: "概预差*" },
            level2Content: {
              value: "",
              placeholder: "设计阶段限额设计和设计优化的工作成果",
            },
            level2Target: { value: "", placeholder: "≥3%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
        ],
      },
      {
        serialNumber: { value: "", placeholder: "2" },
        entityType: { value: "", placeholder: "建设项目" },
        rows: [
          {
            level1Code: { value: "", placeholder: "(4)" },
            level1Name: { value: "", placeholder: "投资价差收取达成率" },
            level1Content: {
              value: "",
              placeholder:
                "考核投资项目设计优化、合同策划、承包穿透管理和投资价差催收4方面综合能力。",
            },
            level1Target: { value: "", placeholder: "≥100%" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "④" },
            level2Name: { value: "", placeholder: "施工合同降造比例*" },
            level2Content: {
              value: "",
              placeholder:
                "协同施工单位承包合同价（单价水平）较批复预算（除激励基金和风险费外）下降比例。",
            },
            level2Target: { value: "", placeholder: "能建要求≥15%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
          {
            level1Code: { value: "", placeholder: "(5)" },
            level1Name: { value: "", placeholder: "综合融资成本率**" },
            level1Content: {
              value: "",
              placeholder: "建设期融资成本控制水平。",
            },
            level1Target: { value: "", placeholder: "≤银行业自律利率" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "⑤" },
            level2Name: { value: "", placeholder: "投资价差同步收取比例" },
            level2Content: {
              value: "",
              placeholder: "投资价差收取同步性情况。",
            },
            level2Target: { value: "", placeholder: "≥100%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
          {
            level1Code: { value: "", placeholder: "/" },
            level1Name: { value: "", placeholder: "" },
            level1Content: { value: "", placeholder: "" },
            level1Target: { value: "", placeholder: "" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "⑥" },
            level2Name: { value: "", placeholder: "变更索赔费用占预备费比例" },
            level2Content: {
              value: "",
              placeholder: "衡量履约阶段投资控制质量。",
            },
            level2Target: { value: "", placeholder: "<70%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
        ],
      },
      {
        serialNumber: { value: "", placeholder: "3" },
        entityType: { value: "", placeholder: "运营项目" },
        rows: [
          {
            level1Code: { value: "", placeholder: "(6)" },
            level1Name: { value: "", placeholder: "百元营收“管理费+运行费”" },
            level1Content: { value: "", placeholder: "管理、运行成本控制水平" },
            level1Target: { value: "", placeholder: "同行业均值之下" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "⑦" },
            level2Name: { value: "", placeholder: "集约化、智能化措施完成率" },
            level2Content: {
              value: "",
              placeholder: "考核公司“三定方案”等降本措施落实情况",
            },
            level2Target: { value: "", placeholder: "100%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
        ],
      },
    ];
    // 🌟 修改5：ejzb 初始化数据（和yjzb结构完全一致）
    formData.ejzb = [
      {
        serialNumber: { value: "", placeholder: "4" },
        entityType: { value: "", placeholder: " 工程建设类 " },
        rows: [
          {
            level1Code: { value: "", placeholder: "(7)" },
            level1Name: { value: "", placeholder: " 累计养护成本总成本比例 " },
            level1Content: {
              value: "",
              placeholder: " 综合养护能力和养护成本控制水平。",
            },
            level1Target: { value: "", placeholder: " 三块算养护成本 " },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "⑧" },
            level2Name: { value: "", placeholder: " 百公里养护成本 " },
            level2Content: {
              value: "",
              placeholder:
                " 在 POI 等养护质量指标达标前提下，养护成本控制水平 ",
            },
            level2Target: { value: "", placeholder: " 降低 1%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
          {
            level1Code: { value: "", placeholder: "(8)" },
            level1Name: { value: "", placeholder: " 综合融资成本率 " },
            level1Content: {
              value: "",
              placeholder: " 运营期融资成本控制水平。",
            },
            level1Target: { value: "", placeholder: " 三目制利率 + 10BP" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "⑨" },
            level2Name: { value: "", placeholder: " 车车通收费人数 " },
            level2Content: {
              value: "",
              placeholder: " 考核智慧化改造、少人化收费工作落实情况 ",
            },
            level2Target: { value: "", placeholder: " 降低 15%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
          {
            level1Code: { value: "", placeholder: "(9)" },
            level1Name: { value: "", placeholder: " 成本营收比 " },
            level1Content: {
              value: "",
              placeholder: " 公司成本管控水平和业务盈利水平（有利润的营收）。",
            },
            level1Target: { value: "", placeholder: "≤85%" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "⑩" },
            level2Name: { value: "", placeholder: " 项目平均毛利率 " },
            level2Content: { value: "", placeholder: " 项目成本控制水平 " },
            level2Target: { value: "", placeholder: "≥15%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
          {
            level1Code: { value: "", placeholder: "(10)" },
            level1Name: { value: "", placeholder: " 总部支出占营收比例 " },
            level1Content: {
              value: "",
              placeholder: " 总部成本控制水平及业务发展规模。",
            },
            level1Target: { value: "", placeholder: "≤10%" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "⑪" },
            level2Name: { value: "", placeholder: " 项目成本责任制覆盖率 " },
            level2Content: {
              value: "",
              placeholder: " 集团标后预算等成本管理制度落实情况。",
            },
            level2Target: { value: "", placeholder: "100%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
          {
            level1Code: { value: "", placeholder: "(11)" },
            level1Name: { value: "", placeholder: " 项目直接费占总成本比例 " },
            level1Content: {
              value: "",
              placeholder: " 项目直接成本水平不增的前提下降低间接成本 ",
            },
            level1Target: { value: "", placeholder: " 近期升 5%" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "⑫" },
            level2Name: { value: "", placeholder: " 项目直接费占总成本比例 " },
            level2Content: {
              value: "",
              placeholder: " 项目直接成本水平不增的前提下降低间接成本 ",
            },
            level2Target: { value: "", placeholder: " 近期升 5%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
          {
            level1Code: { value: "", placeholder: "(12)" },
            level1Name: { value: "", placeholder: " 营收收现比例 " },
            level1Content: { value: "", placeholder: " 有现金流的利润。" },
            level1Target: { value: "", placeholder: "≥能建考核指标 " },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "⑬" },
            level2Name: { value: "", placeholder: " 专业分包比例 *" },
            level2Content: { value: "", placeholder: " 自营施工水平。" },
            level2Target: { value: "", placeholder: "≤50%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
        ],
      },
      {
        serialNumber: { value: "", placeholder: "5" },
        entityType: { value: "", placeholder: " 路衍经济类 " },
        rows: [
          {
            level1Code: { value: "", placeholder: "(13)" },
            level1Name: { value: "", placeholder: " 成本营收比 " },
            level1Content: {
              value: "",
              placeholder: " 公司成本管控水平和业务盈利水平（有利润的营收）。",
            },
            level1Target: { value: "", placeholder: "≤85%" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "⑭" },
            level2Name: { value: "", placeholder: " 商业策划覆盖比例 " },
            level2Content: {
              value: "",
              placeholder:
                " 考核商业分析、经营策划、成本核算等经营机制建立情况 ",
            },
            level2Target: { value: "", placeholder: "100%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
          {
            level1Code: { value: "", placeholder: "(14)" },
            level1Name: { value: "", placeholder: " 总部支出占营收比例 " },
            level1Content: {
              value: "",
              placeholder: " 总部成本控制水平及业务发展规模。",
            },
            level1Target: { value: "", placeholder: "≤10%" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "⑮" },
            level2Name: { value: "", placeholder: " 各类业务净利率 " },
            level2Content: {
              value: "",
              placeholder: " 考核业务筛选、成本优化、经营能力提升等情况 ",
            },
            level2Target: { value: "", placeholder: " 均≥0%" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
        ],
      },
      {
        serialNumber: { value: "", placeholder: "6" },
        entityType: { value: "", placeholder: " 功能性单位 " },
        rows: [
          {
            level1Code: { value: "", placeholder: "(15)" },
            level1Name: { value: "", placeholder: " 经费预算纳入考核比例 " },
            level1Content: { value: "", placeholder: " 考核成本体系建立情况 " },
            level1Target: { value: "", placeholder: "100%" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "/" },
            level2Name: { value: "", placeholder: "" },
            level2Content: { value: "", placeholder: "" },
            level2Target: { value: "", placeholder: "" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
          {
            level1Code: { value: "", placeholder: "(16)" },
            level1Name: { value: "", placeholder: " 委外成果与付费挂钩比例 " },
            level1Content: {
              value: "",
              placeholder: " 考核引入中介和委外咨询服务效率评价体系建立情况 ",
            },
            level1Target: { value: "", placeholder: "100%" },
            level1EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
            level2Code: { value: "", placeholder: "/" },
            level2Name: { value: "", placeholder: "" },
            level2Content: { value: "", placeholder: "" },
            level2Target: { value: "", placeholder: "" },
            level2EvaluationResult: {
              value: "",
              placeholder: "请输入考核结果",
            },
          },
        ],
      },
    ];
  }
});
</script>

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