<template>
  <el-dialog
    v-model="visible"
    :title="`${paramsProps.title}-${paramsProps.row?.userName}`"
    :destroy-on-close="true"
    width="650px"
    draggable
    append-to-body>
    <el-transfer
      v-model="hasRoles"
      filterable
      :filter-method="filterMethod"
      :titles="['未设置角色', '已设置角色']"
      filter-placeholder="筛选角色"
      :props="transferProps"
      :data="allRoles" />
    <template #footer>
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="AddRoleDialog">
import { RoleVO } from '@/api/interface/system/role'
import { UserBO } from '@/api/interface/system/user'
import UserApi from '@/api/module/system/user'
import { ResultEnum } from '@/enums/HttpEnum'

interface EcoDialogProps {
  api?: (params: any) => Promise<any> // 调用接口
  title: string // 顶部标题
  row: Partial<UserBO>
  getTableList?: () => void
}

const transferProps = {
  key: 'roleId',
  label: 'name'
}

/**
 * 过滤角色
 * @param query
 * @param item
 * @returns {boolean}
 */
const filterMethod = (query: string, item: Record<string, any>) => {
  return item.name.toLowerCase().includes(query.toLowerCase())
}

const visible = ref(false)
const paramsProps = ref<EcoDialogProps>({
  title: '',
  row: {},
  api: undefined,
  getTableList: undefined
})

// 接收父组件传过来的参数
const acceptParams = (params: EcoDialogProps) => {
  paramsProps.value = params
  visible.value = true
  getRole(params.row.userId || '')
}

const allRoles = ref<RoleVO[]>([])
const hasRoles = ref<string[]>([])

/**
 * 获取权限信息
 * @param userId
 */
const getRole = (userId: string) => {
  if (!userId) return
  UserApi.getRole(userId).then(res => {
    hasRoles.value = res.data.hasRoles
    allRoles.value = res.data.allRoles
  })
}

const handleSubmit = async () => {
  try {
    const { code } = await paramsProps.value.api!({ userId: paramsProps.value.row.userId, roleIds: hasRoles.value })
    if (code == ResultEnum.SUCCESS) {
      ElMessage.success({ message: `${paramsProps.value.title}成功！` })
      paramsProps.value.getTableList!()
      visible.value = false
    }
  } catch (error) {
    console.log(error)
  }
}

defineExpose({
  acceptParams
})
</script>

<style scoped lang="scss"></style>
