<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="24">
                    <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="所属行业">
                        <CommonSelector
                          v-model="formData.sshy"
                          dictName="participation_industry"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目公司名称">
                        <el-input
                          v-model="formData.xmgsmc"
                          placeholder="请输入项目公司名称"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item label="填报单位名称">
                        <el-input
                          v-model="formData.sbdw"
                          placeholder="请输入填报单位名称"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item label="所属二级企业">
                        <el-input
                          v-model="formData.ssejqy"
                          placeholder="请输入所属二级企业"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="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="项目类别">
                        <CommonSelector
                          v-model="formData.xmlx"
                          dictName="xmlx"
                        ></CommonSelector>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="投资模式分类">
                        <CommonSelector
                          v-model="formData.tzms"
                          dictName="tzms"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="投资回收方式">
                        <CommonSelector
                          v-model="formData.tzhsfs"
                          dictName="tzhsfs"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item label="下年项目阶段">
                        <CommonSelector
                          v-model="formData.xnxmjd"
                          dictName="xmjd"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="财务报表类型">
                        <CommonSelector
                          v-model="formData.cwbblx"
                          dictName="cwbblx"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <DynamicTable
                    :columns="transferColumns"
                    :disabled="isPreview"
                    v-model="formData.projectGdxxs"
                  >
                  </DynamicTable>
                </el-collapse-item>

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

                <el-collapse-item
                  title="2025年投资回收累计完成情况-年度更新"
                  name="2025年投资回收累计完成情况-年度更新"
                >
                  <el-row gutter="20">
                    <!-- 第一行：决策目标值相关数字项 -->
                    <el-col :span="12">
                      <el-form-item label="本年完成 投资回收决策目标值（万元）">
                        <el-input
                          v-model="formData.bnwc"
                          type="number"
                          precision="8"
                          placeholder="请输入本年完成 投资回收决策目标值（万元）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="截止本年累计（决策目标值）">
                        <el-input
                          v-model="formData.jzbnlj"
                          type="number"
                          precision="8"
                          placeholder="请输入截止本年累计（决策目标值）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="下一年完成数（万元）">
                        <el-input
                          v-model="formData.xynwcs"
                          type="number"
                          precision="8"
                          placeholder="请输入下一年完成数（万元）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="本年计划（万元）">
                        <el-input
                          v-model="formData.bnjh"
                          type="number"
                          precision="8"
                          placeholder="请输入本年计划（万元）"
                        />
                      </el-form-item>
                    </el-col>

                    <!-- 第二行：实际值相关数字项 -->
                    <el-col :span="12">
                      <el-form-item label="本年完成--投资回收实际值（万元）">
                        <el-input
                          v-model="formData.bnwcsjz"
                          type="number"
                          precision="8"
                          placeholder="请输入本年完成--投资回收实际值（万元）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="截止本年累计--投资回收实际值">
                        <el-input
                          v-model="formData.jzbnljsjz"
                          type="number"
                          precision="8"
                          placeholder="请输入截止本年累计--投资回收实际值"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="累计欠收（万元）">
                        <el-input
                          v-model="formData.ljqs"
                          type="number"
                          precision="8"
                          placeholder="请输入累计欠收（万元）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="完成率（%）">
                        <el-input
                          v-model="formData.wcl"
                          type="number"
                          precision="2"
                          placeholder="请输入完成率（%）"
                        />
                      </el-form-item>
                    </el-col>

                    <!-- 第三行及以后：长文本说明项（占满整行） -->
                    <el-col :span="24">
                      <el-form-item label="计划与决策目标值差异说明">
                        <el-input
                          v-model="formData.jhyjcmbcysm"
                          type="textarea"
                          rows="3"
                          placeholder="请输入计划与决策目标值差异说明"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="实际与计划差异说明">
                        <el-input
                          v-model="formData.sjyjhcysm"
                          type="textarea"
                          rows="3"
                          placeholder="请输入实际与计划差异说明"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="存在主要问题">
                        <el-input
                          v-model="formData.czdzywt"
                          type="textarea"
                          rows="3"
                          placeholder="请输入存在主要问题"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="采取措施及开展情况">
                        <el-input
                          v-model="formData.cqcsjgzkzqk"
                          type="textarea"
                          rows="3"
                          placeholder="请输入采取措施及开展情况"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="备注">
                        <el-input
                          v-model="formData.bz"
                          type="textarea"
                          rows="3"
                          placeholder="请输入备注"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

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

                <el-collapse-item
                  title="截止12月末累计实收"
                  name="截止12月末累计实收"
                >
                  <FinancialTable
                    v-model="formData.jzymljsh"
                    :is-preview="isPreview"
                  />
                </el-collapse-item>
                <el-collapse-item
                  title="投资回收（决策）"
                  name="投资回收（决策）"
                >
                  <FinancialTable
                    v-model="formData.tzhsjc"
                    :is-preview="isPreview"
                  />
                </el-collapse-item>
                <el-collapse-item
                  title="投资回收（计划）"
                  name="投资回收（计划）"
                >
                  <FinancialTable
                    v-model="formData.tzhsjh"
                    :is-preview="isPreview"
                  />
                </el-collapse-item>
              </el-collapse>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

