<template>
  <div class="mobile-selector">
    <!-- 只读输入框，点击打开选择器 -->
    <!-- <div class="selector-input" @click="openPicker">
      <span class="selector-value" :class="{ 'placeholder': !displayValue }">
        {{ displayValue || placeholder }}
      </span>
      <van-icon name="arrow-down" class="selector-icon" />
    </div> -->
    <van-field :modelValue="modelValue" is-link readonly :label="label" :placeholder="placeholder" :rules="rules" :required="required" @click="showPicker = true" />

    <!-- 移动端弹出层（使用 van-action-sheet + 内部列表） -->
    <van-action-sheet v-model:show="showPicker" :title="dialogTitle" :close-on-click-action="false" round :style="{ maxHeight: '80vh' }" @close="handlePickerClose">
      <div class="picker-content">
        <!-- 已选择提示 -->
        <div class="selected-tip" v-if="tempSelectedItem">已选择路线：{{ tempSelectedItem.routeCode }}</div>

        <!-- 搜索框 -->
        <van-search v-model="searchKeyword" :placeholder="searchPlaceholder" clearable @input="handleSearchInput" @clear="handleSearchClear" />

        <!-- 列表区域 -->
        <van-list v-model:loading="listLoading" :finished="finished" finished-text="没有更多了" @load="onLoadMore" :immediate-check="false">
          <van-cell
            v-for="item in dataList"
            :key="item.routeCode"
            :title="item.routeCode"
            :class="{ 'is-selected': tempSelectedItem?.routeCode === item.routeCode }"
            @click="handleItemClick(item)"
          />
          <van-empty v-if="!listLoading && dataList.length === 0" description="暂无数据" />
        </van-list>
      </div>
    </van-action-sheet>
  </div>
</template>

<script setup>
import { ref, computed, watch, onUnmounted } from 'vue'
import { showToast } from 'vant'
import { request } from '@shared/utils/request'

  // ==================== Props ====================
const props = defineProps({
  // v-model 绑定的值（路线编号）
  modelValue: {
    type: [String, Number],
    default: ''
  },
  label: {
    type: String,
    default: ''
  },
  // 占位符文本
  placeholder: {
    type: String,
    default: '请选择路线'
  },
  // 弹窗标题
  dialogTitle: {
    type: String,
    default: '选择地点路线'
  },
  // 搜索框占位符
  searchPlaceholder: {
    type: String,
    default: '请输入路线编号'
  },
  // 请求接口地址
  apiUrl: {
    type: String,
    default: '/snow-ops-platform/infrastructure-asset/routes'
  },
  // 每页大小（移动端常用固定分页，也可配置）
  pageSize: {
    type: Number,
    default: 20
  },
  // 额外请求参数
  extraParams: {
    type: Object,
    default: () => ({})
  },
  // 搜索防抖延迟时间(ms)
  searchDelay: {
    type: Number,
    default: 500
  },
  // 表单验证规则
  rules: {
    type: Array,
    default: () => []
  },
  // 左上角是否必填标志
  required: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

// ==================== 状态 ====================
const showPicker = ref(false) // 控制弹出层显示
const searchKeyword = ref('') // 搜索关键词
const dataList = ref([]) // 当前已加载的数据列表
const listLoading = ref(false) // 是否正在加载更多
const finished = ref(false) // 是否已加载全部
const currentPage = ref(1) // 当前页码
const total = ref(0) // 总记录数

// 临时选中的数据（确认前暂存，移动端点击即选中并关闭）
const tempSelectedItem = ref(null)

// 防抖定时器
let searchTimer = null

// 显示值：优先显示已确认选中的 routeCode
const displayValue = computed(() => {
  return props.modelValue || ''
})

// 监听外部 modelValue 变化，清空临时选中标记（当外部值改变时）
watch(
  () => props.modelValue,
  (newVal) => {
    if (tempSelectedItem.value && tempSelectedItem.value.routeCode !== newVal) {
      tempSelectedItem.value = null
    }
  }
)

// ==================== API 请求 ====================
// 加载数据（支持分页追加或重置）
const fetchData = async (isReset = true) => {
  if (isReset) {
    // 重置时清空列表，重置页码
    currentPage.value = 1
    dataList.value = []
    finished.value = false
  }

  if (finished.value && !isReset) return

  listLoading.value = true

  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: props.pageSize,
      lxbh: searchKeyword.value || props.modelValue || undefined,
      xzdj: props.extraParams?.xzdj,
      qxid: props.extraParams?.qxid
    }

    const response = await request({
      url: props.apiUrl,
      method: 'get',
      params
    })

    if (response?.code === '00000') {
      const records = response.data.records || []
      total.value = response.data.total || 0

      if (isReset) {
        dataList.value = records
      } else {
        dataList.value = [...dataList.value, ...records]
      }

      // 判断是否已加载全部
      finished.value = dataList.value.length >= total.value
    } else {
      showToast(response.message || '加载失败')
      if (isReset) dataList.value = []
      finished.value = true
    }
  } catch (error) {
    console.error('请求失败:', error)
    showToast('加载失败，请重试')
    if (isReset) dataList.value = []
    finished.value = true
  } finally {
    listLoading.value = false
  }
}

