<template>
  <view class="page-container">
    <NavBar :title="pageTitle" />

    <view class="search-bar">
      <view class="search-input-wrap">
        <text class="search-icon iconfont icon-search"></text>
        <input
          v-model="searchText"
          class="search-input"
          type="text"
          :placeholder="t('moldRepair.placeholderUserSearch')"
          placeholder-class="search-placeholder"
          confirm-type="search"
          @input="onSearchInput"
          @confirm="loadUsers"
        />
        <text v-if="searchText" class="search-clear" @click="clearSearch">x</text>
      </view>
    </view>

    <scroll-view v-if="userList.length > 0" scroll-y class="user-list">
      <view
        v-for="user in userList"
        :key="user.id"
        class="user-card"
        :class="{ active: String(selectedId) === String(user.id) }"
        @click="selectedId = user.id"
      >
        <text class="user-name">{{ textValue(user.nickname) }}</text>
        <view class="user-meta">
          <text class="user-meta-text">ID: {{ textValue(user.id) }}</text>
          <text v-if="user.deptName" class="user-meta-divider">|</text>
          <text v-if="user.deptName" class="user-meta-text">{{ textValue(user.deptName) }}</text>
        </view>
      </view>
    </scroll-view>

    <view v-else class="empty-wrap">
      <text v-if="loading" class="empty-text">{{ t('functionCommon.loading') }}</text>
      <text v-else class="empty-text">{{ t('moldRepair.noUserData') }}</text>
    </view>

    <view class="bottom-actions">
      <view class="bottom-btn confirm-btn" @click="handleConfirm">
        {{ t('functionCommon.confirm') }}
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import NavBar from '@/components/common/NavBar.vue'
import { getSimpleUserList } from '@/api/system/user'

const { t } = useI18n()

const field = ref('acceptedBy')
const selectedId = ref('')
const searchText = ref('')
const userList = ref([])
const loading = ref(false)
const fromSource = ref('moldRepair')  // moldRepair | sparepartInbound | sparepartOutbound | materialInbound | materialOutbound
let searchTimer = null

const pageTitle = computed(() => {
  if (field.value === 'operator') return '选择经办人'
  return field.value === 'confirmBy' ? t('moldRepair.confirmBy') : t('moldRepair.acceptedBy')
})

onLoad(async (options) => {
  field.value = String(options?.field || 'acceptedBy')
  selectedId.value = String(options?.selectedId || '')
  fromSource.value = String(options?.from || 'moldRepair')
  await loadUsers()
})

function onSearchInput() {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    loadUsers()
  }, 300)
}

function clearSearch() {
  searchText.value = ''
  loadUsers()
}

async function loadUsers() {
  if (searchTimer) {
    clearTimeout(searchTimer)
    searchTimer = null
  }
  loading.value = true
  try {
    const nickname = searchText.value.trim()
    const res = await getSimpleUserList({
      nickname: nickname || undefined
    })
    const root = res && res.data !== undefined ? res.data : res
    const data = Array.isArray(root) ? root : (Array.isArray(root?.data) ? root.data : [])
    userList.value = Array.isArray(data) ? data : []
  } catch (error) {
    userList.value = []
  } finally {
    loading.value = false
  }
}

function handleConfirm() {
  if (!selectedId.value) {
    uni.showToast({ title: t('moldRepair.validatorUserRequired'), icon: 'none' })
    return
  }
  const user = userList.value.find((item) => String(item.id) === String(selectedId.value))
  if (!user) {
    uni.showToast({ title: t('moldRepair.validatorUserRequired'), icon: 'none' })
    return
  }
  // 根据来源使用不同的 globalData key
  const keyMap = {
    sparepartInbound: '_sparepartInboundUserSelectResult',
    sparepartOutbound: '_sparepartOutboundUserSelectResult',
    materialInbound: '_materialInboundUserSelectResult',
    materialOutbound: '_materialOutboundUserSelectResult',
    productInbound: '_productInboundUserSelectResult',
    productOutbound: '_productOutboundUserSelectResult',
    productCheck: '_productCheckUserSelectResult'
  }
  const key = keyMap[fromSource.value] || '_moldRepairUserSelectResult'
  getApp().globalData[key] = {
    field: field.value === 'confirmBy' ? 'confirmBy' : 'acceptedBy',
    user
  }
  uni.navigateBack()
}

function textValue(value) {
  if (value === 0) return '0'
  if (value === null || value === undefined) return '-'
  const text = String(value).trim()
  return text || '-'
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: #f5f6f8;
  padding-bottom: 140rpx;
}

.search-bar {
  padding: 16rpx 24rpx;
  background: #fff;
}

.search-input-wrap {
  display: flex;
  align-items: center;
  height: 72rpx;
  padding: 0 16rpx;
  background: #f5f6f8;
  border-radius: 36rpx;
}

.search-icon {
  font-size: 32rpx;
  color: #999;
  margin-right: 12rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.search-placeholder {
  color: #bbb;
}

.search-clear {
  font-size: 28rpx;
  color: #999;
  padding: 8rpx;
}

.user-list {
  padding: 16rpx 24rpx;
}

.user-card {
  background: #fff;
  border-radius: 14rpx;
  padding: 28rpx 24rpx;
  margin-bottom: 16rpx;
  border: 2rpx solid transparent;

  &.active {
    border-color: #2563eb;
    background: #f0f5ff;
  }
}

.user-name {
  font-size: 30rpx;
  font-weight: 700;
  color: #1a1a1a;
}

.user-meta {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-top: 10rpx;
}

.user-meta-text {
  font-size: 24rpx;
  color: #7a8494;
  line-height: 1.3;
}

.user-meta-divider {
  font-size: 22rpx;
  color: #c3cad5;
}

.empty-wrap {
  padding: 120rpx 0;
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.bottom-actions {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 18rpx 24rpx calc(18rpx + env(safe-area-inset-bottom));
  background: #fff;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
  z-index: 99;
}

.bottom-btn {
  width: 100%;
  height: 84rpx;
  line-height: 84rpx;
  text-align: center;
  border-radius: 16rpx;
  font-size: 30rpx;
  font-weight: 600;
}

.confirm-btn {
  background: #1f4b79;
  color: #fff;
}
</style>