// 折叠面板默认展开项
const activeCollapse = ref([
  "项目基本信息",
  "出资情况",
  "合同约定权益获取",
  "分红情况",
  "投资额完成情况（万元）",
  "投资回收（决策）",
  "投资回收（计划）",
  "2025年投资回收累计完成情况-年度更新",
  "净现金流",
  "截止12月末累计应收",
  "截止12月末累计实收",
  "资金流出",
  "分红情况",
]);

// 表单数据
let initTableData = () => {
  Object.assign(formData, {
    jzymljys: {
      // 指标列表
      indicatorList: [
        { name: "政府付费", isTextRow: false, noTotal: false },
        { name: "政府补贴", isTextRow: false, noTotal: false },
        { name: "使用者付费", isTextRow: false, noTotal: false },
        { name: "使用者欠付", isTextRow: false, noTotal: false },
        { name: "补贴收入", isTextRow: false, noTotal: false },
        {
          name: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
          isTextRow: false,
          noTotal: false,
        },
        { name: "资产盘活", isTextRow: false, noTotal: false },
        { name: "股权分红", isTextRow: false, noTotal: false },
        { name: "其他", isTextRow: false, noTotal: false },
        // 关键：标记为文本行+不需要合计
        { name: "目标（决策）与计划差异说明", isTextRow: true, noTotal: true },
      ],

      // 时间列表（月度）
      dynamicTimeList: [
        "一月",
        "二月",
        "三月",
        "四月",
        "五月",
        "六月",
        "七月",
        "八月",
        "九月",
        "十月",
        "十一月",
        "十二月",
      ],
      // 表格数据（子组件会自动初始化，父组件可传初始值）
      tableData: [],
    },
    jzymljsh: {
      // 指标列表
      indicatorList: [
        { name: "政府付费", isTextRow: false, noTotal: false },
        { name: "政府补贴", isTextRow: false, noTotal: false },
        { name: "使用者付费", isTextRow: false, noTotal: false },
        { name: "使用者欠付", isTextRow: false, noTotal: false },
        { name: "补贴收入", isTextRow: false, noTotal: false },
        {
          name: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
          isTextRow: false,
          noTotal: false,
        },
        { name: "资产盘活", isTextRow: false, noTotal: false },
        { name: "股权分红", isTextRow: false, noTotal: false },
        { name: "其他", isTextRow: false, noTotal: false },
        // 关键：标记为文本行+不需要合计
        { name: "目标（决策）与计划差异说明", isTextRow: true, noTotal: true },
      ],

      // 时间列表（月度）
      dynamicTimeList: [
        "一月",
        "二月",
        "三月",
        "四月",
        "五月",
        "六月",
        "七月",
        "八月",
        "九月",
        "十月",
        "十一月",
        "十二月",
      ],
      // 表格数据（子组件会自动初始化，父组件可传初始值）
      tableData: [],
    },
    tzhsjc: {
      // 指标列表
      indicatorList: [
        { name: "建设期政府付费", isTextRow: false, noTotal: false },
        { name: "运营期政府付费", isTextRow: false, noTotal: false },
        { name: "投资价差收取", isTextRow: false, noTotal: false },
        { name: "参股项目投资回收", isTextRow: false, noTotal: false },
        { name: "代建工程款回收", isTextRow: false, noTotal: false },
        { name: "政府付费", isTextRow: false, noTotal: false },
        { name: "政府补贴", isTextRow: false, noTotal: false },
        { name: "使用者付费", isTextRow: false, noTotal: false },
        { name: "使用者欠付", isTextRow: false, noTotal: false },
        { name: "补贴收入", isTextRow: false, noTotal: false },
        {
          name: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
          isTextRow: false,
          noTotal: false,
        },
        { name: "资产盘活", isTextRow: false, noTotal: false },
        { name: "股权分红", isTextRow: false, noTotal: false },
        { name: "其他", isTextRow: false, noTotal: false },
        // 关键：标记为文本行+不需要合计
        { name: "目标（决策）与计划差异说明", isTextRow: true, noTotal: true },
      ],

      // 时间列表（月度）
      dynamicTimeList: ["一季度", "二季度", "三季度", "四季度"],
      // 表格数据（子组件会自动初始化，父组件可传初始值）
      tableData: [],
    },
    tzhsjh: {
      // 指标列表
      indicatorList: [
        { name: "建设期政府付费", isTextRow: false, noTotal: false },
        { name: "运营期政府付费", isTextRow: false, noTotal: false },
        { name: "投资价差收取", isTextRow: false, noTotal: false },
        { name: "参股项目投资回收", isTextRow: false, noTotal: false },
        { name: "代建工程款回收", isTextRow: false, noTotal: false },
        { name: "政府付费", isTextRow: false, noTotal: false },
        { name: "政府补贴", isTextRow: false, noTotal: false },
        { name: "使用者付费", isTextRow: false, noTotal: false },
        { name: "使用者欠付", isTextRow: false, noTotal: false },
        { name: "补贴收入", isTextRow: false, noTotal: false },
        {
          name: "销售回款（含房地产、水泥、新能源售电、其他生产制造收入等）",
          isTextRow: false,
          noTotal: false,
        },
        { name: "资产盘活", isTextRow: false, noTotal: false },
        { name: "股权分红", isTextRow: false, noTotal: false },
        { name: "其他", isTextRow: false, noTotal: false },
        // 关键：标记为文本行+不需要合计
        { name: "目标（决策）与计划差异说明", isTextRow: true, noTotal: true },
      ],

      // 时间列表（月度）
      dynamicTimeList: ["一季度", "二季度", "三季度", "四季度"],
      // 表格数据（子组件会自动初始化，父组件可传初始值）
      tableData: [],
    },
  });
};
const formData = reactive({
  jzymljys: {},
  jzymljsh: {},
  tzhsjc: {},
  tzhsjh: {},
  projectGdxxs: [],
});

let options = ref();

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

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

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

  loading.value = true;
  proxy.$post({
    url: "/api/project/getYyqtzhsInfo",
    data: { id: rcCgqyglId.value },
    callback: (data) => {
      loading.value = false;
      console.log(data.jzymljys.tableData[0], "1111");

      Object.assign(formData, {
        ...data,
      });
    },
  });
};

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

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

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

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

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

// 页面初始化
onMounted(() => {
  // 获取项目列表
  getProjectData();
  options.value = JSON.parse(sessionStorage.getItem("resourceData"));
  // 如果有ID则加载详情
  if (rcCgqyglId.value) {
    getRcCgqyglDetail();
  } else {
    initTableData();
  }
});
</script>

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

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