<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.key"
                            :label="item.projectName"
                            :value="item.id"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="项目所处阶段">
                        <el-select
                          v-model="formData.xmscjd"
                          placeholder="请选择项目所处阶段"
                        >
                          <el-option
                            v-for="item in options?.xmjd"
                            :key="item.key"
                            :label="item.name"
                            :value="item.key"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="全称">
                        <el-input
                          v-model="formData.qc"
                          placeholder="请输入全称"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="简称">
                        <el-input
                          v-model="formData.jc"
                          placeholder="请输入简称"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="内部投资管理主体">
                        <el-input
                          v-model="formData.nbtzglzt"
                          placeholder="请输入内部投资管理主体"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="股权结构">
                        <el-input
                          v-model="formData.gqjg"
                          placeholder="请输入股权结构"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>

                <el-collapse-item title="出资情况" name="出资情况">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item
                        label-width="210"
                        label="项目资本金总额（亿元）"
                      >
                        <el-input
                          type="number"
                          v-model.number="formData.xmzbjze"
                          placeholder="请输入项目资本金总额（亿元）"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label-width="210"
                        label="公司资本金应出资总额（亿元）"
                      >
                        <el-input
                          type="number"
                          v-model.number="formData.gszbjyczze"
                          placeholder="请输入公司资本金应出资总额（亿元）"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item
                        label-width="210"
                        label="公司当前应出资额（亿元）"
                      >
                        <el-input
                          type="number"
                          v-model.number="formData.gsdqycze"
                          placeholder="请输入公司当前应出资额（亿元）"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label-width="210"
                        label="公司当前已出资额（亿元）"
                      >
                        <el-input
                          type="number"
                          v-model.number="formData.gsdqyjcze"
                          placeholder="请输入公司当前已出资额（亿元）"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item
                        label-width="210"
                        label="公司当前应出未出金额（亿元）"
                      >
                        <el-input
                          type="number"
                          v-model.number="formData.gsdqycwcje"
                          placeholder="请输入公司当前应出未出金额（亿元）"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label-width="210"
                        label="公司当前剩余出资额（亿元）"
                      >
                        <el-input
                          type="number"
                          v-model.number="formData.gsdqsycze"
                          placeholder="请输入公司当前剩余出资额（亿元）"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label-width="210" label="超股比出资情况">
                        <el-input
                          v-model="formData.cgbczqk"
                          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="我方权益合同条款约定">
                        <el-input
                          type="textarea"
                          v-model="formData.wfqyhttkyd"
                          placeholder="请输入我方权益合同条款约定（市场、设计、施工、运营权、养护份额等权益）"
                          :rows="3"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="权益获取进展">
                        <el-input
                          type="textarea"
                          v-model="formData.qyhqjz"
                          placeholder="请输入权益获取进展"
                          :rows="3"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="权益获取与约定不一致的情况">
                        <el-input
                          type="textarea"
                          v-model="formData.qyhqyyd"
                          placeholder="请输入权益获取与约定不一致的情况"
                          :rows="3"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="督办情况">
                        <el-input
                          type="textarea"
                          v-model="formData.dbqk"
                          placeholder="请输入督办情况"
                          :rows="3"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </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.lrfp"
                          placeholder="请输入利润分配/分红约定"
                          :rows="2"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="是否达到利润分配条件">
                        <el-radio-group
                          placeholder="请选择是否达到利润分配条件"
                          v-model="formData.sfddlrfptj"
                        >
                          <el-radio
                            v-for="item in options?.sf"
                            :key="item.id"
                            :id="item.name"
                            :value="item.key"
                            >{{ item.name }}</el-radio
                          >
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="累计获取分红（万元）">
                        <el-input
                          type="number"
                          v-model.number="formData.ljhqfh"
                          placeholder="请输入累计获取分红（万元）"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>
                <el-collapse-item title="资金流出" name="资金流出">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="应投入资金（万元）">
                        <el-input
                          type="number"
                          v-model.number="formData.ytrzj"
                          placeholder="请输入应投入资金（万元）"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="累计投入资金（万元）">
                        <el-input
                          type="number"
                          v-model.number="formData.ljtrzj"
                          placeholder="请输入累计投入资金（万元）"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="尚需投入资金（万元）">
                        <el-input
                          type="number"
                          v-model.number="formData.sxtrzj"
                          placeholder="请输入尚需投入资金（万元）"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-collapse-item>
                <el-collapse-item title="资金流入" name="资金流入">
                  <div class="tab-handle">
                    <el-button type="primary" @click="addPfyjlsqk"
                      >新增</el-button
                    >
                  </div>
                  <el-table
                    :data="wtyys"
                    style="width: 100%"
                    empty-text="暂无数据"
                    show-summary
                    :summary-method="sumWtyysColumns"
                    border
                  >
                    <el-table-column type="index" width="60" label="序号" />
                    <el-table-column prop="lx" label="类型">
                      <template #default="scope">
                        <el-select
                          v-model="scope.row.lx"
                          placeholder="请选择"
                          no-data-text="暂无数据"
                        >
                          <el-option
                            v-for="item in options?.participation_capital"
                            :key="item.key"
                            :label="item.name"
                            :value="item.key"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>

                    <el-table-column prop="fwsj" label="服务时间">
                      <template #default="scope">
                        <el-date-picker
                          v-model="scope.row.fwsj"
                          type="datetime"
                          format="YYYY-MM-DD HH:mm:ss"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column prop="htje" label="合同金额（万元）">
                      <template #default="scope">
                        <el-input
                          type="number"
                          v-model.number="scope.row.htje"
                          placeholder="请输入合同金额（万元）"
                          step="0.01"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column prop="ywlr" label="业务利润（万元）">
                      <template #default="scope">
                        <el-input
                          type="number"
                          v-model.number="scope.row.ywlr"
                          placeholder="请输入业务利润（万元）"
                          step="0.01"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="60">
                      <template #default="scope">
                        <el-button
                          link
                          type="danger"
                          size="small"
                          @click="deletePfyjlsqk(scope.$index)"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>

                  <div class="tab-handle">
                    <el-button type="primary" @click="addTzfhs">新增</el-button>
                  </div>
                  <el-table
                    :data="tzfhs"
                    style="width: 100%"
                    empty-text="暂无数据"
                    show-summary
                    :summary-method="sumTzfhsColumns"
                    border
                  >
                    <el-table-column type="index" width="60" label="序号" />
                    <el-table-column prop="fhsj" label="分红时间">
                      <template #default="scope">
                        <el-date-picker
                          v-model="scope.row.fhsj"
                          type="datetime"
                          format="YYYY-MM-DD HH:mm:ss"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column prop="fhje" label="分红金额（万元）">
                      <template #default="scope">
                        <el-input
                          type="number"
                          v-model.number="scope.row.fhje"
                          placeholder="请输入分红金额"
                          step="0.01"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="60">
                      <template #default="scope">
                        <el-button
                          link
                          type="danger"
                          size="small"
                          @click="deleteTzfhs(scope.$index)"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                  <div class="subtotal">
                    <div class="label">流入小计</div>
                    <div class="value">{{ subtotalNum }}（万元）</div>
                  </div>
                </el-collapse-item>

                <el-collapse-item title="净现金流" name="净现金流">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="静态">
                        <el-input
                          type="number"
                          v-model.number="formData.jt"
                          placeholder="请输入静态"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="折现（3.5%）">
                        <el-input
                          type="number"
                          v-model.number="formData.zx"
                          placeholder="请输入折现（3.5%）"
                          step="0.01"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="联系人">
                        <el-input
                          v-model="formData.lxr"
                          placeholder="请输入联系人"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="联系方式">
                        <el-input
                          v-model="formData.lxfs"
                          placeholder="请输入联系方式"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="备注">
                        <el-input
                          type="textarea"
                          v-model="formData.bz"
                          placeholder="请输入备注"
                          :rows="4"
                        />
                      </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, h, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/user.js";

