<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-row>
                </el-collapse-item>

                <!-- 投资（成本）分析会资料 -->
                <el-collapse-item
                  title="投资（成本）分析会资料"
                  name="投资（成本）分析会资料"
                >
                  <DynamicTable
                    v-model="yyqtzjcTzfxsList"
                    :columns="tzcbfxhzlColumns"
                    :default-row="tzcbfxhzlDefaultRow"
                    :disabled="isPreview"
                  />
                </el-collapse-item>

                <!-- 专项检查 -->
                <el-collapse-item title="专项检查" name="专项检查">
                  <DynamicTable
                    v-model="yyqtzjcZxjcsList"
                    :columns="zxjcColumns"
                    add-button-text="新增"
                    :default-row="zxjcDefaultRow"
                    :disabled="isPreview"
                    :select-options="{
                      construction_classify:
                        options?.construction_classify || [],
                    }"
                  />
                </el-collapse-item>
              </el-collapse>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, getCurrentInstance } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import DynamicTable from "@/components/FormDynamicTable/index.vue"; // 引入通用组件
// 初始化全局变量
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

// 折叠面板默认展开项
const activeCollapse = ref(["基本信息", "投资（成本）分析会资料", "专项检查"]);
const tzcbfxhzlColumns = ref([
  {
    prop: "jd",
    label: "时间",
    type: "input",
    placeholder: "请按照 xx年xx季度 格式填写",
  },
  {
    prop: "ycztz",
    label: "当期预测总投资",
    type: "input",
    placeholder: "请输入当期预测总投资",
  },
  {
    prop: "zbjnbsyl",
    label: "资本金内部收益率（%）",
    type: "number",
    placeholder: "请输入资本金内部收益率（%）",
  },
  {
    prop: "tzcbfxhzl",
    label: "投资（成本）分析会资料",
    type: "upload",
    placeholder: "",
  },
]);
const tzcbfxhzlDefaultRow = ref({
  jd: "",
  ycztz: "",
  zbjnbsyl: "",
  tzcbfxhzl: [],
});
const zxjcColumns = ref([
  {
    prop: "zxjcfl",
    label: "专项检查类型",
    type: "select",
    optionKey: "construction_classify",
    placeholder: "请选择专项检查类型",
  },
  {
    prop: "jcjg",
    label: "检查结果",
    type: "input",
    placeholder: "请输入检查结果",
  },
  {
    prop: "zgcsqd",
    label: "整改措施清单",
    type: "input",
    placeholder: "请输入整改措施清单",
  },
  {
    prop: "fjcl",
    label: "附件材料",
    type: "upload",
    placeholder: "",
  },
]);

// 专项检查默认行数据
const zxjcDefaultRow = ref({
  zxjcfl: "",
  jcjg: "",
  zgcsqd: "",
  fjcl: [],
});

// 表单数据
const formData = reactive({
  projectName: "",
  projectId: "",
  del: 0, // 删除标记，0为正常
  createdAt: "",
  updatedAt: "",
});

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

// 投资（成本）分析会资料列表
const yyqtzjcTzfxsList = ref([]);
// 专项检查列表
const yyqtzjcZxjcsList = ref([]);

// ========== 投资（成本）分析会资料 操作方法 ==========
const addyyqtzjcTzfxs = () => {
  yyqtzjcTzfxsList.value.push({
    jd: "",
    ycztz: "",
    zbjnbsyl: "",
    yyqtzjcTzfxs: [],
  });
};

const deleteyyqtzjcTzfxs = (index) => {
  ElMessageBox.confirm("确认删除该项？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    yyqtzjcTzfxsList.value.splice(index, 1);
    ElMessage.success("删除成功");
  });
};

// ========== 专项检查 操作方法 ==========
const addyyqtzjcZxjcs = () => {
  yyqtzjcZxjcsList.value.push({
    zxjcfl: "",
    jcjg: "",
    zgcsqd: "",
    fjcl: [],
  });
};

const deleteyyqtzjcZxjcs = (index) => {
  ElMessageBox.confirm("确认删除该项？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    yyqtzjcZxjcsList.value.splice(index, 1);
    ElMessage.success("删除成功");
  });
};

// ========== 通用方法 ==========
// 获取项目列表
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 getJsqtzjcDetail = () => {
  if (!rcCgqyglId.value) return;

  loading.value = true;
  proxy.$post({
    url: "/api/project/getYyqtzjcInfo",
    data: { id: rcCgqyglId.value },
    callback: (data) => {
      loading.value = false;
      // 赋值基础表单数据
      Object.assign(formData, data);
      // 赋值列表数据
      yyqtzjcTzfxsList.value = data.yyqtzjcTzfxs || [];
      yyqtzjcZxjcsList.value = data.yyqtzjcZxjcs || [];
    },
  });
};

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

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

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

  // 组装提交数据
  const submitData = {
    ...formData,
    projectId: formData.projectId + "", // 确保为字符串类型
    yyqtzjcTzfxs: yyqtzjcTzfxsList.value,
    yyqtzjcZxjcs: yyqtzjcZxjcsList.value,
  };

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

// 页面初始化
onMounted(() => {
  // 获取项目列表
  getProjectData();
  options.value = JSON.parse(sessionStorage.getItem("resourceData"));

  // 如果有ID则加载详情
  if (rcCgqyglId.value) {
    getJsqtzjcDetail();
  }
});
</script>

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