<template>
  <!-- 编辑模式 -->
  <view v-if="mode === 'edit'" class="location-picker-wrapper">
    <!-- 显示输入框 -->
    <view class="input-display" @click="showPicker = true">
      <text class="input-text" :class="{ placeholder: !displayLabel }">
        {{ displayLabel || placeholder }}
      </text>
      <view class="suffix-icons">
        <view 
          v-if="innerValue && displayLabel"
          @click.stop="clearAddress"
          class="clear-btn"
        >
          <text class="clear-icon">×</text>
        </view>
        <text class="arrow-icon">></text>
      </view>
    </view>

    <!-- 选择器弹窗 -->
    <uni-data-picker
      v-model="innerValue"
      :localdata="localData"
      :popup-title="popupTitle"
      :show="showPicker"
      @change="onChange"
      @popupopened="onPopupOpened"
      @popupclosed="onPopupClosed"
    />
  </view>

  <!-- 展示模式：纯文本 -->
  <text v-else class="location-text">
    {{ displayLabel || "无" }}
  </text>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import cityRows from '@/utils/data.json'

// Props definition
const props = defineProps({
  mode: {
    type: String,
    default: "edit"
  },
  modelValue: {
    type: [String, Number],
    default: ""
  },
  placeholder: {
    type: String,
    default: "请选择省市区"
  },
  popupTitle: {
    type: String,
    default: "请选择省市区"
  }
})

// Emits definition
const emit = defineEmits(['update:modelValue', 'clear'])

// Reactive data
const innerValue = ref(props.modelValue)
const localData = ref([])
const displayLabel = ref('')
const showPicker = ref(false)

// Watchers
watch(() => props.modelValue, (newVal) => {
  console.log('[LocationPicker] props.modelValue 变化:', newVal)
  innerValue.value = newVal
  updateDisplayLabel(newVal)
})

watch(innerValue, (newVal) => {
  console.log('[LocationPicker] innerValue 变化:', newVal)
  emit("update:modelValue", newVal)
})

// Methods
const onPopupOpened = () => {
  console.log('[LocationPicker] 弹窗打开')
}

const onPopupClosed = () => {
  console.log('[LocationPicker] 弹窗关闭')
  showPicker.value = false
}

const onChange = (e) => {
  console.log('[LocationPicker] onChange 事件:', e)
  
  if (e && e.detail && e.detail.value && e.detail.value.length > 0) {
    const selectedNodes = e.detail.value
    const lastNode = selectedNodes[selectedNodes.length - 1]
    
    console.log('[LocationPicker] 选择的节点:', selectedNodes)
    console.log('[LocationPicker] 最后节点:', lastNode)
    
    // 更新值
    innerValue.value = lastNode.value
    
    // 构建显示文本
    const pathLabels = selectedNodes.map(node => node.text)
    displayLabel.value = pathLabels.join(' - ')
    
    console.log('[LocationPicker] 更新后 - code:', lastNode.value, 'label:', displayLabel.value)
    
    // 关闭弹窗
    showPicker.value = false
  }
}

const clearAddress = () => {
  console.log('[LocationPicker] 清空地址')
  innerValue.value = ""
  displayLabel.value = ""
  emit("update:modelValue", "")
  emit("clear")
}

const updateDisplayLabel = (value) => {
  if (!value) {
    displayLabel.value = ""
    return
  }
  
  const label = getLocationLabel(value)
  displayLabel.value = label
  console.log('[LocationPicker] 更新显示标签:', label)
}

const getLocationLabel = (value) => {
  if (!value) return ""
  
  let label = ""
  
  const traverse = (nodes, path = []) => {
    for (const node of nodes) {
      const currentPath = [...path, node.text]
      
      // 使用 == 而不是 === 以支持字符串和数字比较
      if (node.value == value) {
        label = currentPath.join(' - ')
        return true
      }
      
      if (node.children && node.children.length > 0) {
        if (traverse(node.children, currentPath)) {
          return true
        }
      }
    }
    return false
  }
  
  traverse(localData.value)
  return label
}

const get_city_tree = () => {
  if (!cityRows || cityRows.length === 0) {
    console.warn('[LocationPicker] cityRows 数据为空')
    return []
  }
  return handleTree(cityRows)
}

const handleTree = (data, parent_code = null) => {
  let res = []
  let keys = {
    id: "code",
    pid: "parent_code",
    children: "children",
    text: "name",
    value: "code"
  }

  for (let item of data) {
    if (parent_code === null) {
      if (!item.hasOwnProperty(keys.pid) || item[keys.pid] == parent_code) {
        let node = {
          text: item[keys.text],
          value: item[keys.value],
          children: handleTree(data, item[keys.id])
        }
        res.push(node)
      }
    } else {
      if (item.hasOwnProperty(keys.pid) && item[keys.pid] == parent_code) {
        let node = {
          text: item[keys.text],
          value: item[keys.value],
          children: handleTree(data, item[keys.id])
        }
        res.push(node)
      }
    }
  }
  return res
}

// Initialize
localData.value = get_city_tree()
console.log('[LocationPicker] 初始化 - localData 长度:', localData.value.length)
console.log('[LocationPicker] 初始化 - modelValue:', props.modelValue)

updateDisplayLabel(props.modelValue)
</script>

<style scoped>
.location-picker-wrapper {
  width: 100%;
}

.input-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  min-height: 44rpx;
  padding: 12rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.input-text {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  line-height: 44rpx;
}

.input-text.placeholder {
  color: #999;
}

.suffix-icons {
  display: flex;
  align-items: center;
  gap: 8rpx;
  flex-shrink: 0;
}

.clear-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32rpx;
  height: 32rpx;
}

.clear-icon {
  font-size: 32rpx;
  color: #999;
  line-height: 1;
}

.arrow-icon {
  font-size: 24rpx;
  color: #999;
}

.location-text {
  font-size: 28rpx;
  color: #333;
}
</style>
