<template>
  <a-modal
    v-model:visible="modalVisible"
    title="分配角色"
    :width="600"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div v-if="userData" class="user-info">
      <a-descriptions :column="2" bordered size="small">
        <a-descriptions-item label="用户">{{ userData.name }}（{{ userData.account }}）</a-descriptions-item>
        <a-descriptions-item label="部门">{{ userData.deptName || '-' }}</a-descriptions-item>
      </a-descriptions>
    </div>
    
    <div class="role-section">
      <h4>选择角色</h4>
      <a-checkbox-group v-model="selectedRoles" direction="vertical" style="width: 100%">
        <a-checkbox 
          v-for="role in availableRoles" 
          :key="role.value" 
          :value="role.value"
          style="margin-bottom: 8px; display: block;"
        >
          <span class="role-item">
            <span class="role-name">{{ role.label }}</span>
            <span class="role-desc">{{ role.description || '暂无描述' }}</span>
          </span>
        </a-checkbox>
      </a-checkbox-group>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { bindUserRole } from '@/apis/system/user-new'

interface Props {
  visible: boolean
  userData?: any
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  userData: null
})

const emit = defineEmits<{
  'update:visible': [visible: boolean]
  success: []
}>()

const modalVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const selectedRoles = ref<string[]>([])

// 模拟角色数据，实际应该从API获取
const availableRoles = ref([
  { value: 'admin', label: '系统管理员', description: '拥有系统所有权限' },
  { value: 'manager', label: '部门经理', description: '管理本部门相关业务' },
  { value: 'employee', label: '普通员工', description: '基础员工权限' },
  { value: 'hr', label: '人事专员', description: '人力资源相关权限' },
  { value: 'finance', label: '财务专员', description: '财务相关权限' }
])

// 监听用户数据变化，初始化已选角色
watch(() => props.userData, (newData) => {
  if (newData && newData.roleIds) {
    selectedRoles.value = [...newData.roleIds]
  } else {
    selectedRoles.value = []
  }
}, { immediate: true })

// 监听弹窗显示状态
watch(() => props.visible, (visible) => {
  if (visible && props.userData) {
    selectedRoles.value = props.userData.roleIds ? [...props.userData.roleIds] : []
  }
})

const handleSubmit = async () => {
  try {
    if (!props.userData) {
      Message.error('用户信息不存在')
      return false
    }

    await bindUserRole({
      userId: props.userData.userId,
      roleIds: selectedRoles.value.map(id => String(id))
    })
    
    Message.success('角色分配成功')
    emit('success')
    modalVisible.value = false
    return true
  } catch (error) {
    console.error('角色分配失败:', error)
    Message.error('角色分配失败')
    return false
  }
}

const handleCancel = () => {
  modalVisible.value = false
}

// 这里可以添加获取角色列表的API调用
const loadRoles = async () => {
  // 实际项目中应该调用角色列表API
  // const response = await getRoleList()
  // availableRoles.value = response.data
}

onMounted(() => {
  loadRoles()
})
</script>

<style scoped lang="scss">
.user-info {
  margin-bottom: 20px;
}

.role-section {
  h4 {
    margin-bottom: 12px;
    color: #1d2129;
    font-weight: 500;
  }
}

.role-item {
  display: flex;
  flex-direction: column;
  
  .role-name {
    font-weight: 500;
    color: #1d2129;
  }
  
  .role-desc {
    font-size: 12px;
    color: #86909c;
    margin-top: 2px;
  }
}

:deep(.arco-checkbox) {
  align-items: flex-start;
  
  .arco-checkbox-icon {
    margin-top: 2px;
  }
}
</style> 