<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-row :gutter="20">
                <!-- 会议编号（必填、唯一） -->
                <el-col :span="12">
                  <el-form-item label="会议编号">
                    <el-input
                      v-model="formData.meetingCode"
                      placeholder="请输入会议编号（如：TWH202601）"
                    />
                  </el-form-item>
                </el-col>
                <!-- 会议名称（必填） -->
                <el-col :span="12">
                  <el-form-item label="会议名称">
                    <el-input
                      v-model="formData.meetingName"
                      placeholder="请输入会议名称"
                    />
                  </el-form-item>
                </el-col>
                <!-- 会议时间（必填） -->
                <el-col :span="12">
                  <el-form-item label="会议时间">
                    <el-date-picker
                      v-model="formData.meetingDate"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      placeholder="请选择会议时间"
                      picker-options="{ disabledDate: (date) => date > new Date() }"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <!-- 会议地点 -->
                <el-col :span="12">
                  <el-form-item label="会议地点">
                    <el-input
                      v-model="formData.meetingLocation"
                      placeholder="请输入会议地点"
                    />
                  </el-form-item>
                </el-col>

                <!-- 参会领导 -->
                <el-col :span="12">
                  <el-form-item label="参会领导">
                    <el-input
                      v-model="formData.attendingLeaders"
                      placeholder="请输入参会领导"
                    />
                  </el-form-item>
                </el-col>
                <!-- 参会部门 -->
                <el-col :span="12">
                  <el-form-item label="参会部门">
                    <el-input
                      v-model="formData.attendingDepartments"
                      placeholder="请输入参会部门"
                    />
                  </el-form-item>
                </el-col>
                <!-- 会议纪要附件（无需额外处理，组件直接绑定） -->
                <el-col :span="24">
                  <el-form-item label="会议纪要附件" label-width="200">
                    <FileUploader v-model="formData.meetingMinutesAttachment" />
                  </el-form-item>
                </el-col>
              </el-row>
            </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 } from "element-plus";
import FileUploader from "../../components/FileUploader/index.vue";

// 路由&全局实例
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

// ========== 核心状态 ==========
const loading = ref(false); // 加载状态
const isPreview = ref(!!route.query.isPreview); // 是否预览模式
const rcTwhglId = ref(route.query.id || ""); // 投委会管理记录ID（匹配表名）

// 会议层级固定选项（匹配表注释：company-公司级,department-部门级,project-项目级）
const meetingLevelOptions = ref([
  { key: "company", label: "公司级" },
  { key: "department", label: "部门级" },
  { key: "project", label: "项目级" },
]);

// ========== 表单核心数据（完全匹配RcTwhgl表结构） ==========
const formData = reactive({
  meetingCode: "", // 会议编号（唯一、必填）
  meetingName: "", // 会议名称（必填）
  meetingDate: "", // 会议时间（必填）
  meetingLocation: "", // 会议地点
  attendingLeaders: "", // 参会领导
  attendingDepartments: "", // 参会部门
  meetingMinutesAttachment: [], // 会议纪要附件（JSON数组，组件直接绑定）
  projectId: "", // 所属项目ID
  creator: proxy.$store?.getters?.userId || "", // 创建人ID（从全局状态取，可调整）
  del: 0, // 删除标识，默认正常
});

// ========== 接口请求 ==========
// 获取投委会管理单条记录详情（编辑/预览时用）
const getRcTwhglDetail = () => {
  loading.value = true;
  proxy.$post({
    url: "/api/project/getTwhgl",
    data: { id: rcTwhglId.value },
    callback: (data) => {
      loading.value = false;
      Object.assign(formData, data);
      // 格式处理&默认值，避免渲染报错
      formData.projectId = Number(data.projectId) || "";
      formData.meetingDate = data.meetingDate || "";
      formData.meetingMinutesAttachment = data.meetingMinutesAttachment || [];
    },
    error: () => (loading.value = false),
  });
};

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

// 保存/提交表单（新增/编辑统一处理）
const saveClick = () => {
  // 核心必填项校验（表中allowNull:false的字段）
  if (!formData.meetingCode) {
    ElMessage.warning("请填写会议编号，编号唯一请勿重复");
    return;
  }
  if (!formData.meetingName) {
    ElMessage.warning("请填写会议名称");
    return;
  }
  if (!formData.meetingDate) {
    ElMessage.warning("请选择会议时间");
    return;
  }

  loading.value = true;
  // 投委会管理专属新增/编辑接口

  const url = rcTwhglId.value
    ? "/api/project/updateTwhgl"
    : "/api/project/createTwhgl";
  proxy.$post({
    url: url,
    data: { ...formData },
    callback: () => {
      loading.value = false;
      ElMessage.success(rcTwhglId.value ? "编辑成功" : "新增成功");
      router.back(-1);
    },
    error: (err) => {
      loading.value = false;
      // 唯一键冲突特殊提示（会议编号重复）
      if (err.msg?.includes("unique") || err.msg?.includes("重复")) {
        ElMessage.error("会议编号已存在，请更换唯一编号后重试");
      }
    },
  });
};

// ========== 页面初始化 ==========
onMounted(() => {
  // 编辑/预览模式，加载投委会管理详情数据
  if (rcTwhglId.value) {
    getRcTwhglDetail();
  }
});
</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;
}

// 表单样式优化
:deep(.el-form-item__label) {
  font-weight: 500;
}
// 输入框提示文字
.input-tip {
  margin-left: 4px;
  color: #f56c6c;
  font-size: 12px;
  line-height: 1.5;
}
// 附件上传区域间距
:deep(.el-upload) {
  margin-bottom: 8px;
}
</style>
