<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>
      <el-button class="ml10" type="primary" @click="handleAdd">
        新增通知
      </el-button>
    </div>

    <el-table border :data="tableData" stripe>
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column
        prop="noticeTitle"
        label="通知主题"
        min-width="180"
        align="center"
      />
      <el-table-column
        prop="noticeContent"
        label="通知内容"
        min-width="250"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="contactName"
        label="联系人姓名"
        min-width="120"
        align="center"
      />
      <el-table-column
        prop="contactPhone"
        label="联系人手机号"
        min-width="150"
        align="center"
      />
      <el-table-column
        prop="postedBy"
        label="发布人"
        min-width="120"
        align="center"
      />
      <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="noticeTitle">
          <el-input v-model="formData.noticeTitle" class="w400" />
        </el-form-item>
        <el-form-item label="通知内容" prop="noticeContent">
          <el-input
            v-model="formData.noticeContent"
            type="textarea"
            :rows="6"
            class="w400"
          />
        </el-form-item>
        <el-form-item label="通知图片" prop="noticeImgFileKey">
          <Uploader
            v-model="formData.noticeImgFileKey"
            :limit="1"
            :action-url="store.state.uploadUrl"
            :fileList="fileList"
            @onUploadFileList="handleFileListUpdate"
            @onRemoveFileList="handleFileListRemove"
          />
        </el-form-item>
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="formData.contactName" class="w400" />
        </el-form-item>
        <el-form-item label="联系人手机号" prop="contactPhone">
          <el-input v-model="formData.contactPhone" class="w400" />
        </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 api from "../../apis/fetch";
import { subTimeStr } from "../../utils/utils";
import Uploader from "../../components/Uploader.vue";
import store from "../../store";

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 = ref({
  noticeId: "",
  noticeTitle: "",
  noticeImgFileKey: "",
  noticeContent: "",
  contactName: "",
  contactPhone: "",
  postedBy: "汇很多",
});

const rules = reactive({
  noticeTitle: [{ required: true, message: "请输入通知主题", trigger: "blur" }],
  noticeContent: [
    { required: true, message: "请输入通知内容", trigger: "blur" },
  ],
  contactName: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: "请输入联系人手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
});

onMounted(() => {
  getNoticeList();
});

// 获取通知列表
async function getNoticeList() {
  try {
    const { data } = await api.getAnnualInspectionNoticeList({
      term: searchKey.value,
      currentPage: currentPage.value,
      size: 10,
    });
    if (data.status === 0) {
      tableData.value = data.result;
      total.value = data.total;
    }
  } catch (error) {
    ElMessage.error("获取数据失败");
  }
}

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

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

const handleFileListRemove = () => {
  formData.value.noticeImgFileKey = "";
  fileList.value = [];
};
const handleFileListUpdate = ({ response: data }) => {
  if (data.status === 0) {
    formData.value.noticeImgFileKey = data.result.key;
    fileList.value = [
      { viewUrl: data.result.viewUrl, fileKey: data.result.key },
    ];
    ElMessage.success("上传成功");
  } else {
    ElMessage.error(data.msg || "上传失败");
  }
};

// 新增
function handleAdd() {
  dialogTitle.value = "新增通知";
  formData.value = {
    // 直接重新赋值整个对象
    noticeId: "",
    noticeTitle: "",
    noticeImgFileKey: "",
    noticeContent: "",
    contactName: "",
    contactPhone: "",
    postedBy: "汇很多",
  };
  fileList.value = [];
  dialogVisible.value = true;
}

// 编辑
function handleEdit(row) {
  dialogTitle.value = "修改通知";
  formData.value.noticeId = row.id;
  formData.value.noticeTitle = row.noticeTitle;
  formData.value.noticeContent = row.noticeContent;
  formData.value.noticeImgFileKey = row.noticeImgFileKey || "";
  formData.value.contactName = row.contactName;
  formData.value.contactPhone = row.contactPhone;
  formData.value.postedBy = row.postedBy || "汇很多";

  // 设置文件列表
  if (row.noticeImgFileKey) {
    fileList.value = [
      {
        noticeImgFileKey: row.noticeImgFileKey,
        viewUrl: row.noticeImgUrl,
        fileKey: row.noticeImgFileKey,
      },
    ];
  }

  dialogVisible.value = true;
}

// 删除通知
async function deleteNotice(row) {
  try {
    await ElMessageBox.confirm("确定要删除该通知吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const { data } = await api.deleteAnnualInspectionNotice({
      noticeId: row.id,
    });

    if (data.status === 0) {
      ElMessage.success("删除成功");
      getNoticeList();
    } else {
      ElMessage.error(data.message || "删除失败");
    }
  } catch (error) {
    console.error(error);
  }
}

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

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

<style scoped>
.w300 {
  width: 300px;
}

.w400 {
  width: 400px;
}
</style>
