<script setup>
import { reactive, ref, watch, onBeforeMount } from "vue"
import {
  getTableDataApi,
  getQueryCollegesApi,
  getQueryPeriodsApi,
  getQueryMajorsApi,
  getQueryClassesApi,
  getQueryPassTypesApi,
  toExamineClubApi,
  queryClubProcessExcelApi
} from "@/api/alumniOrganization/audit-list"
import { ElMessageBox } from "element-plus"
import { usePagination } from "@/hooks/usePagination"

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

//#region 查
const tableData = ref([])
const searchFormRef = ref(null)
const searchData = reactive({
  userName: undefined,
  createTime: null,
  status: undefined,
  statusOptions: undefined,
  name: undefined,
  college: undefined,
  collegeOptions: undefined,
  period: undefined,
  periodOptions: undefined,
  major: undefined,
  majorOptions: undefined,
  class: undefined,
  classOptions: undefined
})
/**
 * 获取 审核状态列表
 */
const getQueryPassTypes = () => {
  loading.value = true
  getQueryPassTypesApi()
    .then(({ data }) => {
      searchData.statusOptions = data
    })
    .catch(() => {
      searchData.statusOptions = []
    })
    .finally(() => {
      loading.value = false
    })
}
/**
 * 获取 学院列表
 */
const getQueryColleges = () => {
  loading.value = true
  getQueryCollegesApi()
    .then(({ data }) => {
      searchData.collegeOptions = data
    })
    .catch(() => {
      searchData.collegeOptions = []
    })
    .finally(() => {
      loading.value = false
    })
}
/**
 * 获取 学段列表
 */
const getQueryPeriods = () => {
  if (searchData.college === undefined) {
    return
  }
  searchData.periodOptions = []
  searchData.period = ""

  searchData.majorOptions = []
  searchData.major = ""

  searchData.classOptions = []
  searchData.class = ""
  loading.value = true
  getQueryPeriodsApi({
    collegeId: searchData.college
  })
    .then(({ data }) => {
      searchData.periodOptions = data
    })
    .catch(() => {
      searchData.periodOptions = []
    })
    .finally(() => {
      loading.value = false
    })
}
/**
 * 获取 专业列表
 */
const getQueryMajors = () => {
  if (searchData.period === undefined) {
    return
  }
  searchData.majorOptions = []
  searchData.major = ""

  searchData.classOptions = []
  searchData.class = ""
  loading.value = true
  getQueryMajorsApi({
    periodId: searchData.period
  })
    .then(({ data }) => {
      searchData.majorOptions = data
    })
    .catch(() => {
      searchData.majorOptions = []
    })
    .finally(() => {
      loading.value = false
    })
}
/**
 * 获取 班级列表
 */
const getQueryClasses = () => {
  if (searchData.major === undefined) {
    return
  }
  searchData.classOptions = []
  searchData.class = ""
  loading.value = true
  getQueryClassesApi({
    majorId: searchData.major
  })
    .then(({ data }) => {
      searchData.classOptions = data
    })
    .catch(() => {
      searchData.classOptions = []
    })
    .finally(() => {
      loading.value = false
    })
}
/**
 * 获取 表格数据
 */
