<template>
  <div class="add-project-container">
    <div class="add-project-content" v-loading="loading">
      <routerBack />

      <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"
                          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-input
                          v-model="formData.jcztz"
                          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.zbjnbsyl"
                          placeholder="请输入资本金内部收益率（%） 一次填报锁定"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="预测总投资">
                        <el-input
                          v-model="formData.ycztz"
                          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.qrztz"
                          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="addjsqtzjcTzfxs"
                      >新增</el-button
                    >
                  </div>
                  <el-table
                    :data="jsqtzjcTzfxsList"
                    style="width: 100%"
                    empty-text="暂无数据"
                    border
                  >
                    <el-table-column type="index" width="60" label="序号" />
                    <el-table-column prop="jd" label="时间 ">
                      <template #default="scope">
                        <!-- <el-date-picker
                          v-model="scope.row.jd"
                          type="datetime"
                          format="YYYY-MM-DD HH:mm:ss"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择"
                        /> -->
                        <el-input
                          v-model="scope.row.jd"
                          placeholder="请按照 xx年xx季度 格式填写"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="ycztz"
                      label="当期预测总投资（万元）"
                    >
                      <template #default="scope">
                        <el-input
                          type="number"
                          v-model.number="scope.row.ycztz"
                          placeholder="请输入当期预测总投资（万元）"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="zbjnbsyl"
                      label="项目资本金内部收益率（%）"
                    >
                      <template #default="scope">
                        <el-input
                          v-model.number="scope.row.zbjnbsyl"
                          placeholder="请输入项目资本金内部收益率（%）"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="wfzbjnbsyl"
                      label="我方资本金内部收益率（%）"
                    >
                      <template #default="scope">
                        <el-input
                          v-model.number="scope.row.wfzbjnbsyl"
                          placeholder="请输入我方资本金内部收益率（%）"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="tzcbfxhzl"
                      label="投资（成本）分析会资料"
                    >
                      <template #default="scope">
                        <FileUploader
                          v-model="scope.row.tzcbfxhzl"
                          :isInline="true"
                        ></FileUploader>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="60">
                      <template #default="scope">
                        <el-button
                          link
                          type="danger"
                          size="small"
                          @click="deletejsqtzjcTzfxs(scope.$index)"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </el-collapse-item>

                <!-- 专项检查 -->
                <el-collapse-item title="专项检查" name="专项检查">
                  <div class="tab-handle">
                    <el-button type="primary" @click="addJsqtzjcZxjcs"
                      >新增</el-button
                    >
                  </div>
                  <el-table
                    :data="jsqtzjcZxjcsList"
                    style="width: 100%; overflow-y: scroll"
                    empty-text="暂无数据"
                    border
                  >
                    <el-table-column type="index" width="60" label="序号" />
                    <el-table-column prop="zxjcfl" label="专项检查类型">
                      <template #default="scope">
                        <el-select
                          v-model="scope.row.zxjcfl"
                          placeholder="请选择专项检查类型"
                        >
                          <el-option
                            v-for="item in options?.construction_classify"
                            :key="item.key"
                            :label="item.name"
                            :value="item.key"
                          ></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="jcmc" label="检查名称">
                      <template #default="scope">
                        <el-input
                          v-model.number="scope.row.jcmc"
                          placeholder="请输入检查名称"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column prop="jcsj" label="检查时间">
                      <template #default="scope">
                        <el-date-picker
                          v-model="scope.row.jcsj"
                          type="date"
                          placeholder="请选择检查时间"
                          format="YYYY-MM-DD"
                          value-format="YYYY-MM-DD"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="jcjg"
                      label="检查揭示的主要问题或结论"
                    >
                      <template #default="scope">
                        <el-input
                          v-model.number="scope.row.jcjg"
                          placeholder="请输入检查揭示的主要问题或结论"
                        />
                      </template>
                    </el-table-column>
                    <!-- <el-table-column  prop="zgcsqd" label="整改措施清单">
                      <template #default="scope">
                        <el-input
                          v-model.number="scope.row.zgcsqd"
                          placeholder="请输入整改措施清单"
                        />
                      </template>
                    </el-table-column> -->

                    <el-table-column
                      prop="zgcsqd"
                      min-width="120px"
                      label="整改措施清单"
                    >
                      <template #default="scope">
                        <FileUploader
                          v-model="scope.row.zgcsqd"
                          :isInline="true"
                        ></FileUploader>
                      </template>
                    </el-table-column>

                    <el-table-column
                      min-width="120px"
                      prop="jcbg"
                      label="检查报告"
                    >
                      <template #default="scope">
                        <FileUploader
                          v-model="scope.row.jcbg"
                          :isInline="true"
                        ></FileUploader>
                      </template>
                    </el-table-column>

                    <el-table-column
                      min-width="120px"
                      prop="fjcl"
                      label="附件材料"
                    >
                      <template #default="scope">
                        <FileUploader
                          v-model="scope.row.fjcl"
                          :isInline="true"
                        ></FileUploader>
                      </template>
                    </el-table-column>

                    <el-table-column prop="zgjz" label="整改进展">
                      <template #default="scope">
                        <el-input
                          type="textarea"
                          rows="2"
                          v-model.number="scope.row.zgjz"
                          placeholder="请输入整改进展"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="60">
                      <template #default="scope">
                        <el-button
                          link
                          type="danger"
                          size="small"
                          @click="deleteJsqtzjcZxjcs(scope.$index)"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </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 FileUploader from "../../components/FileUploader/index.vue";
import routerBack from "@/components/common/routerBack.vue";

// 初始化全局变量
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

// 折叠面板默认展开项
const activeCollapse = ref(["基本信息", "投资（成本）分析会资料", "专项检查"]);

// 表单数据
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 jsqtzjcTzfxsList = ref([]);
// 专项检查列表
const jsqtzjcZxjcsList = ref([]);

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

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

// ========== 专项检查 操作方法 ==========
const addJsqtzjcZxjcs = () => {
  jsqtzjcZxjcsList.value.push({
    zxjcfl: null,
    jcjg: null,
    zgcsqd: null,
    jcsj: null,
    jcmc: null,
    zgcsqd: [],
    jcbg: [],
    fjcl: [],
  });
};

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

// ========== 通用方法 ==========
// 获取项目列表
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/getJsqtzjcInfo",
    data: { id: rcCgqyglId.value },
    callback: (data) => {
      loading.value = false;
      // 赋值基础表单数据
      Object.assign(formData, data);
      // 赋值列表数据
      jsqtzjcTzfxsList.value = data.jsqtzjcTzfxs || [];
      jsqtzjcZxjcsList.value = data.jsqtzjcZxjcs || [];
    },
  });
};

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

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

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

  // 组装提交数据
  const submitData = {
    ...formData,
    projectId: formData.projectId + "", // 确保为字符串类型
    jsqtzjcTzfxs: jsqtzjcTzfxsList.value,
    jsqtzjcZxjcs: jsqtzjcZxjcsList.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">
.tab-handle {
  margin-bottom: 10px;
  text-align: left;
}

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

// 支持表格横向滚动
.tab-content {
  overflow-x: auto;
}

.project-tab-content {
  overflow-x: auto;
}
</style>
