<template>
  <ADialog v-model:show="showDialog"
    :closed="dialogCloseHandler"
    title="分配角色" width="700px">
    <ElTransfer
      v-model="rightValue"
      :button-texts="['解绑', '绑定']"
      :data="allRoles"
      :filter-method="filterMethod"
      :props="{
      key: 'id',
      label: 'roleName',
    }"
      :titles="['角色列表', '已有角色']"
      class="transfer"
      filter-placeholder="搜索"
      filterable
    >
      <template #default="{ option }">
        <ElTooltip
          :content="option.roleCode"
          placement="top">
          <span> {{ option.roleName }} </span>
        </ElTooltip>
      </template>
      <template #left-empty>
        <el-empty :image-size="60" description="暂无数据"/>
      </template>
      <template #right-empty>
        <el-empty :image-size="60" description="暂无数据"/>
      </template>
    </ElTransfer>
    <template #footer>
      <ElButton @click="showDialog = false">取消</ElButton>
      <ElButton :disabled="rightValue.length <= 0" :loading="submiting" type="primary" @click="submitHandler">提交</ElButton>
    </template>
  </ADialog>
</template>
<script lang="ts" setup>
import RoleApi from '@/pages/sys/role/role-api.ts'
import Strings from '@/common/utils/strings.ts'
import {
  ElMessage,
  type TransferDataItem,
} from 'element-plus'
import UserApi from '@/pages/sys/user/user-api.ts'
import ADialog from '@/components/a-dialog/ADialog.vue'

const showDialog = ref(false)
const submiting = ref(false)
const hadRoles = ref<RoleTypes.SearchRoleResult[]>([])
const allRoles = ref<RoleTypes.SearchRoleResult[]>([])
const rightValue = ref<string[]>([])
const currentUserId = ref<string>('')

function dialogCloseHandler() {
  currentUserId.value = ''
  hadRoles.value = []
  allRoles.value = []
  rightValue.value = []
}

function filterMethod(query: string, item: TransferDataItem) {
  return Strings.isBlank(query) || (item as RoleTypes.SearchRoleResult).roleCode!.includes(query) || (item as RoleTypes.SearchRoleResult).roleName!.includes(query)
}

function submitHandler() {
  submiting.value = true
  UserApi.bindRole({
    id: currentUserId.value,
    roles: rightValue.value,
  }).then(() => {
    ElMessage.success('修改成功')
    showDialog.value = false
  })
    .finally(() => {
      submiting.value = false
    })
}

defineExpose({
  open(userId: string) {
    currentUserId.value = userId
    showDialog.value = true
    RoleApi.listUserRole(userId)
      .then(res => {
        hadRoles.value = res.data ?? []
        rightValue.value = hadRoles.value.map(it => it.id!)
      })
    RoleApi.list()
      .then(res => {
        allRoles.value = res.data ?? []
      })
  },
})
</script>
<style lang="stylus" scoped>
.transfer {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