const getTableData = () => {
  loading.value = true
  getTableDataApi({
    currentPage: paginationData.currentPage,
    pageCount: paginationData.pageSize,
    name: searchData.name,
    userName: searchData.userName,
    isPass: searchData.status,
    collegeId: searchData.college,
    periodId: searchData.period,
    majorId: searchData.major,
    classId: searchData.class,
    startTime: searchData.createTime ? searchData.createTime[0] : undefined,
    endTime: searchData.createTime ? searchData.createTime[1] : undefined
  })
    .then(({ data }) => {
      paginationData.total = data.totalCount
      tableData.value = data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
/**
 * 导出 表格数据
 */
const handleDownload = async () => {
  loading.value = true
  const res = await queryClubProcessExcelApi({
    name: searchData.name,
    userName: searchData.userName,
    isPass: searchData.status,
    college: searchData.college,
    period: searchData.period,
    major: searchData.major,
    class: searchData.class,
    startTime: searchData.createTime ? searchData.createTime[0] : undefined,
    endTime: searchData.createTime ? searchData.createTime[1] : undefined
  })
  // console.log(res)
  // 请求成功返回后，获取到Excel文件的二进制数据
  const blob = new Blob([res], { type: "application/vnd.ms-excel" })
  // 创建下载链接
  const downloadUrl = URL.createObjectURL(blob)
  // 创建一个隐藏的a标签，设置下载链接和文件名，模拟点击下载
  const link = document.createElement("a")
  link.style.display = "none"
  link.href = downloadUrl
  link.download = `审核列表数据_下载时间_${getCurrentDateTime()}.xlsx`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  loading.value = false
}
/**
 * 获取日期时间
 */
const getCurrentDateTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, "0") // 月份从0开始，需要加1
  const day = String(now.getDate()).padStart(2, "0")
  const hours = String(now.getHours()).padStart(2, "0")
  const minutes = String(now.getMinutes()).padStart(2, "0")
  const seconds = String(now.getSeconds()).padStart(2, "0")
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

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

/** 通过 */
const handlePass = (row) => {
  ElMessageBox.confirm("确认通过？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    closeOnPressEscape: false,
    closeOnClickModal: false
  }).then(() => {
    // 调用通过接口
    toExamineClubApi({
      id: row.id,
      isPass: 2
    })
      .then(() => {
        ElMessage.success("已审核通过")
        getTableData()
      })
      .catch(() => {})
  })
}

/** 拒绝 */
const handleReject = (row) => {
  ElMessageBox.prompt("确认拒绝？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /[\u4e00-\u9fa5a-zA-Z0-9_-]{2,100}/,
    inputErrorMessage: "请输入拒绝理由",
    closeOnPressEscape: false,
    closeOnClickModal: false
  }).then((content) => {
    // 调用拒绝接口
    toExamineClubApi({
      id: row.id,
      isPass: 3,
      passValue: content.value
    })
      .then(() => {
        ElMessage.success("已拒绝")
        getTableData()
      })
      .catch(() => {})
  })
}

onBeforeMount(() => {
  getQueryPassTypes()
  getQueryColleges()
})
</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="name" label="组织名称">
            <el-input v-model="searchData.name" clearable placeholder="请输入" style="width: 150px" />
          </el-form-item>
          <el-form-item prop="userName" label="申请人">
            <el-input v-model="searchData.userName" clearable placeholder="请输入" style="width: 150px" />
          </el-form-item>
          <el-form-item prop="status" label="审核状态">
            <el-select v-model="searchData.status" placeholder="请选择" style="width: 150px">
              <el-option v-for="item in searchData.statusOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="college" label="学院">
            <el-select
              v-model="searchData.college"
              placeholder="请选择"
              @change="getQueryPeriods"
              clearable
              style="width: 178px"
            >
              <el-option v-for="item in searchData.collegeOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="period" label="学段">
            <el-select
              v-model="searchData.period"
              placeholder="请选择"
              @change="getQueryMajors"
              clearable
              style="width: 178px"
              :disabled="!searchData.college"
            >
              <el-option v-for="item in searchData.periodOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="major" label="专业">
            <el-select
              v-model="searchData.major"
              placeholder="请选择"
              @change="getQueryClasses"
              clearable
              style="width: 178px"
              :disabled="!searchData.period"
            >
              <el-option v-for="item in searchData.majorOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="class" label="班级">
            <el-select
              v-model="searchData.class"
              placeholder="请选择"
              clearable
              style="width: 178px"
              :disabled="!searchData.major"
            >
              <el-option v-for="item in searchData.classOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <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-button plain @click="handleDownload">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" max-height="450" height="450">
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="applyName" 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="className" label="班级" align="center" />
          <el-table-column prop="name" label="申请组织" align="center" />
          <el-table-column prop="applyUserName" label="审核人" align="center" />
          <el-table-column prop="passName" label="审核状态" align="center" />
          <el-table-column prop="passTime" label="审核时间" align="center" width="160" />
          <el-table-column prop="createTime" label="创建时间" align="center" width="160" />
          <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="scope">
              <el-link type="danger" @click="handleReject(scope.row)">拒绝</el-link>
              <el-link type="primary" @click="handlePass(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>
  </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>