// 加载更多（van-list 的 load 事件）
const onLoadMore = () => {
  if (finished.value) return
  currentPage.value++
  fetchData(false)
}

// 防抖搜索函数
const debouncedSearch = () => {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    // 重置列表并重新加载第一页
    currentPage.value = 1
    fetchData(true)
  }, props.searchDelay)
}

// ==================== 事件处理 ====================
const openPicker = () => {
  showPicker.value = true
  // 打开时重置临时选中状态（基于当前已选中的值）
  if (props.modelValue) {
    tempSelectedItem.value = { routeCode: props.modelValue }
  } else {
    tempSelectedItem.value = null
  }
  // 清空搜索关键词（可选，视需求决定是否保留）
  searchKeyword.value = ''
  // 重置分页并加载数据
  currentPage.value = 1
  fetchData(true)
}

const handlePickerClose = () => {
  showPicker.value = false
  // 清除防抖定时器
  if (searchTimer) clearTimeout(searchTimer)
}

const handleSearchInput = () => {
  debouncedSearch()
}

const handleSearchClear = () => {
  searchKeyword.value = ''
  debouncedSearch()
}

// 点击某一项：立即选中并关闭弹窗
const handleItemClick = (item) => {
  tempSelectedItem.value = item
  // 更新 v-model 值
  emit('update:modelValue', item.routeCode)
  emit('change', item)
  // 关闭选择器
  showPicker.value = false
}

// ==================== 清理定时器 ====================
onUnmounted(() => {
  if (searchTimer) clearTimeout(searchTimer)
})
</script>

<style scoped lang="scss">
.mobile-selector {
  width: 100%;

  .selector-input {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 12px;
    background-color: #f7f8fa;
    border-radius: 8px;
    font-size: 14px;
    line-height: 1.4;
    cursor: pointer;
    transition: background-color 0.2s;
    min-height: 44px; // 移动端触摸区域

    &:active {
      background-color: #ebedf0;
    }

    .selector-value {
      flex: 1;
      color: #323233;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      &.placeholder {
        color: #c8c9cc;
      }
    }

    .selector-icon {
      color: #969799;
      font-size: 16px;
      margin-left: 8px;
    }
  }
}

.picker-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  max-height: 80vh;

  .selected-tip {
    padding: 12px 16px;
    background-color: #f0f9eb;
    color: #67c23a;
    font-size: 13px;
    border-bottom: 1px solid #e9e9e9;
  }

  // 覆盖 van-list 内部样式，让滚动更自然
  :deep(.van-list) {
    flex: 1;
    overflow-y: auto;
  }

  .van-cell {
    font-size: 14px;
    padding: 12px 16px;

    &.is-selected {
      color: #1989fa;
      background-color: #ecf5ff;
    }
  }
}
</style>
