<!--
 * @Author: wjc
 * @Date: 2025-04-11 14:13:23
 * @LastEditors: wjc
 * @LastEditTime: 2026-01-16 14:25:53
 * @Description: 自定义选择器组件
-->
<template>
  <view class="flex items-center" @click="show = true">
    <text v-if="pickerValueDesc" class="text-color-place">
      {{ pickerValueDesc }}
    </text>
    <text v-else class="text-color-place">请选择</text>
    <text class="i-custom-arrow-right wh-16px ml-10px text-color-place" />
  </view>
  <nut-popup v-model:visible="show" :position="position" safe-area-inset-bottom>
    <nut-picker
      v-model="pickerValue"
      :title="title"
      :columns="columns"
      :field-names="fieldNames"
      @confirm="onConfirm"
      @cancel="onCancel"
    />
  </nut-popup>
</template>

<script setup lang="ts">
  import type { PickerBaseEvent, PickerOption } from 'nutui-uniapp'

  defineOptions({
    name: 'MPicker',
    options: {
      styleIsolation: 'shared',
      virtualHost: true,
    },
  })
  const props = withDefaults(
    defineProps<{
      columns: (PickerOption | PickerOption[])[]
      fieldNames?: any
      position?: any
      title?: string
    }>(),
    {
      position: 'bottom',
      title: '',
      // columns: [],
      fieldNames: {
        text: 'label',
        value: 'value',
        children: 'children',
      },
    }
  )
  const emits = defineEmits<{
    (e: 'confirm'): void
    (e: 'cancel'): void
  }>()

  const pickerValue = ref([])
  const pickerValueDesc = ref('')

  /** v-model 绑定值，将pickerValue的值处理为字符串 */
  const modelValue = defineModel<number | string>()
  watch(
    () => modelValue.value,
    (val) => {
      console.log('2431--')
      if (val) {
        pickerValue.value = [val]
        const cur = props.columns.find((item: PickerOption) => item.value === val)
        if (cur) {
          pickerValueDesc.value = cur[props.fieldNames.text]
        }
      }
    }
  )

  const show = ref(false)
  const onConfirm = ({ selectedValue, selectedOptions }: PickerBaseEvent) => {
    pickerValueDesc.value = selectedOptions
      .map((item: PickerOption) => item[props.fieldNames.text])
      .join(',')
    // TODO: 多维数组要额外处理
    modelValue.value = selectedValue.pop()
    emits('confirm')
    show.value = false
  }
  const onCancel = () => {
    show.value = false
    emits('cancel')
  }

  onMounted(() => {
    const cur = props.columns.find((item: PickerOption) => item.value === modelValue.value)
    if (cur) {
      pickerValueDesc.value = cur[props.fieldNames.text]
    }
  })
</script>
