<script setup>
import { reactive, ref, watch } from "vue"
import { getImagePage, deleteImageById, setImageAdmin } from "@/api/alumniAlbum"
import { ElMessage, ElMessageBox } from "element-plus"
import { usePagination } from "@/hooks/usePagination"
import { getQueryCollegesApi, getQueryPeriodsApi, getQueryMajorsApi, getQueryClassesApi } from "@/api/alumniManager"
import { getPageUser } from "@/api/schoolEndorsement"
import { cloneDeep } from "lodash-es"

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

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

//#region 查
const tableData = ref([])
const searchFormRef = ref(null)
const searchData = reactive({
  userName: undefined,
  orgName: undefined,
  collegeId: undefined,
  colleges: [],
  periodId: undefined,
  periods: [],
  majorId: undefined,
  majors: [],
  classId: undefined,
  classList: []
})
const getTableData = () => {
  loading.value = true
  getImagePage({
    currentPage: paginationData.currentPage,
    pageCount: paginationData.pageSize,
    userName: searchData.userName,
    orgName: searchData.orgName,
    collegeId: searchData.collegeId,
    periodId: searchData.periodId,
    majorId: searchData.majorId,
    classId: searchData.classId
  })
    .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()
}

// 获取学院集合
const getColleges = async () => {
  const res = await getQueryCollegesApi()
  // console.log(res)
  searchData.colleges = res.data
}

// 学院筛选框切换回调
const changeCollege = async (e) => {
  const res = await getQueryPeriodsApi({
    collegeId: e
  })
  // console.log(res)
  searchData.periods = res.data
}

// 学段筛选框切换回调
const changePeriod = async (e) => {
  const res = await getQueryMajorsApi({
    periodId: e
  })
  searchData.majors = res.data
}

// 专业筛选框切换回调
const changeMajorId = async (e) => {
  const res = await getQueryClassesApi({
    majorId: e
  })
  searchData.classList = res.data
}
//#endregion

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

watch([() => paginationData.currentPage, () => paginationData.pageSize], getColleges, { immediate: true })

/** 设置管理员 */
const handleSet = () => {
  setAdminDialogVisible.value = true
  getUserData()
}

// 获取用户列表以设置管理员
const getUserData = async () => {
  const res = await getPageUser({
    currentPage: 1,
    pageCount: 999
  })
  // console.log(res)
  setAdminFormData.value.list = res.data.list
}

//#region 设置管理员
const SET_ADMIN_DEFAULT_FORM_DATA = {
  list: [],
  admins: []
}
const setAdminDialogVisible = ref(false)
const setAdminFormRef = ref(null)
const setAdminFormData = ref(cloneDeep(SET_ADMIN_DEFAULT_FORM_DATA))
const setAdminFormRules = {
  admins: [{ required: true, trigger: "blur", message: "必填" }]
}
const handleSetAdmin = () => {
  setAdminFormRef.value?.validate(async (valid, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    // todo 调用设置管理员接口

    await setImageAdmin(setAdminFormData.value)

    ElMessage.success("操作成功")
    setAdminDialogVisible.value = false
    resetSetAdminForm()
  })
}
const resetSetAdminForm = () => {
  setAdminFormRef.value?.clearValidate()
  setAdminFormData.value = cloneDeep(SET_ADMIN_DEFAULT_FORM_DATA)
}
//#endregion
</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="userName" label="姓名">
            <el-input v-model="searchData.userName" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="orgName" label="组织名称">
            <el-input v-model="searchData.orgName" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="collegeId" label="学院">
            <el-select v-model="searchData.collegeId" placeholder="请选择" style="width: 178px" @change="changeCollege">
              <el-option v-for="item in searchData.colleges" :label="item.name" :value="item.id" :key="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="periodId" label="学段">
            <el-select
              v-model="searchData.periodId"
              placeholder="请选择"
              style="width: 178px"
              :disabled="!searchData.collegeId"
              @change="changePeriod"
            >
              <el-option v-for="item in searchData.periods" :label="item.name" :value="item.id" :key="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="majorId" label="专业">
            <el-select
              v-model="searchData.majorId"
              placeholder="请选择"
              style="width: 178px"
              :disabled="!searchData.periodId"
              @change="changeMajorId"
            >
              <el-option v-for="item in searchData.majors" :label="item.name" :value="item.id" :key="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="classId" label="班级">
            <el-select
              v-model="searchData.classId"
              placeholder="请选择"
              style="width: 178px"
              :disabled="!searchData.majorId"
            >
              <el-option v-for="item in searchData.classList" :label="item.name" :value="item.id" :key="item.id" />
            </el-select>
          </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 plain @click="handleSet">设置管理员</el-button>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" max-height="500">
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="name" label="姓名" align="center" />
          <el-table-column prop="collegeName" label="学院" align="center" />
          <el-table-column prop="periodName" label="学段" align="center" />
          <el-table-column prop="majorName" label="专业" align="center" />
          <el-table-column prop="majorName" label="班级" align="center" />
          <el-table-column prop="categoryName" label="分类" align="center" />
          <el-table-column prop="orgName" label="组织" align="center" />
          <el-table-column label="图片" align="center">
            <template #default="{ row }">
              <el-image
                style="width: 100px; height: 100px"
                :src="row.images[0]"
                fit="cover"
                lazy
                :preview-src-list="row.images"
                hide-on-click-modal
                preview-teleported
              />
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip />
          <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="scope">
              <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="setAdminDialogVisible" title="设置管理员" @closed="resetSetAdminForm" width="50%">
      <el-form
        ref="setAdminFormRef"
        :model="setAdminFormData"
        :rules="setAdminFormRules"
        label-width="auto"
        size="large"
      >
        <el-form-item prop="admins" label="管理员">
          <el-select v-model="setAdminFormData.admins" placeholder="请选择" multiple value-key="name">
            <el-option v-for="item in setAdminFormData.list" :label="item.name" :value="item" :key="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="setAdminDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSetAdmin" :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>
