<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"
              label-width="160px"
              :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"
                          :disabled="projectDisabled"
                          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"
                  />
                </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, ElMessageBox } from "element-plus";
import DynamicTable from "@/components/FormDynamicTable/index.vue"; // 引入通用组件
import routerBack from "@/components/common/routerBack.vue";
import { useProjectDetail } from "@/composables/useProjectDetail";
// 初始化全局变量
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: "wfzbjnbsyl",
    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: "jcmc",
    label: "检查名称",
    type: "input",
    placeholder: "请输入请输入检查名称",
  },
  {
    prop: "jcsj",
    label: "检查时间",
    type: "date",
    placeholder: "请输入请输入检查时间",
  },
  {
    prop: "jcjg",
    label: "检查揭示的主要问题或结论",
    type: "input",
    placeholder: "请输入请输入检查揭示的主要问题或结论",
  },

  {
    prop: "zgcsqd",
    label: "整改措施清单",
    type: "upload",
    placeholder: "",
  },
  {
    prop: "jcbg",
    label: "检查报告",
    type: "upload",
    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 { projectDisabled, cachedInfo } = useProjectDetail();
// 是否预览模式
const isPreview = ref(!!route.query.isPreview);
// 项目列表数据
const projectList = ref([]);
// 当前编辑的记录ID
const rcCgqyglId = ref(route.query.id || "");

// 投资（成本）分析会资料列表
const yyqtzjcTzfxsList = ref([]);
// 专项检查列表
const yyqtzjcZxjcsList = 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/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("保存成功");
    },
  });
};
let options = ref();

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

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

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