<template>
  <picker mode="selector" :range="displayRange" :disabled="disableChange" @change="change($event)">
    <common-cell :name="name" :required="required">
      <view class="form-content__wrapper">
        <view class="flex-main-content truncate" :class="valueLabel ? '' : 'form__placeholder'">
          {{ valueLabel || placeholder }}
        </view>
        <uni-icons class="form-arrow" type="arrowright"></uni-icons>
      </view>
    </common-cell>
  </picker>
</template>

<script setup>
import { computed } from 'vue';
import commonCell from '../common-cell.vue';

const emits = defineEmits(['change']);
const props = defineProps({
  form: { type: Object, default: () => ({}) },
  name: { default: '' },
  range: { type: Array, default: () => [] }, // 支持 string[] 或 {label,value,image}[]
  required: { type: Boolean, default: false },
  disableChange: { type: Boolean, default: false },
  title: { default: '' },
});

function normalizeOptions(options) {
  if (!Array.isArray(options)) return [];
  if (!options.length) return [];
  if (typeof options[0] === 'string') return options.filter(Boolean).map((i) => ({ label: String(i), value: String(i) }));
  return options
    .map((i) => {
      const label = i?.label ?? i?.name ?? i?.text ?? i?.title ?? '';
      const value = i?.value ?? i?.id ?? i?.key ?? label;
      if (!label && (value === undefined || value === null || value === '')) return null;
      return { label: String(label || value), value: String(value) };
    })
    .filter(Boolean);
}

const options = computed(() => normalizeOptions(props.range));
const placeholder = computed(() => `请选择${props.name || ''}`);
const displayRange = computed(() => options.value.map((i) => i.label));

const rawValue = computed(() => {
  const v = props.form?.[props.title];
  return v === undefined || v === null ? '' : String(v);
});
const valueLabel = computed(() => {
  if (!rawValue.value) return '';
  const found = options.value.find((i) => String(i.value) === rawValue.value);
  return found ? found.label : rawValue.value;
});

function change(e) {
  const idx = Number(e?.detail?.value || 0);
  const picked = options.value[idx];
  emits('change', { title: props.title, value: picked ? picked.value : '' });
}
</script>

<style scoped>
@import '../cell-style.css';
</style>
