<template>
  <common-cell :name="name" :required="required" @click="open">
    <view class="form-content__wrapper">
      <view class="flex-main-content truncate" :class="displayText ? '' : 'form__placeholder'">
        {{ displayText || placeholder }}
      </view>
      <view v-if="displayText && !disableChange" class="form-arrow" @click.stop="clear">
        <uni-icons type="closeempty" size="18" color="#bbb" />
      </view>
      <uni-icons class="form-arrow" type="arrowright"></uni-icons>
    </view>
  </common-cell>
</template>

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

const emits = defineEmits(['change']);
const props = defineProps({
  form: { type: Object, default: () => ({}) },
  name: { default: '' },
  required: { type: Boolean, default: false },
  title: { default: '' },
  range: { type: Array, default: () => [] },
  disableChange: { type: Boolean, default: false },
});

const placeholder = computed(() => `请选择${props.name || ''}`);

const value = computed(() => {
  const v = props.form?.[props.title];
  return Array.isArray(v) ? v.map(String).filter(Boolean) : [];
});

const valueToLabel = computed(() => {
  const map = new Map();
  const r = Array.isArray(props.range) ? props.range : [];
  r.forEach((i) => {
    if (typeof i === 'string') map.set(String(i), String(i));
    else if (i && typeof i === 'object') {
      const val = i.value ?? i.id ?? i.key ?? i.label ?? i.name ?? '';
      const label = i.label ?? i.name ?? i.text ?? String(val);
      if (val) map.set(String(val), String(label || val));
    }
  });
  return map;
});

const displayText = computed(() => {
  if (!value.value.length) return '';
  const labels = value.value.map((id) => valueToLabel.value.get(id) || id);
  return labels.join('、');
});

const eventName = `select_tag_${Date.now()}_${Math.random().toString(16).slice(2)}`;

function open() {
  if (props.disableChange) return;
  console.log('[debug][wxapp][tagPicker] open click');
  uni.setStorageSync('ykt_tag_list_selections', value.value);
  const url = `/pages/library/tag-list/tag-list?eventName=${eventName}`;
  uni.navigateTo({
    url,
    fail: (e) => {
      console.error('[debug][wxapp][tagPicker] navigateTo fail:', url, e);
      const msg = e && typeof e === 'object' && e.errMsg ? e.errMsg : '跳转失败';
      uni.showToast({ title: msg, icon: 'none' });
    },
  });
}

function clear() {
  emits('change', { title: props.title, value: [] });
}

onMounted(() => {
  console.log('[debug][wxapp][tagPicker] mounted:', props.title);
  uni.$on(eventName, (data) => {
    const next = Array.isArray(data) ? data.map(String).filter(Boolean) : [];
    emits('change', { title: props.title, value: next });
  });
});

onBeforeUnmount(() => {
  uni.$off(eventName);
});
</script>

<style lang="scss" scoped>
@import '../cell-style.css';

.form-content__wrapper {
  line-height: 42rpx;
}

.flex-main-content {
  line-height: 42rpx;
}
</style>
