<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true">
        <el-form-item label="公告标题" prop="noticeTitle">
          <el-input
            placeholder="请输入公告标题"
            v-model="searchParams.noticeTitle"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleListPage"
          ></el-input>
        </el-form-item>
        <el-form-item label="公告类型" prop="noticeType">
          <el-select
            placeholder="请选择公告类型"
            v-model="searchParams.noticeType"
            style="width: 240px"
            @keyup.enter.native="handleListPage"
            clearable
          >
            <el-option
              v-for="dict in koiDicts.sys_notice_type"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-throttle="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:notice:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:notice:edit']">
          <el-button type="success" icon="edit" plain @click="handleUpdate()" :disabled="single">修改</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:notice:remove']">
          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">删除</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        border
        :data="tableList"
        empty-text="暂时没有数据哟"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" prop="noticeId" width="120px" align="center" type="index"></el-table-column>
        <el-table-column label="公告名称" prop="noticeTitle" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="公告类型" prop="noticeType" width="100px" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="koiDicts.sys_notice_type" :value="scope.row.noticeType"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="公告状态" prop="status" width="100px" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="koiDicts.sys_notice_status" :value="scope.row.status"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="公告备注" prop="remark" width="260px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
        <el-table-column label="修改时间" prop="updateTime" width="180px" align="center"></el-table-column>
        <el-table-column label="修改人" prop="updateBy" width="180px" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="修改" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="handleUpdate(row)"
                v-auth="['system:notice:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
                v-auth="['system:notice:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-20px"></div>
      <!-- 分页 -->
      <Pagination :queryParams="searchParams" :total="total" :getList="handleListPage" />

      <!-- 添加 OR 修改 -->
      <KoiDialog
        ref="koiDialogRef"
        :title="title"
        width="800"
        height="500"
        @koiConfirm="handleConfirm"
        @koiCancel="handleCancel"
        :loading="confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
            <el-row>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="公告名称" prop="noticeTitle">
                  <el-input v-model="form.noticeTitle" placeholder="请输入公告名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="公告类型" prop="noticeType">
                  <el-select placeholder="请选择公告类型" v-model="form.noticeType" clearable>
                    <el-option
                      v-for="item in koiDicts.sys_notice_type"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="公告状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择公告状态" clearable>
                    <el-option label="启用" value="0" />
                    <el-option label="停用" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="公告内容" prop="noticeContent">
                  <Editor v-model="form.noticeContent" :min-height="192"/>
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 24 }" :xs="{ span: 24 }">
                <el-form-item label="公告备注" prop="remark">
                  <el-input v-model="form.remark" :rows="5" type="text" placeholder="请输入公告备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDialog>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="noticePage">
import { nextTick, ref, reactive, onMounted } from "vue";
import {
  koiMsgSuccess,
  koiNoticeSuccess,
  koiNoticeError,
  koiMsgError,
  koiMsgWarning,
  koiMsgBox,
  koiMsgInfo
} from "@/utils/koi.ts";
import { listNotice, getNotice, delNotice, addNotice, updateNotice } from "@/api/system/notice/index.ts";
import {useKoiDict} from "@/hooks/dicts";

const {koiDicts} = useKoiDict(['sys_notice_status', 'sys_notice_type']);
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件

// 表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref({
  pageNum: 1, // 第几页
  pageSize: 15, // 每页显示多少条
  noticeTitle: "",
  noticeType: ""
});

const total = ref<number>(0);

/** 重置搜索参数 */
const resetSearchParams = () => {
  searchParams.value = {
    pageNum: 1,
    pageSize: 15,
    noticeTitle: "",
    noticeType: ""
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNum = 1;
  handleTableData();
};

/** 重置 */
const resetSearch = () => {
  console.log("重置搜索");
  resetSearchParams();
  handleListPage();
};

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选择条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    const res: any = await listNotice(searchParams.value);
    tableList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch (error) {
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

/** 数据表格[不带Loading，删除、批量删除等使用] */
const handleTableData = async () => {
  try {
    const res: any = await listNotice(searchParams.value);
    tableList.value = res.rows
    total.value = res.total;
  } catch (error) {
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

onMounted(() => {
  // 获取表格数据
  handleListPage();
});

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  // console.log(selection);
  ids.value = selection.map((item: any) => item.noticeId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 添加 */
const handleAdd = () => {
  // 打开抽屉
  koiDialogRef.value.koiOpen();
  koiMsgSuccess("添加");
  // 重置表单
  resetForm();
  // 标题
  title.value = "公告添加";
  form.value.status = "0";
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据");
    return;
  }
  try {
    const res: any = await getNotice(id);
    form.value = res.data;
  } catch (error) {
    koiNoticeError("数据获取失败，请刷新重试");
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 打开抽屉
  koiDialogRef.value.koiOpen();
  koiMsgSuccess("修改");
  // 重置表单
  resetForm();
  // 标题
  title.value = "公告修改";
  const noticeId = row ? row.noticeId : ids.value[0];
  if (noticeId == null || noticeId == "") {
    koiMsgError("请选择需要修改的数据");
  }
  // 回显数据
  handleEcho(noticeId);
};

// 添加 OR 修改抽屉Ref
const koiDialogRef = ref();
// 标题
const title = ref("公告类型管理");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  noticeTitle: "",
  noticeType: "",
  status: "",
  noticeContent: "",
  remark: ""
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  form.value = {
    noticeTitle: "",
    noticeType: "",
    status: "",
    noticeContent: "",
    remark: ""
  };
};

/** 表单规则 */
const rules = reactive({
  noticeTitle: [{ required: true, message: "请输入公告名称", trigger: "blur" }],
  noticeType: [{ required: true, message: "请输入公告类型", trigger: "blur" }],
  status: [{ required: true, message: "请输入选择公告状态", trigger: "blur" }],
  noticeContent: [{ required: true, message: "请输入公告内容", trigger: "blur" }]
});

// 确定按钮是否显示Loading
const confirmLoading = ref(false);

/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      if (form.value.noticeId != null && form.value.noticeId != "") {
        try {
          await updateNotice(form.value);
          koiNoticeSuccess("修改成功");
          confirmLoading.value = false;
          koiDialogRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          confirmLoading.value = false;
          koiNoticeError("修改失败，请刷新重试");
        }
      } else {
        try {
          await addNotice(form.value);
          koiNoticeSuccess("添加成功");
          confirmLoading.value = false;
          koiDialogRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          confirmLoading.value = false;
          koiNoticeError("添加失败，请刷新重试");
        }
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDialogRef.value.koiClose();
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.noticeId;
  if (id == null || id == "") {
    koiMsgWarning("请选择需要删除的数据");
    return;
  }
  koiMsgBox("您确认需要删除公告名称[" + row.noticeTitle + "]么？")
    .then(async () => {
      try {
        await delNotice(id);
        handleTableData();
        koiNoticeSuccess("删除成功");
      } catch (error) {
        koiNoticeError("删除失败，请刷新重试");
      }
    })
    .catch(() => {
      koiMsgError("已取消");
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgInfo("请选择需要删除的数据");
    return;
  }
  koiMsgBox("您确认需要进行批量删除么？")
    .then(async () => {
      try {
        console.log("ids", ids.value);
        await delNotice(ids.value);
        handleTableData();
        koiNoticeSuccess("批量删除成功");
      } catch (error) {
        console.log(error);
        handleTableData();
        koiNoticeError("批量删除失败，请刷新重试");
      }
    })
    .catch(() => {
      koiMsgError("已取消");
    });
};
</script>

<style lang="scss" scoped></style>
