<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="问题整改">
                  <DynamicTable
                    v-model="formData.tzhpjwtzgs"
                    :columns="problemColumns"
                    :default-row="problemDefaultRow"
                    :select-options="selectOptions"
                    :show-import-export="true"
                    export-name="问题整改数据"
                    :scrollbar-always-on="true"
                    :disabled="isPreview"
                  />
                </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";
// 引入增强后的DynamicTable组件
import DynamicTable from "../../components/FormDynamicTable/index.vue";

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

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

// ========== 问题整改表格配置 ==========
// 列配置（包含input、textarea、datetime、radio类型）
const problemColumns = ref([
  {
    prop: "ccwt",
    label: "存在的问题",
    type: "input",
    placeholder: "请输入存在的问题",
    minWidth: 140,
  },
  {
    prop: "wtxs",
    label: "问题详述",
    type: "textarea",
    placeholder: "请输入问题详述",
    rows: 2,
    minWidth: 140,
  },
  {
    prop: "zgcs",
    label: "整改措施",
    type: "textarea",
    placeholder: "请输入整改措施",
    rows: 2,
    minWidth: 140,
  },
  {
    prop: "lsqk",
    label: "落实情况",
    type: "textarea",
    placeholder: "请输入落实情况",
    rows: 2,
    minWidth: 140,
  },
  {
    prop: "zrbm",
    label: "责任部门",
    type: "input",
    placeholder: "请输入责任部门",
    minWidth: 140,
  },
  {
    prop: "zrr",
    label: "责任人",
    type: "input",
    placeholder: "请输入责任人",
    minWidth: 140,
  },
  {
    prop: "zgqx",
    label: "整改期限",
    type: "datetime", // 日期时间选择器
    placeholder: "请选择整改期限",
    format: "YYYY-MM-DD HH:mm:ss",
    valueFormat: "YYYY-MM-DD HH:mm:ss",
    minWidth: 140,
  },
  {
    prop: "sfgb",
    label: "是否关闭",
    type: "radio", // 单选框组
    optionKey: "sf", // 对应selectOptions中的sf选项
    align: "center",
    minWidth: 140,
  },
]);

// 问题整改默认行数据
const problemDefaultRow = ref({
  ccwt: "",
  wtxs: "",
  zgcs: "",
  lsqk: "",
  zrbm: "",
  zrr: "",
  zgqx: "",
  sfgb: "",
  fjcl: [],
});

// 单选框选项配置
const selectOptions = ref({
  sf: [
    { key: 1, name: "是" },
    { key: 2, name: "否" },
  ],
});

// ========== 表单数据 ==========
const formData = reactive({
  xmgszcbg: [],
  hpjbg: [],
  qsmzqpj: [],
  // 问题整改列表（由DynamicTable自动维护）
  tzhpjwtzgs: [],
});

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

// ========== 原有方法保留（移除手动新增/删除） ==========
// 获取项目列表
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 || [];

      // 同步单选选项（如果从接口获取）
      if (data.sfOptions) {
        selectOptions.value.sf = data.sfOptions;
      }
    },
  });
};

// 返回上一页
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 + "",
    tzhpjwtzgs: formData.tzhpjwtzgs,
  };

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

let options = ref();

// 页面初始化
onMounted(() => {
  getProjectData();
  try {
    options.value = JSON.parse(sessionStorage.getItem("resourceData")) || {};
    // 合并全局选项到selectOptions
    if (options.value.sf) {
      selectOptions.value.sf = options.value.sf;
    }
  } catch (e) {
    options.value = {};
  }

  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>
