<template>
  <div class="full-container-p24">
    <div class="mb30 df aic jcsb">
      <div class="df aic">
        <el-input
          v-model="searchKey"
          placeholder="请输入培训公告标题"
          class="w300"
          @keyup.enter="handleSearch"
          clearable
          @clear="handleSearch"
        />
        <el-button class="ml10" type="primary" @click="handleSearch">
          搜索
        </el-button>
      </div>
      <div>
        <el-button class="ml10" type="primary" @click="goToSchoolInfo">
          学校信息
        </el-button>
        <el-button class="ml10" type="primary" @click="handleAdd">
          新增培训公告
        </el-button>
      </div>
    </div>

    <el-table border :data="tableData" stripe>
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column
        prop="trainingNoticeTitle"
        label="公告标题"
        min-width="200"
        align="center"
      />
      <el-table-column
        prop="trainingNoticeContent"
        label="公告内容"
        min-width="300"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="createTime"
        label="发布日期"
        min-width="150"
        align="center"
      >
        <template v-slot="scope">
          {{ subTimeStr(scope.row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="primary" text @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button type="danger" text @click="deleteNotice(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="df aic jcfe mt40 mr20">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :total="total"
        @current-change="pageChange"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="公告标题" prop="trainingNoticeTitle">
          <el-input v-model="formData.trainingNoticeTitle" class="w400" />
        </el-form-item>
        <el-form-item label="公告内容" prop="trainingNoticeContent">
          <el-input
            v-model="formData.trainingNoticeContent"
            type="textarea"
            :rows="6"
            class="w400"
          />
        </el-form-item>
        <el-form-item label="公告图片" prop="trainingNoticeImgFileKey">
          <Uploader
            v-model="formData.trainingNoticeImgFileKey"
            :limit="1"
            :action-url="store.state.uploadUrl"
            :fileList="fileList"
            @onUploadFileList="handleFileListUpdate"
            @onRemoveFileList="handleFileListRemove"
          />
        </el-form-item>
        <el-form-item label="发布人" prop="postedBy">
          <el-input
            v-model="formData.postedBy"
            class="w400"
            placeholder="默认：汇很多"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import api from "../../apis/fetch";
import { subTimeStr } from "../../utils/utils";
import Uploader from "../../components/Uploader.vue";
import store from "../../store";

const router = useRouter();

const searchKey = ref("");
const currentPage = ref(1);
const total = ref(0);
const tableData = ref([]);
const fileList = ref([]);

const dialogVisible = ref(false);
const dialogTitle = ref("新增培训公告");
const formRef = ref(null);
const formData = reactive({
  trainingNoticeId: "",
  crewSchoolId: "",
  trainingNoticeTitle: "",
  trainingNoticeContent: "",
  trainingNoticeImgFileKey: "",
  postedBy: "汇很多",
});

const rules = reactive({
  trainingNoticeTitle: [
    { required: true, message: "请输入公告标题", trigger: "blur" },
  ],
  trainingNoticeContent: [
    { required: true, message: "请输入公告内容", trigger: "blur" },
  ],
  postedBy: [{ required: true, message: "请输入发布人", trigger: "blur" }],
});

// 获取培训公告列表
async function getNoticeList() {
  try {
    const { data } = await api.getCrewSchoolTrainingNoticeList({
      term: searchKey.value,
      currentPage: currentPage.value,
      size: 10,
      crewSchoolId: 1,
    });
    if (data.status === 0) {
      tableData.value = data.result;
      total.value = data.total;
    } else {
      tableData.value = [];
      total.value = 0;
      ElMessage.error(data.msg);
    }
  } catch (error) {
    ElMessage.error("获取数据失败");
  }
}

// 处理文件列表更新
const handleFileListUpdate = ({ response: data }) => {
  if (data.status === 0) {
    formData.trainingNoticeImgFileKey = data.result.key;
    fileList.value = [
      { viewUrl: data.result.viewUrl, fileKey: data.result.key },
    ];
    ElMessage.success("上传成功");
  } else {
    ElMessage.error(data.msg || "上传失败");
  }
};

// 处理文件列表移除
const handleFileListRemove = () => {
  formData.trainingNoticeImgFileKey = "";
  fileList.value = [];
};

// 跳转到学校信息页面
function goToSchoolInfo() {
  router.push("/workStation/crewSchoolInfoManage");
}

// 分页切换
function pageChange(page) {
  currentPage.value = page;
  getNoticeList();
}

// 搜索
function handleSearch() {
  currentPage.value = 1;
  getNoticeList();
}

// 新增
function handleAdd() {
  dialogTitle.value = "新增培训公告";
  Object.keys(formData).forEach((key) => {
    if (key !== "postedBy") {
      formData[key] = "";
    }
    if (key === "crewSchoolId") {
      formData[key] = 1;
    }
  });
  formData.postedBy = "汇很多";
  fileList.value = [];
  dialogVisible.value = true;
}

// 编辑
function handleEdit(row) {
  dialogTitle.value = "修改培训公告";
  formData.trainingNoticeId = row.id;
  formData.trainingNoticeTitle = row.trainingNoticeTitle;
  formData.trainingNoticeContent = row.trainingNoticeContent;
  formData.trainingNoticeImgFileKey = row.trainingNoticeImgFileKey || "";
  formData.postedBy = row.postedBy || "汇很多";

  // 设置文件列表
  fileList.value = [];
  if (row.trainingNoticeImgFileKey) {
    fileList.value = [
      {
        viewUrl:
          row.trainingNoticeImgUrl ||
          `/api/file/view?fileKey=${row.trainingNoticeImgFileKey}`,
        fileKey: row.trainingNoticeImgFileKey,
      },
    ];
  }

  dialogVisible.value = true;
}

// 提交表单
async function submitForm() {
  try {
    await formRef.value.validate();
    const apiMethod = !formData.trainingNoticeId
      ? api.addCrewSchoolTrainingNotice
      : api.updateCrewSchoolTrainingNotice;

    const { data } = await apiMethod(formData);
    if (data.status === 0) {
      ElMessage.success("操作成功");
      dialogVisible.value = false;
      getNoticeList();
    } else {
      ElMessage.error(data.msg || "操作失败");
    }
  } catch (error) {
    console.error(error);
  }
}

// 删除
function deleteNotice(row) {
  ElMessageBox.confirm("确认删除该培训公告？", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const { data } = await api.deleteCrewSchoolTrainingNotice({
        trainingNoticeId: row.id,
      });
      if (data.status === 0) {
        ElMessage.success("删除成功");
        getNoticeList();
      } else {
        ElMessage.error(data.msg || "删除失败");
      }
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
}

onMounted(() => {
  getNoticeList();
});
</script>

<style scoped>
.w300 {
  width: 300px;
}
.w400 {
  width: 400px;
}
.ml10 {
  margin-left: 10px;
}
</style>
