<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="120" :disabled="isPreview">
              <el-collapse v-model="activeCollapse">
                <el-collapse-item title="基本信息" name="基本信息">
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <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-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-row :gutter="20">
                    <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.id"
                            :label="item.name"
                            :value="item.id"
                          ></el-option>
                        </el-select>
                      </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.number="formData.xmzbjze"
                          placeholder="请输入项目资本金总额（亿元）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="公司资本金应出资总额（亿元）">
                        <el-input
                          v-model.number="formData.gszbjyczze"
                          placeholder="请输入公司资本金应出资总额（亿元）"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="公司当前应出资额（亿元）">
                        <el-input
                          v-model.number="formData.gsdqycze"
                          placeholder="请输入公司当前应出资额（亿元）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="公司当前已出资额（亿元）">
                        <el-input
                          v-model.number="formData.gsdqyjcze"
                          placeholder="请输入公司当前已出资额（亿元）"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="公司当前应出未出金额（亿元）">
                        <el-input
                          v-model.number="formData.gsdqycwcje"
                          placeholder="请输入公司当前应出未出金额（亿元）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="公司当前剩余出资额（亿元）">
                        <el-input
                          v-model.number="formData.gsdqsycze"
                          placeholder="请输入公司当前剩余出资额（亿元）"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item 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="12">
                      <el-form-item label="权益获取进展">
                        <el-input
                          type="textarea"
                          v-model="formData.qyhqjz"
                          placeholder="请输入权益获取进展"
                          :rows="3"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <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="12">
                      <el-form-item label="督办情况">
                        <el-input
                          type="textarea"
                          v-model="formData.dbqk"
                          placeholder="请输入督办情况"
                          :rows="2"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="利润分配/分红约定">
                        <el-input
                          type="textarea"
                          v-model="formData.lrfp"
                          placeholder="请输入利润分配/分红约定"
                          :rows="2"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <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.id"
                            >{{ item.name }}</el-radio
                          >
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="累计获取分红（万元）">
                        <el-input
                          v-model.number="formData.ljhqfh"
                          placeholder="请输入累计获取分红（万元）"
                        />
                      </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
                          v-model.number="scope.row.htje"
                          placeholder="请输入合同金额"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column prop="ywlr" label="业务利润">
                      <template #default="scope">
                        <el-input
                          v-model.number="scope.row.ywlr"
                          placeholder="请输入业务利润"
                        />
                      </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>
                </el-collapse-item>
                <el-collapse-item title="资金流出" name="资金流出">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="应投入资金（万元）">
                        <el-input
                          v-model.number="formData.ytrzj"
                          placeholder="请输入应投入资金（万元）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="累计投入资金（万元）">
                        <el-input
                          v-model.number="formData.ljtrzj"
                          placeholder="请输入累计投入资金（万元）"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="尚需投入资金（万元）">
                        <el-input
                          v-model.number="formData.sxtrzj"
                          placeholder="请输入尚需投入资金（万元）"
                        />
                      </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                      <el-form-item label="业务利润+分红小计（万元）">
                        <el-input
                          v-model.number="formData.lrxj"
                          placeholder="请输入业务利润+分红小计（万元）"
                        />
                      </el-form-item>
                    </el-col> -->
                  </el-row>
                </el-collapse-item>
                <el-collapse-item title="分红情况" name="分红情况">
                  <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
                          v-model.number="scope.row.fhje"
                          placeholder="请输入分红金额"
                        />
                      </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>
                </el-collapse-item>

                <el-collapse-item title="其他信息" name="其他信息">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="静态">
                        <el-input
                          v-model.number="formData.jt"
                          placeholder="请输入静态"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="折现（3.5%）">
                        <el-input
                          v-model.number="formData.zx"
                          placeholder="请输入折现（3.5%）"
                        />
                      </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 } 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 activeCollapse = ref([
  "基本信息",
  "资本金出资情况",
  "权益与分红情况",
  "资金流入",
  "其他信息",
  "资金流出",
  "分红情况",
]);

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

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(8);
      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(8);
      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(8);
      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 = () => {
  wtyys.value.push({});
};
const deletePfyjlsqk = (index) => {
  ElMessageBox.confirm("确认删除该项？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    wtyys.value.splice(index, 1);
  });
};

let tzfhs = ref([]);
// 新增
const addTzfhs = () => {
  tzfhs.value.push({});
};
// 删除
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 || [];
    },
    errorCallback: () => {
      ElMessage.error("获取项目列表失败");
    },
  });
};

// 选择项目后同步项目名称
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;
      Object.assign(formData, {
        ...data,
        sfddlrfptj: Number(data.sfddlrfptj),
        xmscjd: Number(data.xmscjd),
      });
      if (data.wtyys) {
        Object.assign(wtyys.value, data.wtyys);
      }
      // 新增：加载
      if (data.tzfhs) {
        Object.assign(tzfhs.value, data.tzfhs);
      }
    },
    errorCallback: () => {
      loading.value = false;
      ElMessage.error("网络异常，获取数据失败");
    },
  });
};

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";

  // 处理空数字字段：空值转为null，避免提交空字符串
  const submitData = {
    ...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 lang="less">
@import "@/styles/manage.less";
.add-project-header {
  margin-bottom: 10px;
}
.el-form-item__label {
  line-height: 1.5;
}
.tab-handle {
  margin-bottom: 10px;
  text-align: right;
}
.always-click {
  cursor: pointer;
  color: #409eff;
  margin-right: 10px;
}
.el-table .el-table__footer-wrapper {
  .el-table-cell {
    font-weight: bold;
    background-color: #f5f7fa;
  }
}
</style>
