<template>
  <div>
    <div class="d-flex align-items-center">
      <div class="grid-item-text" @click="showPicker">{{ name }}</div>
      <van-icon name="close" v-if="name !== initialName" @click="clearName" />
      <van-icon name="arrow-down" v-else @click="showPicker" />
    </div>
    <van-popup v-model:show="showPickerFlag" position="bottom">
      <van-field v-model="searchValue" :placeholder="'请输入' + initialName" @input="onSearchInput" />
      <van-picker show-toolbar :title="initialName + '列表'" :columns="list" @confirm="onConfirm"
        @cancel="showPickerFlag = false" />
    </van-popup>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
let showPickerFlag = ref(false)
let name: any = ref('')
let popupValue: any = ref('')
let searchValue = ref('')
let list: any = ref([])
let prop = defineProps({
  type: String,
  initialName: String,
  selectName: String,
  selectValue: String,
  other: String
})

onMounted(() => {
  nextTick(() => {
    name.value = prop.selectName
    popupValue.value = prop.selectValue
  })
})


const showPicker = () => {
  searchValue.value = name.value === prop.initialName ? '' : prop.type === 'cus' ? name.value : popupValue.value
  list.value = name.value === prop.initialName ? [] : [{
    text: name.value,
    value: popupValue.value
  }]
  showPickerFlag.value = true
}

import { stockStockInfoLookUp, cusInfoLookUp } from '@/utils/api'
import { debounceThrottle } from '@/mixins/debounce-throttle'
const { throttle } = debounceThrottle()
const onSearchInput = throttle(
  async () => {
    if (searchValue.value) {
      if (prop.type === 'stock') {
        const { data } = await stockStockInfoLookUp({ stockCode: searchValue.value })
        list.value = data.map((ele: any) => {
          ele.text = `${ele.stockCode}【${ele.stockName}】`
          ele.value = ele.stockCode
          return ele
        })
      } else if (prop.type === 'cus') {
        const { data } = await cusInfoLookUp({ cusName: searchValue.value })
        list.value = data.map((ele: any) => {
          ele.text = ele.cusName
          ele.value = ele.cusId
          return ele
        })
      }
    } else {
      list.value = []
    }
  },
  500
)

const clearName = () => {
  name.value = prop.initialName
  popupValue.value = ''
  emit('refresh', { value: popupValue.value, name: name.value })
}

const onConfirm = (e: any) => {
  console.log(e)
  popupValue.value = e.selectedIndexes > -1 ? e.selectedOptions[0].value : ''
  name.value = e.selectedIndexes > -1 ? e.selectedOptions[0].text : prop.initialName
  showPickerFlag.value = false
  emit('refresh', { value: popupValue.value, name: name.value })
}
const emit = defineEmits(['refresh'])
</script>
<style lang="scss"></style>