<template>
  <wd-popup
    v-model="visible"
    position="bottom"
    :safe-area-inset-bottom="true"
    custom-style="height: 100vh; border-radius: 0;"
    @close="handleCancel"
  >
    <view class="select-user-modal">
      <!-- 顶部按钮栏 -->
      <view class="modal-header">
        <view class="header-btn cancel-btn" @click="handleCancel">
          <text>取消</text>
        </view>
        <text class="header-title">{{ title }}</text>
        <view class="header-btn confirm-btn" @click="handleConfirm">
          <text>确定</text>
        </view>
      </view>

      <!-- 搜索栏 -->
      <view class="search-bar">
        <wd-search
          v-model="searchText"
          placeholder="请输入姓名搜索"
          :placeholder-left="true"
          hide-cancel
          @blur="handleSearch"
          @clear="handleClear"
        />
      </view>

      <!-- 已选中用户 -->
      <view class="selected-bar">
        <text class="selected-label">已选中：</text>
        <scroll-view class="selected-tags-scroll" scroll-x>
          <view
            v-for="user in selectedUsers"
            :key="user.id"
            class="selected-user-tag"
          >
            <text class="selected-user-name">{{ user.nickname || '-' }}</text>
            <view class="selected-user-remove" @click.stop="handleRemoveSelected(user)">
              <wd-icon name="close" size="14px" color="#999" />
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 列表区域 -->
      <scroll-view class="user-list" scroll-y>
        <view
          v-for="item in userList"
          :key="item.id"
          class="user-item"
          :class="{ 'user-item--selected': isUserSelected(item) }"
          @click="handleSelectUser(item)"
        >
          <view class="user-avatar">
            <wd-img
              v-if="item.avatar"
              width="36"
              height="36"
              :src="item.avatar"
            />
            <view v-else class="avatar-placeholder">
              <text class="avatar-text">{{ (item.nickname || '?')[0] }}</text>
            </view>
          </view>
          <view class="user-info">
            <view class="user-name-row">
              <text class="user-name">{{ item.nickname || '-' }}</text>
              <text v-if="item.employeeNo" class="user-employee-no">{{ item.employeeNo }}</text>
            </view>
            <text v-if="item.deptName" class="user-dept">{{ item.deptName }}</text>
          </view>
        </view>
        <view v-if="!userList.length" class="empty-tip">
          <wd-status-tip image="content" tip="暂无数据" />
        </view>
      </scroll-view>
    </view>
  </wd-popup>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { getUserPage } from '@/api/system/user'

interface UserItem {
  id: string
  nickname?: string
  username?: string
  avatar?: string
  employeeNo?: string,
  deptName?: string,
  [key: string]: any
}

interface Props {
  modelValue: boolean
  title?: string
  selected?: UserItem[]
  multiple?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '选择人员',
  selected: () => [],
  multiple: true,
})

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  confirm: [users: UserItem[]]
  cancel: []
}>()

const visible = ref(false)
const searchText = ref('')
const userList = ref<UserItem[]>([])
const selectedUsers = ref<UserItem[]>([])

watch(
  () => props.modelValue,
  (val) => {
    visible.value = val
    if (val) {
      selectedUsers.value = props.selected ? [...props.selected] : []
      fetchUserList()
    }
  },
  { immediate: true },
)

watch(visible, (val) => {
  if (!val) {
    searchText.value = ''
    emit('update:modelValue', false)
  }
})

const fetchUserList = (nickName?: string) => {
  const params: Record<string, any> = {
    pageNo: 1,
    pageSize: 100,
    nickName,
  }
  getUserPage(params).then(res => {
    userList.value = res.data.list
  })
}

const handleSearch = () => {
  fetchUserList(searchText.value)
}

const handleClear = () => {
  searchText.value = ''
  fetchUserList()
}

const isUserSelected = (item: UserItem) => {
  return selectedUsers.value.some((u) => u.id === item.id)
}

const handleSelectUser = (item: UserItem) => {
  if (props.multiple) {
    const idx = selectedUsers.value.findIndex((u) => u.id === item.id)
    if (idx >= 0) {
      selectedUsers.value.splice(idx, 1)
    } else {
      selectedUsers.value.push(item)
    }
  } else {
    // 单选：点击同一项取消选中，点击其他项替换
    if (selectedUsers.value.length && selectedUsers.value[0].id === item.id) {
      selectedUsers.value = []
    } else {
      selectedUsers.value = [item]
    }
  }
}

const handleRemoveSelected = (user: UserItem) => {
  const idx = selectedUsers.value.findIndex((u) => u.id === user.id)
  if (idx >= 0) {
    selectedUsers.value.splice(idx, 1)
  }
}

const handleConfirm = () => {
  emit('confirm', [...selectedUsers.value])
  visible.value = false
}

const handleCancel = () => {
  visible.value = false
  emit('cancel')
}
</script>

<style lang="scss" scoped>
.select-user-modal {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.modal-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.header-btn {
  padding: 0 8px;
  height: 100%;
  display: flex;
  align-items: center;
}

.cancel-btn {
  color: rgba(51, 51, 51, 0.7);
  font-size: 16px;
}

.confirm-btn {
  color: rgb(47, 142, 255);
  font-size: 16px;
}

.header-title {
  font-size: 17px;
  font-weight: 500;
  color: #333;
}

.search-bar {
  background-color: #fff;
  padding: 0 8px;
}

.selected-bar {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 8px 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;

  &--hidden {
    display: none;
  }
}

.selected-label {
  font-size: 13px;
  color: #999;
  flex-shrink: 0;
}

.selected-tags-scroll {
  flex: 1;
  display: flex;
  flex-direction: row;
  white-space: nowrap;
}

.selected-user-tag {
  display: inline-flex;
  flex-direction: row;
  align-items: center;
  padding: 3px 8px;
  margin-left: 6px;
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
  border-radius: 4px;
  flex-shrink: 0;
}

.selected-user-name {
  font-size: 13px;
  color: rgb(47, 142, 255);
}

.selected-user-remove {
  margin-left: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-list {
  flex: 1;
  overflow: hidden;
}

.user-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 12px 16px;
  background-color: #fff;
  border: 1px solid transparent;
  border-bottom-color: #f0f0f0;

  &--selected {
    background-color: #ecf5ff;
    border-color: rgb(47, 142, 255);
  }
}

.user-avatar {
  width: 36px;
  height: 36px;
  margin-right: 12px;
  flex-shrink: 0;
}

.avatar-placeholder {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: rgb(47, 142, 255);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 0;
}

.user-name-row {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.user-name {
  font-size: 15px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-employee-no {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
  flex-shrink: 0;
}

.user-dept {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 80px;
}
</style>
