<script setup>
import { reactive, ref, watch } from "vue"
import { getCategoryImagePage, addCategoryImage, updateCategoryImage, deleteCategoryImage } from "@/api/alumniAlbum"
import { ElMessage, ElMessageBox } from "element-plus"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"

const loading = ref(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const DEFAULT_FORM_DATA = {
  id: undefined,
  name: ""
}
const dialogVisible = ref(false)
const formRef = ref(null)
const formData = ref(cloneDeep(DEFAULT_FORM_DATA))
const formRules = {
  name: [{ required: true, trigger: "blur", message: "必填" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = formData.value.id === undefined ? addCategoryImage : updateCategoryImage
    api(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisible.value = false
        getTableData()
      })
      .catch(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
//#endregion

//#region 删
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteCategoryImage(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const handleUpdate = (row) => {
  dialogVisible.value = true
  formData.value = cloneDeep(row)
}
//#endregion

//#region 查
const tableData = ref([])
const searchFormRef = ref(null)
const searchData = reactive({
  createTime: null
})
const getTableData = () => {
  loading.value = true
  getCategoryImagePage({
    currentPage: paginationData.currentPage,
    pageCount: paginationData.pageSize,
    startTime: searchData.createTime ? searchData.createTime[0] : undefined,
    endTime: searchData.createTime ? searchData.createTime[1] : undefined
  })
    .then(({ data }) => {
      // console.log(data)

      paginationData.total = data.totalCount
      tableData.value = data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" header="分类管理">
      <div class="toolbar-wrapper">
        <el-form ref="searchFormRef" :inline="true" :model="searchData">
          <el-form-item prop="createTime" label="创建时间">
            <el-date-picker
              v-model="searchData.createTime"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch" plain>重置</el-button>
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" @click="dialogVisible = true">创建分类</el-button>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" max-height="500">
          <el-table-column type="index" label="序号" width="100" align="center" />
          <el-table-column prop="name" label="分类名称" align="center" />
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column prop="createUser" label="创建人" align="center" />
          <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="scope">
              <el-link type="primary" @click="handleUpdate(scope.row)">编辑</el-link>
              <el-link type="danger" @click="handleDelete(scope.row)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id === undefined ? '创建分类' : '编辑分类'"
      @closed="resetForm"
      width="50%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="auto" size="large">
        <el-form-item prop="name" label="分类名称">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">立即创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.toolbar-wrapper {
  margin-bottom: 26px;
}

.table-wrapper {
  margin-bottom: 29px;
  .el-link {
    margin-right: 15px;
  }
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
