<script setup lang="ts">
import { pageSize } from "@/api/types/requests"
import { AuthPermissions } from "@/api/permission/type/permission"
import { onMounted, ref } from "vue"
import {
  addAuthPermission,
  changeAuthPermissions,
  changeAuthPermissionsStats,
  deleteAuthPermissions,
  getAuthPermissions
} from "@/api/permission"
import { ElMessage } from "element-plus"
// 本页面所使用的类型
type pageDataType = AuthPermissions
// 表格展示的数据
const tableShowData = ref<pageDataType[]>([])
// 总数据数（应在handleChangePage时写入）
const totalDataCount = ref<number>(0)
// 当前展示页面（应在handleChangePage中读取）
const nowPage = ref<number>(1)
// 待修改数据（应在beforeClose中置空）
const exchangeData = ref<pageDataType>({ permissionName: "", permissionCode: "", description: "" })
// 待添加数据（应在beforeClose中置空）
const addData = ref<pageDataType>({ permissionName: "", permissionCode: "", description: "" })
// 是否展示修改窗口
const showExchangeDialog = ref<boolean>(false)
// 是否展示添加窗口
const showAddDialog = ref<boolean>(false)
/**
 * 当添加按钮被点击（应将addData置空，且将showAddDialog置为true）
 */
const handleAddButtonClick = () => {
  addData.value = {
    createTime: "",
    description: "",
    updateTime: "",
    permissionCode: "",
    permissionName: "",
    status: true
  }
  showAddDialog.value = true
}
/**
 * 添加方法（请求在这里发出）
 */
const handleAdd = () => {
  addAuthPermission(addData.value as AuthPermissions)
    .then(() => {
      ElMessage.success("添加成功")
    })
    .catch((err) => {
      ElMessage.error("添加失败！")
      console.log(err)
    })
  showAddDialog.value = false
}
/**
 * 当修改按钮被点击（应将exchangeData修改为入参data的值，且将showExchangeDialog置为true）
 * @param data 待修改的数据
 */
const handleExchangeButtonClick = (data: pageDataType) => {
  exchangeData.value = data
  showExchangeDialog.value = true
}
/**
 * 修改数据方法（请求在这里发出）
 */
const handleExchange = () => {
  changeAuthPermissions(exchangeData.value as AuthPermissions)
    .then(() => {
      ElMessage.success("修改成功！")
    })
    .catch((err) => {
      ElMessage.error("修改失败！")
      console.log(err)
    })
  showExchangeDialog.value = false
}
/**
 * 修改状态方法
 * @param dataIndex 数据的index
 */
const handleChangeStatus = (dataIndex: number) => {
  const nowData = tableShowData.value[dataIndex]
  const newStatus = !nowData.status
  changeAuthPermissionsStats(nowData.id as number, newStatus)
    .then(() => {
      ElMessage.success("状态修改成功")
      tableShowData.value[dataIndex].status = newStatus
    })
    .catch((err) => {
      console.log(err)
      ElMessage.error("修改状态失败")
    })
}
/**
 * 删除按钮点击时（可以发请求了）
 * @param data 删除的项数据
 */
const handleDeleteButtonClick = (data: pageDataType) => {
  deleteAuthPermissions(data.id as number)
    .then(() => {
      ElMessage.success("删除成功！")
    })
    .catch((err) => {
      console.log(err)
      ElMessage.error("删除失败！")
    })
}
/**
 * 当页面更换时（应在Mounted时调用）
 */
const handleChangePage = () => {
  getAuthPermissions(nowPage.value)
    .then((response) => {
      totalDataCount.value = response.data.data.total
      tableShowData.value = response.data.data.info
    })
    .catch((err) => {
      ElMessage.error("获取页面数据失败！")
      console.log(err)
    })
}
onMounted(() => {
  handleChangePage()
})
</script>

<template>
  <div class="permissionManagerDiv">
    <div class="permissionManagerSearchDiv">
      <el-button style="margin-left: 10px" type="warning" @click="handleAddButtonClick">添加权限</el-button>
    </div>
    <div class="permissionManagerTableDiv">
      <el-table :data="tableShowData" style="width: 100%" table-layout="auto">
        <el-table-column fixed prop="id" label="ID" width="50px" />
        <el-table-column prop="permissionName" label="权限名称" width="200px" />
        <el-table-column prop="permissionCode" label="权限ID" width="200px" />
        <el-table-column prop="description" label="注释" width="200px" />
        <el-table-column prop="createId" label="创建者ID" width="100px" />
        <el-table-column prop="createTime" label="创建时间" width="200px" />
        <el-table-column prop="updateTime" label="更新时间" width="200px" />
        <el-table-column prop="status" label="状态" width="100px">
          <template #default="scope">
            <el-switch :model-value="scope.row.status" @click="handleChangeStatus(scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleExchangeButtonClick(scope.row)">修改</el-button>
            <el-button link type="primary" size="small" @click="handleDeleteButtonClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="permissionManagerPaginationDiv">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalDataCount"
        :page-size="pageSize"
        :current-page="nowPage"
        @update:current-page="handleChangePage"
      />
    </div>
    <el-dialog
      v-model="showExchangeDialog"
      title="修改权限"
      width="30%"
      :before-close="
        () => {
          exchangeData = {
            createTime: '',
            description: '',
            updateTime: '',
            permissionCode: '',
            permissionName: ''
          }
        }
      "
    >
      <el-form :model="exchangeData" label-width="150px">
        <el-form-item label="注释" prop="description">
          <el-input v-model="exchangeData.description" />
        </el-form-item>
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="exchangeData.permissionName" />
        </el-form-item>
        <el-form-item label="权限ID" prop="permissionCode">
          <el-input v-model="exchangeData.permissionCode" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showExchangeDialog = false">取消</el-button>
          <el-button type="primary" @click="handleExchange">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="showAddDialog"
      title="添加权限"
      width="30%"
      :before-close="
        () => {
          addData = {
            createTime: '',
            description: '',
            updateTime: '',
            permissionCode: '',
            permissionName: ''
          }
        }
      "
    >
      <el-form :model="addData" label-width="150px">
        <el-form-item label="注释" prop="description">
          <el-input v-model="addData.description" />
        </el-form-item>
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="addData.permissionName" />
        </el-form-item>
        <el-form-item label="权限ID" prop="permissionCode">
          <el-input v-model="addData.permissionCode" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.permissionManagerDiv {
  width: calc(100% - 20px);
  height: calc(100% - 20px);
  margin: 10px 10px 10px 10px;
}
.permissionManagerTableDiv {
  width: 100%;
  height: calc(90% - 20px);
  margin-top: 10px;
}
.permissionManagerPaginationDiv {
  height: 5%;
  margin-top: 10px;
  min-height: 32px;
}
.permissionManagerSearchDiv {
  height: 5%;
  width: 100%;
}
</style>
