<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" :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
                    :showAddButton="false"
                    v-model="zbyzyj"
                    :show-delete-button="false"
                    :columns="transferColumns"
                    :default-row="transferDefaultRow"
                    :disabled="isPreview"
                  />
                </el-collapse-item>

                <!-- 期中履约终止移交 -->
                <el-collapse-item
                  title="期中履约终止移交"
                  name="期中履约终止移交"
                >
                  <DynamicTable
                    :showAddButton="false"
                    v-model="qzlyzzyj"
                    :show-delete-button="false"
                    :columns="transferColumns"
                    :default-row="transferDefaultRow"
                    :disabled="isPreview"
                  />
                </el-collapse-item>

                <!-- 期满移交 -->
                <el-collapse-item title="期满移交" name="期满移交">
                  <DynamicTable
                    :showAddButton="false"
                    v-model="qmyj"
                    :show-delete-button="false"
                    :columns="transferColumns"
                    :default-row="transferDefaultRow"
                    :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 } 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 transferColumns = ref([
  { prop: "mc", label: "名称", type: "input", placeholder: "请填写文件名称" },
  { prop: "fj", label: "附件", type: "upload", placeholder: "" },
  {
    prop: "bz",
    label: "备注",
    type: "textarea",
    rows: 2,
    placeholder: "请输入备注信息",
  },
]);

// 移交类默认行数据
const transferDefaultRow = ref({ mc: "", fj: [], bz: "" });

// 表单核心数据
const formData = reactive({
  projectName: "",
  projectId: "",
  del: 0,
  createdAt: "",
  updatedAt: "",
});

// 状态管理
const loading = ref(false);
const { projectDisabled, cachedInfo } = useProjectDetail();
const isPreview = ref(!!route.query.isPreview);
const projectList = ref([]);
const rcCgqyglId = ref(route.query.id || "");
let options = ref();

// 初始化移交列表数据
const zbyzyj = ref([
  { mc: "股权转让协议", fj: [], bz: "" },
  { mc: "移交工作方案", fj: [], bz: "" },
  { mc: "资产移交清单", fj: [], bz: "" },
  { mc: "运营交接验收报告", fj: [], bz: "" },
]);

const qzlyzzyj = ref([
  { mc: "终止协议", fj: [], bz: "" },
  { mc: "移交工作方案", fj: [], bz: "" },
  { mc: "资产移交清单", fj: [], bz: "" },
  { mc: "运营交接验收报告", fj: [], bz: "" },
]);

const qmyj = ref([
  { mc: "移交工作方案", fj: [], bz: "" },
  { mc: "资产移交清单", fj: [], bz: "" },
  { mc: "运营交接验收报告", fj: [], bz: "" },
]);

// 可新增的期中履约终止移交列表
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/getYjglInfo",
    data: { id: rcCgqyglId.value },
    callback: (data) => {
      loading.value = false;
      Object.assign(formData, data);
      zbyzyj.value = data.zbyzyj || zbyzyj.value;
      qzlyzzyj.value = data.qzlyzzyj || qzlyzzyj.value;
      qmyj.value = data.qmyj || qmyj.value;
      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/updateYjgl"
    : "/api/project/createYjgl";
  const submitData = {
    ...formData,
    projectId: formData.projectId + "",
    zbyzyj: zbyzyj.value,
    qzlyzzyj: qzlyzzyj.value,
    qmyj: qmyj.value,
    yyqtzjcZxjcs: yyqtzjcZxjcsList.value,
  };

  proxy.$post({
    url: url,
    data: submitData,
    callback: () => {
      loading.value = false;
      ElMessage.success("保存成功");
    },
  });
};

// 页面初始化
onMounted(() => {
  getProjectData();
  if (cachedInfo) {
    formData.projectName = cachedInfo.projectName || "";
    formData.projectId = cachedInfo.projectId || "";
  }
  options.value = JSON.parse(sessionStorage.getItem("resourceData"));
  if (rcCgqyglId.value) getJsqtzjcDetail();
});
</script>

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