// 初始化全局变量
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const token = ref(
  userStore.authToken || sessionStorage.getItem("authToken") || "",
);

// 小记金额
const subtotalNum = computed(() => {
  let totalHtje = tzfhs.value.reduce((sum, item) => {
    const num = Number(item.fhje) || 0; // 兼容空值/非数字
    return sum + num;
  }, 0);
  let totalYwlr = wtyys.value.reduce((sum, item) => {
    const num = Number(item.ywlr) || 0; // 兼容空值/非数字
    return sum + num;
  }, 0);

  return (totalHtje + totalYwlr).toFixed(2);
});

// 折叠面板默认展开项
const activeCollapse = ref([
  "基本信息",
  "出资情况",
  "合同约定权益获取",
  "分红情况",
  "资金流入",
  "净现金流",
  "资金流出",
  "分红情况",
]);

// 表单数据 - 数值字段初始化为数字类型（0）
const formData = reactive({
  // projectName: "",
  // qc: "",
  // jc: "",
  // nbtzglzt: "",
  // xmscjd: "",
  // gqjg: "",
  // xmzbjze: 0,
  // gszbjyczze: 0,
  // gsdqycze: 0,
  // gsdqyjcze: 0,
  // gsdqycwcje: 0,
  // gsdqsycze: 0,
  // cgbczqk: "",
  // wfqyhttkyd: "",
  // qyhqjz: "",
  // qyhqyyd: "",
  // dbqk: "",
  // lrfp: "",
  // sfddlrfptj: "",
  // ljhqfh: 0,
  // ytrzj: 0,
  // ljtrzj: 0,
  // sxtrzj: 0,
  // jt: 0,
  // zx: 0,
  // lxr: "",
  // lxfs: "",
  // bz: "",
  // projectId: "",
  // del: 0, // del字段保留0默认值（删除标记，0为正常）
});

let options = ref();

