<template>
  <view class="row" @click="open">
    <view class="left">
      <text class="label">{{ name }}</text>
      <text v-if="required" class="required">*</text>
    </view>
    <view class="right">
      <view class="value" :class="{ muted: !displayText }">{{
        displayText || placeholder
      }}</view>
      <uni-icons type="arrowright" size="16" color="#999" />
    </view>
  </view>
</template>

<script setup>
import { computed, onUnmounted, ref } from "vue";

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

const placeholder = computed(() =>
  props.placeholder ? String(props.placeholder) : `请选择${props.name || ""}`
);
const rawValue = computed(() => props.form?.[props.title]);
const displayText = computed(() => {
  const v = rawValue.value;
  if (Array.isArray(v))
    return v
      .filter((i) => i !== null && i !== undefined && String(i).trim())
      .join("，");
  return v ? String(v) : "";
});

const activeEventName = ref("");
function clearListener() {
  if (activeEventName.value) uni.$off(activeEventName.value);
  activeEventName.value = "";
}
onUnmounted(clearListener);

function open() {
  if (props.disableChange) return;
  clearListener();
  activeEventName.value = `diagnosis-change_${Date.now()}`;
  uni.$on(activeEventName.value, (data) => {
    emits("change", { title: props.title, value: data });
  });

  if (props.mult) {
    const cur = Array.isArray(rawValue.value) ? rawValue.value : [];
    uni.setStorageSync("diagnosis-list-selection", cur);
  }

  uni.navigateTo({
    url: `/pages/library/diagnosis-list?eventName=${encodeURIComponent(
      activeEventName.value
    )}&mult=${props.mult ? "YES" : "NO"}&value=${encodeURIComponent(
      displayText.value || ""
    )}`,
  });
}
</script>

<style scoped>
.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 28rpx;
  border-bottom: 2rpx solid #eee;
}
.left {
  display: flex;
  align-items: center;
  gap: 12rpx;
}
.label {
  font-size: 30rpx;
  color: #111827;
  font-weight: 700;
}
.required {
  color: #ff4d4f;
  font-size: 30rpx;
}
.right {
  display: flex;
  align-items: center;
  gap: 16rpx;
  min-width: 240rpx;
  justify-content: flex-end;
}
.value {
  font-size: 30rpx;
  color: #111827;
  max-width: 440rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.muted {
  color: #9aa0a6;
}
</style>
