<template>
  <div style="font-weight: bold; font-size: 16px; margin-bottom: 12px;">角色选择</div>
  <div class="role-transfer">
    <div class="transfer-list">
      <div class="transfer-header">
        <span>角色列表</span>
        <span class="select-all-action" @click="handleSelectAllAction">全选</span>
      </div>
      <div class="role-list">
        <div v-for="role in filteredRoles" :key="role.id" class="role-item" @click="handleRoleDirectSelect(role)">
          {{ role.name }}
        </div>
      </div>
    </div>
    <div class="transfer-list">
      <div class="transfer-header">
        <span>已选择角色列表</span>
        <el-button link type="primary" @click="clearSelected">清空</el-button>
      </div>
      <div class="selected-list">
        <div v-for="role in selectedRoles" :key="role.id" class="role-item" @click="handleRoleRemove(role)">
          {{ role.name }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'

// 定义组件名称
defineOptions({
  name: 'RoleTransfer'
})

// 定义props
const props = defineProps({
  roles: {
    type: Array,
    required: true
  },
  selectedRoles: {
    type: Array,
    required: true
  },
  searchRole: {
    type: String,
    default: ''
  }
})

// 定义emit
const emit = defineEmits(['update:roles', 'update:selectedRoles', 'update:searchRole'])

// 计算属性
const filteredRoles = computed(() => {
  return props.roles.filter(role =>
    role.name.toLowerCase().includes(props.searchRole.toLowerCase())
  )
})

// 方法
const handleSelectAllAction = () => {
  emit('update:selectedRoles', [...props.selectedRoles, ...props.roles])
  emit('update:roles', [])
}

const handleRoleDirectSelect = (role) => {
  emit('update:selectedRoles', [...props.selectedRoles, role])
  emit('update:roles', props.roles.filter(r => r.id !== role.id))
}

const handleRoleRemove = (role) => {
  emit('update:roles', [...props.roles, { ...role, selected: false }])
  emit('update:selectedRoles', props.selectedRoles.filter(r => r.id !== role.id))
}

const clearSelected = () => {
  emit('update:roles', [...props.roles, ...props.selectedRoles])
  emit('update:selectedRoles', [])
}
</script>

<style scoped>
.role-transfer {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}
.transfer-list {
  flex: 1;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  height: 300px;
  display: flex;
  flex-direction: column;
  width: 310px;
}
.transfer-header {
  padding: 8px 12px;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f7fa;
}
.select-all-action {
  color: #409EFF;
  cursor: pointer;
  font-size: 14px;
  margin-left: 10px;
  user-select: none;
  transition: color 0.2s;
}
.select-all-action:hover {
  color: #66b1ff;
}
.role-list, .selected-list {
  flex: 1;
  overflow-y: auto;
  padding: 6px 0;
}
.role-item {
  padding: 6px 12px;
  cursor: pointer;
}
.role-item:hover {
  background-color: #f5f7fa;
}
</style>