function sumWtyysColumns(param) {
  const { columns, data } = param;
  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h("div", "合计");
      return;
    }

    const prop = column.property;

    if (prop === "lx" || prop === "fwsj" || !prop) {
      sums[index] = "";
      return;
    }

    if (prop === "htje") {
      const values = data.map((item) => Number(item.htje) || 0);
      const total = values.reduce((prev, curr) => prev + curr, 0);
      sums[index] = total.toFixed(2) + "（万元）";
      return;
    }

    if (prop === "ywlr") {
      const values = data.map((item) => Number(item.ywlr) || 0);
      const total = values.reduce((prev, curr) => prev + curr, 0);
      sums[index] = total.toFixed(2) + "（万元）";
      return;
    }

    sums[index] = "";
  });

  return sums;
}

function sumTzfhsColumns(param) {
  const { columns, data } = param;
  const sums = [];

  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h("div", "合计");
      return;
    }

    const prop = column.property;

    if (prop === "fhsj" || !prop) {
      sums[index] = "";
      return;
    }

    // 分红金额合计
    if (prop === "fhje") {
      const values = data.map((item) => Number(item.fhje) || 0);
      const total = values.reduce((prev, curr) => prev + curr, 0);
      sums[index] = total.toFixed(2) + "（万元）";
      return;
    }

    sums[index] = "";
  });

  return sums;
}

// 加载状态
const loading = ref(false);
// 是否预览模式
const isPreview = ref(!!route.query.isPreview);
// 项目列表数据
const projectList = ref([]);
// 当前编辑的记录ID
const rcCgqyglId = ref(route.query.id || "");

let wtyys = ref([]);
const addPfyjlsqk = () => {
  // 新增行时数值字段初始化为0
  wtyys.value.push({ htje: 0, ywlr: 0 });
};
const deletePfyjlsqk = (index) => {
  ElMessageBox.confirm("确认删除该项？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    wtyys.value.splice(index, 1);
  });
};

let tzfhs = ref([]);
// 新增
const addTzfhs = () => {
  // 新增行时数值字段初始化为0
  tzfhs.value.push({ fhje: 0 });
};
// 删除
const deleteTzfhs = (index) => {
  ElMessageBox.confirm("确认删除该项？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    tzfhs.value.splice(index, 1);
  });
};

// 获取项目列表
const getProjectData = () => {
  proxy.$post({
    url: "/api/project/listProject",
    data: {
      page: 1,
      pagesize: 1000,
      attributes: [],
      menuType: "xmjc",
    },
    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 getRcCgqyglDetail = () => {
  if (!rcCgqyglId.value) return;

  loading.value = true;
  proxy.$post({
    url: "/api/project/getCgqygl",
    data: { id: rcCgqyglId.value },
    callback: (data) => {
      loading.value = false;
      // 处理数值字段，确保为数字类型
      const formatNumberFields = (obj) => {
        const numberFields = [
          "xmzbjze",
          "gszbjyczze",
          "gsdqycze",
          "gsdqyjcze",
          "gsdqycwcje",
          "gsdqsycze",
          "ljhqfh",
          "ytrzj",
          "ljtrzj",
          "sxtrzj",
          "jt",
          "zx",
        ];
        numberFields.forEach((field) => {
          obj[field] = Number(obj[field]) || 0;
        });
        return obj;
      };

      Object.assign(formData, formatNumberFields(data));

      // 处理wtyys数组的数值字段
      if (data.wtyys) {
        wtyys.value = data.wtyys.map((item) => ({
          ...item,
          htje: Number(item.htje) || 0,
          ywlr: Number(item.ywlr) || 0,
        }));
      }

      // 处理tzfhs数组的数值字段
      if (data.tzfhs) {
        tzfhs.value = data.tzfhs.map((item) => ({
          ...item,
          fhje: Number(item.fhje) || 0,
        }));
      }
    },
  });
};

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

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

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

  // 处理空数字字段：确保所有数值字段为数字类型
  const formatSubmitData = (data) => {
    const numberFields = [
      "xmzbjze",
      "gszbjyczze",
      "gsdqycze",
      "gsdqyjcze",
      "gsdqycwcje",
      "gsdqsycze",
      "ljhqfh",
      "ytrzj",
      "ljtrzj",
      "sxtrzj",
      "jt",
      "zx",
    ];

    numberFields.forEach((field) => {
      data[field] = Number(data[field]) || 0;
    });

    // 处理数组中的数值字段
    data.wtyys = data.wtyys.map((item) => ({
      ...item,
      htje: Number(item.htje) || 0,
      ywlr: Number(item.ywlr) || 0,
    }));

    data.tzfhs = data.tzfhs.map((item) => ({
      ...item,
      fhje: Number(item.fhje) || 0,
    }));

    return data;
  };

  // 组装提交数据
  const submitData = formatSubmitData({
    ...formData,
    projectId: formData.projectId + "",
    wtyys: wtyys.value,
    tzfhs: tzfhs.value,
  });

  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();
  }
});
</script>

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

.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>
