<script setup lang="ts">
import { pageSize } from "@/api/types/requests"
import { onMounted, ref } from "vue"
import { add, change, status, get, getAuthPermissionId, getAllPermissions } from "@/api/roles"
import { ElMessage } from "element-plus"
import { AuthRoles, RolePermission } from "@/api/roles/types/Roles"
import { addRolePermissions, deletePermissions } from "@/api/rolePermissions"
import { useUserStore } from "@/store/modules/user"
// 本页面所使用的类型
type pageDataType = AuthRoles
// 表格展示的数据
const tableShowData = ref<pageDataType[]>([])
// 总数据数（应在handleChangePage时写入）
const totalDataCount = ref<number>(0)
// 当前展示页面（应在handleChangePage中读取）
const nowPage = ref<number>(1)
// 待修改数据（应在beforeClose中置空）
const exchangeData = ref<pageDataType>({ roleName: "", description: "", status: true })
// 待添加数据（应在beforeClose中置空）
const addData = ref<pageDataType>({ roleName: "", description: "", status: true })
// 是否展示修改窗口
const showExchangeDialog = ref<boolean>(false)
// 是否展示添加窗口
const showAddDialog = ref<boolean>(false)
const user = useUserStore()
const showPermissionsDialog = ref<boolean>(false)
const permissionHas = ref<RolePermission[]>([])
const allPermissions = ref<RolePermission[]>([])
const nowPermissionIds = ref<number[]>([])
const isLoading = ref<boolean>(false)
const nowChanged = ref<number>()
/**
 * 当添加按钮被点击（应将addData置空，且将showAddDialog置为true）
 */
const handleAddButtonClick = () => {
  addData.value = {
    description: "",
    roleName: "",
    status: true
  }
  showAddDialog.value = true
}
/**
 * 添加方法（请求在这里发出）
 */
const handleAdd = () => {
  add(addData.value as pageDataType)
    .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 = () => {
  change(exchangeData.value as pageDataType)
    .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
  status(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) => {
  delete_(data.id as number)
    .then(() => {
      ElMessage.success("删除成功！")
    })
    .catch((err) => {
      console.log(err)
      ElMessage.error("删除失败！")
    })
}*/
const hasPermissionsData = ref<boolean>(false)
const hasAuthPermissionsData = ref<boolean>(false)
const handlePermissionButtonClick = (data: pageDataType) => {
  permissionHas.value = []
  nowPermissionIds.value = []
  allPermissions.value = []
  showPermissionsDialog.value = true
  isLoading.value = true
  hasPermissionsData.value = false
  hasAuthPermissionsData.value = false
  nowChanged.value = data.id as number
  getAuthPermissionId(nowChanged.value).then((response) => {
    permissionHas.value = response.data.data
    for (const permission of permissionHas.value) {
      nowPermissionIds.value.push(permission.id)
    }
    hasAuthPermissionsData.value = true
    if (hasPermissionsData.value) {
      isLoading.value = false
    }
  })
  getAllPermissions().then((response) => {
    response.data.data
    for (const permission of response.data.data) {
      allPermissions.value.push({ id: permission.id, name: permission.permissionName })
    }
    hasPermissionsData.value = true
    if (hasAuthPermissionsData.value) {
      isLoading.value = false
    }
  })
}
const handlePermissions = () => {
  for (const id of nowPermissionIds.value) {
    let flag = false
    for (const has of permissionHas.value) {
      const has_id = has.id
      if (has_id == id) {
        flag = true
      }
    }
    if (!flag) {
      addRolePermissions({
        roleId: nowChanged.value as number,
        permissionId: id
      }).catch((err) => {
        ElMessage.error(id + "添加失败！")
        console.log(err)
      })
    }
  }
  for (const has of permissionHas.value) {
    const has_id = has.id
    let flag = false
    for (const id of nowPermissionIds.value) {
      if (id == has_id) {
        flag = true
        break
      }
    }
    if (!flag) {
      deletePermissions(nowChanged.value as number, has_id).catch((err) => {
        ElMessage.error(has_id + "删除失败！")
        console.log(err)
      })
    }
  }
  ElMessage.success("修改任务已发送，请等待页面提示，若5-10s无提示则成功")
  showPermissionsDialog.value = false
}
/**
 * 当页面更换时（应在Mounted时调用）
 */
const handleChangePage = () => {
  get(nowPage.value)
    .then((response) => {
      totalDataCount.value = response.data.data.total
      tableShowData.value = response.data.data.info
    })
    .catch((err) => {
      ElMessage.error("获取页面数据失败！")
      console.log(err)
    })
}
const expanded = (e: pageDataType) => {
  if (e.permissions) {
    return
  }
  getAuthPermissionId(e.id as number).then((response) => {
    e.permissions = response.data.data
  })
}
onMounted(() => {
  handleChangePage()
})
</script>

<template>
  <div class="rolesManagerDiv">
    <div class="rolesManagerSearchDiv">
      <el-button style="margin-left: 10px" type="warning" @click="handleAddButtonClick">添加权限组</el-button>
    </div>
    <div class="rolesManagerTableDiv">
      <el-table :data="tableShowData" style="width: 100%" table-layout="auto" @expand-change="expanded">
        <el-table-column type="expand">
          <template #default="props">
            <el-table :data="props.row.permissions" style="width: 100%">
              <el-table-column prop="name" label="权限名称" width="200px" />
              <el-table-column prop="code" label="权限ID" width="200px" />
              <el-table-column prop="description" label="注释" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="50px" />
        <el-table-column prop="roleName" label="权限组名称" 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)"
              v-if="user.hasRole('change:roles')"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click="handlePermissionButtonClick(scope.row)"
              v-if="user.hasRole('change:roles')"
              >修改权限</el-button
            >
            <!--            <el-button
              link
              type="primary"
              size="small"
              @click="handleDeleteButtonClick(scope.row)"
              v-if="user.hasRole('change:roles') && scope.row.id != 1"
              >删除</el-button
            >-->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="rolesManagerPaginationDiv">
      <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 = {
            id: -1,
            description: '',
            roleName: '',
            status: true
          }
        }
      "
    >
      <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="roleName">
          <el-input v-model="exchangeData.roleName" />
        </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 = {
            description: '',
            roleName: '',
            status: true
          }
        }
      "
    >
      <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.roleName" />
        </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>
    <el-dialog v-model="showPermissionsDialog" title="修改权限" width="30%">
      <el-select multiple collapse-tags v-model="nowPermissionIds" :loading="isLoading">
        <el-option v-for="i of allPermissions" :label="i.name" :value="i.id" :key="i.id" />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPermissionsDialog = false">取消</el-button>
          <el-button type="primary" @click="handlePermissions">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.rolesManagerDiv {
  width: calc(100% - 20px);
  height: calc(100% - 20px);
  margin: 10px 10px 10px 10px;
}
.rolesManagerTableDiv {
  width: 100%;
  height: calc(90% - 20px);
  margin-top: 10px;
}
.rolesManagerPaginationDiv {
  height: 5%;
  margin-top: 10px;
  min-height: 32px;
}
.rolesManagerSearchDiv {
  height: 5%;
  width: 100%;
}
</style>
