<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-width="0" 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="项目公司自查报告"
                >
                  <el-form-item label-width="0" label="">
                    <FileUploader v-model="formData.xmgszcbg" />
                  </el-form-item>
                </el-collapse-item>
                <el-collapse-item title="投资后评价报告" name="投资后评价报告">
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label-width="0" label="">
                        <FileUploader v-model="formData.hpjbg" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="评价时间">
                        <el-date-picker
                          v-model="formData.hpjsj"
                          type="datetime"
                          format="YYYY-MM-DD HH:mm:ss"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择评价时间"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="报告编制单位">
                        <el-input
                          v-model="formData.hpjbgbzdw"
                          placeholder="请输入报告编制单位"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="评审单位">
                        <el-input
                          v-model="formData.hpjpsdw"
                          placeholder="请输入评审单位"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="评价结果">
                        <el-input
                          v-model="formData.hpjpjjg"
                          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="addJsqtzjcZxjcs"
                      >新增</el-button
                    >
                  </div>

                  <el-table
                    :data="formData.tzhpjwtzgs"
                    style="width: 100%"
                    empty-text="暂无数据"
                    :scrollbar-always-on="true"
                    border
                  >
                    <el-table-column
                      type="index"
                      width="60"
                      fixed="left"
                      label="序号"
                    />
                    <el-table-column
                      prop="zxjcfl"
                      min-width="140"
                      label="存在的问题"
                    >
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.ccwt"
                          placeholder="请输入存在的问题"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column min-width="140" label="问题详述">
                      <template #default="scope">
                        <el-input
                          type="textarea"
                          v-model="scope.row.wtxs"
                          placeholder="请输入问题详述"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column min-width="140" label="整改措施">
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.zgcs"
                          type="textarea"
                          placeholder="请输入整改措施"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column min-width="140" label="落实情况">
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.lsqk"
                          type="textarea"
                          placeholder="请输入落实情况"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column min-width="140" label="责任部门">
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.zrbm"
                          placeholder="请输入责任部门"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column min-width="140" label="责任人">
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.zrr"
                          placeholder="请输入责任人"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column min-width="140" label="整改期限">
                      <template #default="scope">
                        <el-date-picker
                          v-model="scope.row.zgqx"
                          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
                      min-width="140"
                      align="center"
                      label="是否关闭"
                    >
                      <template #default="scope">
                        <el-radio-group
                          placeholder="请选择是否关闭"
                          v-model="scope.row.sfgb"
                        >
                          <el-radio
                            v-for="item in options?.sf"
                            :key="item.id"
                            :id="item.name"
                            :value="item.key"
                            >{{ item.name }}</el-radio
                          >
                        </el-radio-group>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="60" fixed="right">
                      <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-item
                  title="全生命周期评价报告"
                  name="全生命周期评价报告"
                >
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label-width="0" label="">
                        <FileUploader v-model="formData.qsmzqpj" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="评价时间">
                        <el-date-picker
                          v-model="formData.qsmsj"
                          type="datetime"
                          format="YYYY-MM-DD HH:mm:ss"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择评价时间"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="报告编制单位">
                        <el-input
                          v-model="formData.qsmbgbzdw"
                          placeholder="请输入报告编制单位"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="评审单位">
                        <el-input
                          v-model="formData.qsmpsdw"
                          placeholder="请输入评审单位"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="评价结果">
                        <el-input
                          v-model="formData.qsmpjjg"
                          placeholder="请输入评价结果"
                        />
                      </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 } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import FileUploader from "../../components/FileUploader/index.vue";

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

// 折叠面板默认展开项
const activeCollapse = ref([
  "项目信息",
  "项目公司自查报告",
  "投资后评价报告",
  "问题整改",
  "全生命周期评价报告",
]);

// 表单数据 - 补全所有字段结构
const formData = reactive({
  xmgszcbg: [],
  hpjbg: [],

  qsmzqpj: [],

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

// ========== 问题整改 操作方法 ==========
const addJsqtzjcZxjcs = () => {
  // 新增时添加正确的字段结构
  formData.tzhpjwtzgs.push({
    ccwt: "",
    wtxs: "",
    zgcs: "",
    lsqk: "",
    zrbm: "",
    zrr: "",
    zgqx: "",
    sfgb: "",
    fjcl: [],
  });
};

const deleteJsqtzjcZxjcs = (index) => {
  ElMessageBox.confirm("确认删除该项？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    formData.tzhpjwtzgs.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/getTzhpjInfo",
    data: { id: rcCgqyglId.value },
    callback: (data) => {
      loading.value = false;
      // 赋值基础表单数据
      Object.assign(formData, data);
      // 确保数组字段有默认值，避免空指针
      formData.tzhpjwtzgs = data.tzhpjwtzgs || [];
      formData.xmgszcbg = data.xmgszcbg || [];
      formData.hpjbg = data.hpjbg || [];
      formData.qsmzqpj = data.qsmzqpj || [];
    },
  });
};

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

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

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

  // 组装提交数据 - 包含所有字段
  const submitData = {
    ...formData,
    projectId: formData.projectId + "", // 确保为字符串类型
    // 问题整改列表直接从formData获取
    tzhpjwtzgs: formData.tzhpjwtzgs,
  };

  proxy.$post({
    url: url,
    data: submitData,
    callback: () => {
      loading.value = false;
      ElMessage.success(rcCgqyglId.value ? "编辑成功" : "新增成功");
      router.back(-1);
    },
    // 添加错误处理
    error: () => {
      loading.value = false;
      ElMessage.error("操作失败，请稍后重试");
    },
  });
};

let options = ref();

// 页面初始化
onMounted(() => {
  // 获取项目列表
  getProjectData();
  // 处理options数据，避免空指针
  try {
    options.value = JSON.parse(sessionStorage.getItem("resourceData")) || {};
  } catch (e) {
    options.value = {};
    console.warn("解析resourceData失败:", e);
  }

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

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

.add-project-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.add-project-content {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.add-project-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.tab-handle {
  margin-bottom: 10px;
  text-align: left;
}

:deep(.el-table) {
  --el-table-header-text-color: #303133;
  --el-table-row-hover-bg-color: #f8f9fa;
}

:deep(.el-collapse-item__header) {
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
