<template>
  <view class="personnel-list" v-if="data && data.length">
    <view class="personnel-item" v-for="(item, index) of data" :key="item.id || index" @click="handleItemClick(item, index)">
      <view class="personnel-img">
        <UserAvatar :userName="item.nickName || item.userName" :avatarLink="item.avatar" />
      </view>
      <view class="personnel-name">{{ item.nickName || item.userName }}</view>
      <view v-if="showDelete" class="delete-icon" @click.stop="handleDelete(index)">
        <uni-icons type="close" size="16" color="#999"></uni-icons>
      </view>
    </view>
  </view>
</template>

<script>
import UserAvatar from '@/pages/attendance/components/UserAvatar.vue'

export default {
  name: 'ListUser',
  components: {
    UserAvatar
  },
  props: {
    // 人员数据数组
    data: {
      type: Array,
      default: () => []
    },
    // 是否显示删除图标
    showDelete: {
      type: Boolean,
      default: false
    },
    // 禁用状态
    disabled: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    // 处理删除操作
    handleDelete(index) {
      if (!this.data || !this.data.length || this.disabled) return

      // 创建新数组（避免直接修改props）
      const newData = [...this.data]
      const deletedItem = newData.splice(index, 1)[0]

      // 向外传递删除后的数组和删除的项
      this.$emit('update:data', newData)
      this.$emit('delete', {
        deletedItem,
        index,
        newData
      })

      uni.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 1500
      })
    },

    // 处理人员项点击
    handleItemClick(item, index) {
      this.$emit('click', {
        clickedItem: item,
        index,
        data: this.data
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.personnel-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin: 20rpx 0;
}

.personnel-item {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 24rpx;
  padding: 12rpx 20rpx;
  position: relative;

  .personnel-img {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 16rpx;
    flex-shrink: 0;
  }

  .personnel-name {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    flex: 1;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .delete-icon {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    background: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 16rpx;
    flex-shrink: 0;
    cursor: pointer;
    transition: background-color 0.2s;

    &:hover {
      background: #e0e0e0;
    }

    &:active {
      background: #d0d0d0;
    }
  }
}
</style>